【发布时间】:2021-03-20 19:25:08
【问题描述】:
我有一个需要使用 navigator.mediaDevices 的测试,但我无法让任何模拟正常工作。
我正在使用create-react-app。
这是我的测试:
import getConnectedDevices from "./getConnectedDevices";
describe("getConnectedDevices", () => {
it("Should work", () => {
console.log(navigator); // Navigator {}
console.log(navigator.mediaDevices); // undefined
});
});
我尝试添加一个模拟,因为它声明 here in the jest documentation
// tests/navigator.mock
Object.defineProperty(window, "navigator", {
writable: true,
value: {
mediaDevices: {
enumerateDevices: jest.fn(),
},
},
});
import "../../tests/navigator.mock"; // <- Mock added
import getConnectedDevices from "./getConnectedDevices";
describe("getConnectedDevices", () => {
it("Should work", () => {
console.log(navigator); // Navigator {}
console.log(navigator.mediaDevices); // undefined
});
});
根据 create-react-app 文档,我也尝试过 Initializing the test environment。
// src/setupTests.ts
// jest-dom adds custom jest matchers for asserting on DOM nodes.
// allows you to do things like:
// expect(element).toHaveTextContent(/react/i)
// learn more: https://github.com/testing-library/jest-dom
import "@testing-library/jest-dom";
const navigatorMock = {
mediaDevices: {
enumerateDevices: jest.fn(),
},
};
global.navigator = navigatorMock;
我做错了什么?
【问题讨论】:
标签: reactjs unit-testing jestjs navigator