I am trying to write jest tests for a function, that writes a set of numbers to the clipboard. The important point is that this function should use the current language settings from the browser, i.e. for US culture settings I want a "." as decimal seperator, for German settings I want a ",". Hence, I am internally using ".toLocaleString()".
Now running my test using Node v14, it looks like node is using the culture settings of the machine it is running on. Let's take a look at a simplified version:
const convertNumber = (value: number) => {
return value.toLocaleString();
};
describe("Convert numbers using toLocaleString", () => {
it("can respect decimal seperator", () => {
const value = 3.14;
expect(convertNumber(value)).toBe("3.14");
});
});
Running that tests on a windows machine with US culture settings is successful, running it on a machine with German culture settings fails as it converts the number to "3,14" (thus, the full-icu is there as it is correctly converting to German format).
I assume that it should someone be possible to tell node which language settings to use instead of using the machine settings. Ideally, I would like to define one test with US culture settings and one with German settings to ensure that the method can handle both versions.
So far I am stuck with using ".toLocaleString()" in my test as well to check the return value (to ensure at least that I can run the test on any machine)
expect(convertNumber(value)).toBe(value.toLocaleString());
but I would prefer to test against a hardcoded string to check that the converion happens correctly. I assume it should somehow be possible to mock/define the Intl.NumberSettings object to use a specific culture, but I can't seem to figure out how.
Any input would be greatly appreciated.
Edit: Concerning the comment of @k0pernikus: I am running jest using "react-scripts test" (created with create-react-app v3.4.3). I tried to experiement with the environment variables you mentioned:
const environmentVariableLang = env.LANG || env.LANGUAGE || env.LC_ALL || env.LC_MESSAGES;
const navigatorLang = navigator.language;
const actualLocale = Intl.DateTimeFormat().resolvedOptions().locale;
Turns out that environmentVariableLange = 'en_US.UTF-8' (coming from env.LANG, the others are undefined), navigatorLang = 'en-US' but still the actualLocale resolves to 'de-DE'.