Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

102
Views
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",
about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

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"

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!