我正在尝试为我构建的一个利用navigator.geolocation.getCurrentPosition()
方法的React组件编写测试,代码大致如下:
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函数中模拟函数、"services"和全局对象方法,例如navigator.geolocation等。我花了时间研究这个问题,这段代码是我能找到的最接近模拟的代码:
global.navigator = {
geolocation: {
getCurrentPosition: jest.fn()
}
}
我将这段代码放在我的App测试文件中,但是它没有产生任何效果。
我该如何“模拟”这个navigator方法并使测试通过?
编辑:我研究了一个名为geolocation的库,它据说可以包装navigator.getCurrentPosition
以在node环境中使用。如果我理解正确,jest在node环境中运行测试,并使用JSDOM模拟一些东西,比如window
。我没有找到关于JSDOM对navigator
的支持的太多信息。上述提到的库在我的react应用程序中不起作用。即使正确导入库并在App类的上下文中可用,使用特定的getCurrentPosition方法仍将返回undefined。
geolocation.getCurrentPosition
返回未定义,不知道为什么它不起作用。关于如何解决这个特定问题的实际解释将会更有帮助。 - timothym