Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

516
Visualizações
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 Respostas
Responde à pergunta

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda