【发布时间】:2017-08-17 22:45:25
【问题描述】:
我正在尝试为我构建的一个反应组件编写测试,该组件在这样的方法中使用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 的支持的信息。上面提到的库在我的反应应用程序中不起作用。即使库本身已正确导入并且在 App 类的上下文中可用,使用特定方法 getCurrentPosition 只会返回 undefined。
【问题讨论】:
-
@jordan,你能解释一下为什么你认为它是重复的吗?我查看了该答案并尝试通过使用geolocation 库来解决此问题,该库类似于“节点友好的存根,如'node-localstorage'”。描述的解决方案。但在我的应用程序的上下文中,
geolocation.getCurrentPosition返回未定义,不知道为什么它不起作用。对如何解决这个特定问题的实际解释会更有帮助。
标签: unit-testing reactjs jestjs create-react-app