Company logo
  • Jobs
  • Bootcamp
  • About Us
  • For professionals
    • Home
    • Jobs
    • Courses
    • Questions
    • Teachers
    • Bootcamp
  • For business
    • Home
    • Our process
    • Plans
    • Assessments
    • Payroll
    • Blog
    • Calculator

0

375
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);
7 months 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', () => {  
   ...
})
7 months 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 job Plans Our process Sales
Legal
Terms and conditions Privacy policy
© 2023 PeakU Inc. All Rights Reserved.