I have a test file and am testing for the formatCurrency
function. The problem, even though I've mocked window.navigator.language
to be en-GB
my function in test doesn't format the currency in £
. In the UI it works as expected, but in jest looks like you can't change window.navigator.language
. Any suggestions?
const languageCurrency = {
"en-GB": "GBP",
"en-US": "USD",
};
const userLanguage = window.navigator.language
export const formatCurrency = (value) =>
Intl.NumberFormat(userLanguage, {
style: "currency",
currency: languageCurrency[userLanguage],
}).format(value);
and here is my test file
import { formatCurrency } from "./formatCurrency";
describe("given formatCurrency fucntion", () => {
let windowSpy;
beforeEach(() => {
windowSpy = jest.spyOn(window, "window", "get");
});
afterEach(() => {
windowSpy.mockRestore();
});
it("should set the user language to `en-GB`", () => {
windowSpy.mockImplementation(() => ({
navigator: {
language: "en-GB",
},
}));
expect(window.navigator.language).toBe("en-GB"); //this will pass
expect(formatCurrency(1000)).toBe("£1000.00"); // this fails
});
});
Since the
userLanguage
variable is assigned in the module scope. You should mockwindow.navigator.language
first, then import the module. So that theuserLanguage
variable will be assigned with the mock value.Note: The code defined in the module scope will be executed immediately when you import the module.
Besides, the formatted currency should be
'£1,000.00'
E.g.
formatCurrency.ts
:formatCurrency.test.ts
:Test result: