问题描述
我在React应用程序中使用Geolocation API,我想在Jest中对其进行测试。这是我在应用程序中的Geolocation功能:
const getGeolocation = () => {
const success = position => {
const {latitude} = position.coords
const {longitude} = position.coords
// eslint-disable-next-line no-magic-numbers
map.current.setView([latitude,longitude],12)
}
const error = () => {
// eslint-disable-next-line no-magic-numbers
map.current.setView([46.378333,13.836667],12)
}
if (!navigator.geolocation) {
// eslint-disable-next-line no-magic-numbers
map.current.setView([46.378333,12)
} else {
navigator.geolocation.getCurrentPosition(success,error)
}
}
我能够测试success
函数,但是我无法达到error
函数,并且也无法模拟!navigator.geolocation
情况。这是我的模拟:
const mockGeolocation = {
getCurrentPosition: jest.fn()
.mockImplementationOnce(success => Promise.resolve(success({
coords: {
latitude: 46.378333,longitude: 13.836667,},}))),watchPosition: jest.fn(),}
global.navigator.geolocation = mockGeolocation
如何模拟error
函数和!navigator.geolocation
的大小写?
解决方法
你可以像这样模拟它:
const mockGeolocation = {
getCurrentPosition: jest.fn()
.mockImplementationOnce((success,error) => Promise.resolve(error({
code: 1,message: 'GeoLocation Error',}))),watchPosition: jest.fn(),}
global.navigator.geolocation = mockGeolocation