3

I'm new to unit testing with JS so apologies if I'm missing something obvious.

I need to mock the navigator.mediaDevices.getUserMedia method for some tests, so have defined the following in setupTests.js:

const mockMedia = {
    getUserMedia: jest.fn().mockImplementation(() =>
        Promise.resolve(
            "stream"
        ))
}
global.navigator.mediaDevices = mockMedia

This works as expected when testing in the same file:

navigator.mediaDevices.getUserMedia({video:true})
    .then((stream => console.log(stream)))

But when testing in my component I get TypeError: Cannot read property 'then' of undefined with the same code.

If I don't try and call the mocked function it appears to exist:

console.log(navigator.mediaDevices)

    {
      getUserMedia: [Function: mockConstructor] { ... }
    }

But calling results in undefined

What am I missing here and thanks in advance

Tom Haines
  • 123
  • 3
  • 9

1 Answers1

0

It could be because of CRA having resetMocks default to true.

It is explained in this other question.

Here the proposal to revert that default value in CRA.