I'm currently in the process of writing unit tests for some of my shared utility functions. As someone who is relatively new to unit testing, I am encountering difficulties when trying to mock certain global objects. Specifically, I am struggling to find a way to mock or update the value of navigator.language
, as it always returns en-US
. I have attempted to use Object.defineProperty and various Jest mock objects, but without success.
The interesting thing is that if I use console.log(navigator.language)
within the test, the mocked value is displayed. However, the utility function does not seem to recognize this value.
Here is the code snippet:
//utils.js
export function getLang() {
if (navigator.languages) return navigator.languages[0];
return navigator.language;
}
//utils.spec.ts
describe('Navigator', () => {
afterEach(() => {
jest.restoreAllMocks();
});
//Error - Failing
it('should return the exact language response if there is one', () => {
jest.spyOn(navigator, 'language', 'get').mockImplementation(() => 'en-fr');
expect(getLang()).toBe('en-fr');
});
// Successful - passing
it('should return the first language if there is an array of languages', () => {
jest
.spyOn(navigator, 'languages', 'get')
.mockImplementation(() => ['en-fr', 'en-US', 'en']);
expect(getLang()).toBe('en-fr');
});
});
Expected: "en-fr"
Received: "en-US"
25 | jest.spyOn(navigator, 'language', 'get').mockImplementation(() => 'en-fr');
26 | const lang = getLang();
> 27 | expect(lang).toBe('en-fr');
| ^
28 | });
//package.json:
"jest": "^27.5.1",