Javascript 如何强制navigator.geolocation.getCurrentPosition失败

Javascript 如何强制navigator.geolocation.getCurrentPosition失败,javascript,unit-testing,geolocation,jestjs,Javascript,Unit Testing,Geolocation,Jestjs,我正在使用地理定位API //index.js navigator.geolocation.getCurrentPosition(()=>{…},(err)=>{ 手柄错误(err) }) 让我们假设handleError在测试中被模拟 //index.spec.js 它(“应该调用错误处理程序”,()=>{ expect(handleError).toBeCalled() }) 我想使navigator.geolocation.getCurrentPosition失败,以验证是否调用了ha

我正在使用地理定位API

//index.js
navigator.geolocation.getCurrentPosition(()=>{…},(err)=>{
手柄错误(err)
})
让我们假设handleError在测试中被模拟

//index.spec.js
它(“应该调用错误处理程序”,()=>{
expect(handleError).toBeCalled()
})
我想使
navigator.geolocation.getCurrentPosition
失败,以验证是否调用了handleError


我在使用Jest,那么有没有办法控制
getCurrentPosition
的失败?

这是单元测试解决方案,测试环境是
节点

index.js

从“/errorHandler”导入{handleError};
函数main(){
navigator.geolocation.getCurrentPosition(
() => {
console.log('success');
},
(错误)=>{
handleError(err);
},
);
}
导出{main};
errorHandler.js

从“/errorHandler”导入{handleError};
函数main(){
navigator.geolocation.getCurrentPosition(
() => {
console.log('success');
},
(错误)=>{
handleError(err);
},
);
}
导出{main};
index.test.js

从“/”导入{main};
从“/errorHandler”导入{handleError};
jest.mock('./errorHandler',()=>{
返回{handleError:jest.fn()};
});
描述('60062574',()=>{
在每个之前(()=>{
global.navigator={geolocation:{getCurrentPosition:jest.fn()};
});
它('应该处理错误',()=>{
const mError=新错误(“某些错误”);
global.navigator.geolocation.getCurrentPosition.mockImplementationOnce((successCallback,errorCallback)=>{
错误回调(mError);
});
main();
expect(navigator.geolocation.getCurrentPosition).toBeCalledWith(expect.any(函数)、expect.any(函数));
期望(handleError)。与(mError)一起调用;
});
它('应该处理成功',()=>{
constlogspy=jest.spyOn(控制台,'log');
global.navigator.geolocation.getCurrentPosition.mockImplementationOnce((successCallback,errorCallback)=>{
successCallback();
});
main();
期望(logSpy)。与(“成功”)一起调用;
expect(navigator.geolocation.getCurrentPosition).toBeCalledWith(expect.any(函数)、expect.any(函数));
});
});
100%覆盖率的单元测试结果:

PASS stackoverflow/60062574/index.test.js
60062574
✓ 应处理错误(5ms)
✓ 应处理成功(17ms)
console.log node_modules/jest mock/build/index.js:814
成功
----------|---------|----------|---------|---------|-------------------
文件|%Stmts |%Branch |%Funcs |%Line |未覆盖行|s
----------|---------|----------|---------|---------|-------------------
所有文件| 100 | 100 | 100 | 100 |
index.js | 100 | 100 | 100 | 100 |
----------|---------|----------|---------|---------|-------------------
测试套件:1个通过,共1个
测试:2次通过,共2次
快照:共0个
时间:2.715s,估计5s
jest.config.js

module.exports={
预设:'ts jest/presets/js with ts',
测试环境:“节点”,
setupFilesAfterEnv:['./jest.setup.js'],
测试匹配:['**/?(*)+(规范测试)。[jt]s?(x)],
没错,
};
源代码: