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

514
Views
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 answers
Answer question

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 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!