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

515
Vistas
Mock navigator object in React testing library

I'm using navigator to detect the camera settings in the browser. Below is excerpt from my React component.

  navigator.mediaDevices
    .getUserMedia({ video: true })
    .then(() => {
      setError(false);
    })
    .catch((e) => {
      if (e) {
        setError(true);
      }
    });

I have mocked the navigator object in my setupTests.js file

global.navigator.mediaDevices = {
  getUserMedia: jest.fn().mockImplementation(() => Promise.resolve()),
};

I would still get this error that says 'then' of undefined. Could anyone please help?

    TypeError: Cannot read property 'then' of undefined

      51 |   const [error, setError] = useState(false);
      52 |
    > 53 |   navigator.mediaDevices
         |   ^
      54 |     .getUserMedia({ video: true })
      55 |     .then(() => {
      56 |       setError(false);
about 4 years ago · Juan Pablo Isaza
1 Respuestas
Responde la pregunta

0

Figured out the issue myself. I had to create a mock file and import it in my test cases.

Created a mock file with the below code __mocks__/navigator.js

const mockMediaDevices = {
  getUserMedia: jest.fn().mockResolvedValueOnce('fake data'),
};

Object.defineProperty(navigator, 'mediaDevices', {
  writable: true,
  value: mockMediaDevices,
});

In my test file, I imported the mock navigator file.

import __mocks__/navigator';

navigator.mediaDevices.getUserMedia = () => {
  return new Promise((resolve) => {
    resolve();
  });
};

it('should test something', () => {  
   ...
})
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