如何解决如何在Jest中模拟Geolocation API错误函数和!navigator.geolocation大小写?
我在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
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。