这个
navigator.mediaDevices
不是由JSDOM实现的。所以
window.navigator.mediaDevices
是
undefined
这就是你出错的原因。看看
Mocking methods which are not implemented in JSDOM
.
解决方案是:
device.ts
:
export default class Devices {
public static connectAudioDevice(device?: InputDeviceInfo): Promise<MediaStream> {
return new Promise<MediaStream>((resolve, reject) => {
navigator.mediaDevices
.getUserMedia({ audio: true })
.then((stream) => {
resolve(stream);
})
.catch((error) => {
resolve(error);
});
});
}
}
device.test.ts
:
import devices from './deivce';
describe('65112057', () => {
test('Resolves with valid audio mediaStream', async () => {
const mockMediaDevices = {
getUserMedia: jest.fn().mockResolvedValueOnce('fake data' as any),
};
Object.defineProperty(window.navigator, 'mediaDevices', {
writable: true,
value: mockMediaDevices,
});
const actual = await devices.connectAudioDevice();
expect(actual).toBe('fake data');
expect(mockMediaDevices.getUserMedia).toBeCalledWith({ audio: true });
});
});
单元测试结果:
PASS src/stackoverflow/65112057/device.test.ts
65112057
â Resolves with valid audio mediaStream (7ms)
-----------|----------|----------|----------|----------|-------------------|
File | % Stmts | % Branch | % Funcs | % Lines | Uncovered Line #s |
-----------|----------|----------|----------|----------|-------------------|
All files | 80 | 100 | 75 | 80 | |
deivce.ts | 80 | 100 | 75 | 80 | 10 |
-----------|----------|----------|----------|----------|-------------------|
Test Suites: 1 passed, 1 total
Tests: 1 passed, 1 total
Snapshots: 0 total
Time: 4.994s, estimated 13s