Skip to content
Advertisement

Can’t mock the navigator.language

I’m currently adding unit test for some of shard utils functions. I’m kinda new to unit testing. Currently having hard time to mock some global object. Is there any way to mock/update value of navigator.language? It is always returning en-US. I tried the Object.defineProperty and different jest mock objects. Didn’t work.

The thing is, if I console.log(navigator.language) in the test, it will show me mocked value, but util function is not seeing that value.

Here is the code.

//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 exact response language if there is one', () => {
    jest.spyOn(navigator, 'language', 'get').mockImplementation(() => 'en-fr');
    expect(getLang()).toBe('en-fr');
  });



  // Successful - passing
  it('should return 1st language if there 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",

Advertisement

Answer

Your getLang function requires that you mock both navigator.languages and navigator.language.

In your case, you’d have to mock navigator.languages to return undefined or null to test that it("returns navigator.language when navigator.languages is undefined"

User contributions licensed under: CC BY-SA
8 People found this is helpful
Advertisement