简体   繁体   中英

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);

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM