我正在尝试为我构建的 react 组件编写测试,该组件在这样的方法中利用 navigator.geolocation.getCurrentPosition()
(我的组件的粗略示例):
class App extends Component {
constructor() {
...
}
method() {
navigator.geolocation.getCurrentPosition((position) => {
...code...
}
}
render() {
return(...)
}
}
我正在使用create-react-app ,其中包括一个测试:
it('renders without crashing', () => {
const div = document.createElement('div');
ReactDOM.render(<App />, div);
});
此测试失败,在控制台中打印出以下内容:
TypeError: Cannot read property 'getCurrentPosition' of undefined
我是 React 新手,但对 Angular 1.x 有相当多的经验。在 Angular 中,通常会模拟(在 beforeEach 的测试中)函数、“服务”和全局对象方法,例如 navigator.geolocation.etc。我花了时间研究这个问题,这段代码是我能得到的最接近模拟的代码:
global.navigator = {
geolocation: {
getCurrentPosition: jest.fn()
}
}
我把它放在我的App测试文件中,但没有效果。
如何“模拟”此导航器方法并让测试通过?
编辑:我研究了使用一个名为 geolocation 的库据说它包装了 navigator.getCurrentPosition
以在节点环境中使用。如果我理解正确的话,jest 在节点环境中运行测试并使用 JSDOM 来模拟诸如 window
之类的东西。我还没有找到太多关于 JSDOM 支持 navigator
的信息。上面提到的库在我的 react 应用程序中不起作用。即使库本身已正确导入并且在 App 类的上下文中可用,使用特定方法 getCurrentPosition 也只会返回 undefined。
最佳答案
似乎已经有一个 global.navigator
对象,并且像您一样,我无法重新分配它。
我发现模拟地理位置部分并将其添加到现有的 global.navigator
对我来说很有效。
const mockGeolocation = {
getCurrentPosition: jest.fn(),
watchPosition: jest.fn()
};
global.navigator.geolocation = mockGeolocation;
我将其添加到 src/setupTests.js
文件中,如下所述 - https://create-react-app.dev/docs/running-tests#initializing-test-environment
关于unit-testing - 如何在 React Jest 测试中获取 "mock"navigator.geolocation,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43008925/