Mock toLocaleString in Jest

PhantomJS doesn't support multiple locale. Here is a way to mock them in tests.

Wed, 01 Feb 2017

We had to use toLocaleString with a specific country-code. toLocaleString('de'). This works perfectly in all the browsers. However, not in jest tests.

Our Jest tests were running with --env=jsdom I got to know that jsdom and phantomJS aren’t supporting multiple locale implementations.

PhantomJS support locale-specific.

So, the only solution I found is to mock these methods and test rest of the logic. Here is a sample mock behaviour.

import * as helpers from '../src/helpers';
describe('formatDate', () => {
it('should invoke localString implementation to format date ', () => {
    const localStringMock = jest.fn();
    const mockDate = { toLocaleString: localStringMock };
    expect(localStringMock).toHaveBeenCalledWith('de-DE', {
            year: 'numeric',
            month: '2-digit',
            day: '2-digit',
            hour: '2-digit',
            minute: '2-digit',

Note: This behaviour is applicable for toLocaleDateString() toLocaleTimeString()


Prasanna is a full stack web developer, with exposure to various programming languages. Uses mostly Java, Javascript these days and got 11+ years of architecting and coding enterprise software solutions.

  • rants and writings through personal experience