When running my unit tests with Jest, I encountered an error:
TypeError: Cannot read properties of undefined (reading 'getVideoTracks')
Does anyone have any suggestions on how to properly test the following line using Jest?
[videoTrack] = (await navigator.mediaDevices.getUserMedia({video: true})).getVideoTracks();
This is a snippet from my unit test file:
import { Track } from './Track';
import { } from '../index';
const mockMediaDevices = {
getUserMedia: jest.fn()
};
Object.defineProperty(window.navigator, 'mediaDevices', {
writable: true,
value: mockMediaDevices,
});
Object.defineProperty(navigator.mediaDevices.getUserMedia, 'getVideoTracks', {
writable: true,
value: jest.fn(),
});
describe('Track', () => {
describe('applyConstraints()', () => {
let track: Track;
let videoTrack: MediaStreamTrack;
beforeEach(async () => {
[videoTrack] = (await navigator.mediaDevices.getUserMedia({ video: true })).getVideoTracks();
track = new Track(videoTrack as MediaStreamTrack);
});
it('should have applyConstraints method', () => {
expect(typeof track.applyConstraints).toEqual('function');
});
});
});
Here is the detailed error message:
TypeError: Cannot read properties of undefined (reading 'getVideoTracks')
67 |
68 | beforeEach(async () => {
> 69 | [videoTrack] = (await navigator.mediaDevices.getUserMedia({video: true})).getVideoTracks();
| ^
70 | track = new Track(videoTrack as MediaStreamTrack);
71 | });
72 |
at Object.<anonymous> (Media/Track/Track.test.ts:69:81)
I also attempted the following code:
const mockMediaDevices = {
getUserMedia: jest.fn().mockReturnValue({ getVideoTracks: jest.fn() })
};
Object.defineProperty(navigator, 'mediaDevices', {
writable: true,
value: mockMediaDevices,
});
However, this resulted in another error:
TypeError: undefined is not iterable (cannot read property Symbol(Symbol.iterator))
73 |
74 | beforeEach(async () => {
> 75 | [videoTrack] = (await navigator.mediaDevices.getUserMedia({video: true})).getVideoTracks();