Mock toLocaleString in Jest
01-February-2017
2 minutes read
tech javascript

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 }; helpers.formatDate(mockDate); 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()

Share
Like
profile-image
Prasanna is a full stack web developer, with exposure to various programming languages. Uses mostly Java, Javascript these days and got ~13 years of architecting and coding enterprise software solutions.