Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

106
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda