jest TypeError: undefined is not iterable

jest TypeError: undefined is not iterable

我在 运行 我的单元测试中使用 jest,但出现错误。

TypeError: Cannot read properties of undefined (reading 'getVideoTracks')

关于如何在 jest 中测试以下行的任何建议

[videoTrack] = (await navigator.mediaDevices.getUserMedia({video: true})).getVideoTracks();

我的单元测试文件-

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

详细错误 -

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)

我试过这个代码 -

const mockMediaDevices = {
  getUserMedia: jest.fn().mockReturnValue({ getVideoTracks: jest.fn() })
};
Object.defineProperty(navigator, 'mediaDevices', {
  writable: true,
  value: mockMediaDevices,
});

但这给出了一个错误-

TypeError: undefined is not iterable (cannot read property Symbol(Symbol.iterator))

      73 |
      74 |     beforeEach(async () => {
    > 75 |       [videoTrack] = (await navigator.mediaDevices.getUserMedia({video: true})).getVideoTracks();

尝试更改此代码:

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(),
});

到(已编辑 v2)

const mockMediaDevices = {
  getUserMedia: () => Promise.resolve({
    getVideoTracks: () => [jest.fn()],
  }),
};

Object.defineProperty(window.navigator, 'mediaDevices', {
  writable: true,
  value: mockMediaDevices,
});


beforeEach(async () => {
  const stream = await navigator.mediaDevices.getUserMedia({ video: true });
  [videoTrack] = stream.getVideoTracks();
  track = new Track(videoTrack as MediaStreamTrack);
});

因为当您破坏 getVideoTracks() 结果时,您选择了 0 索引处的元素。但是 jest.fn() 不是一个可以被破坏为 [videoTrack] = (await ....

的数组