我是Jest单元测试的新手。
我想测试对Geolocation getCurrentPosition()方法进行多次调用的组件。
对于函数的每次调用,我想返回一个新的坐标对象。
我已阅读各种文章和教程,但我仍在苦苦挣扎。
任何想法?
答案 0 :(得分:3)
您可以使用global.navigator
访问导航器对象。因此,要模拟getCurrentPosition
,只需为其分配jest.fn
:
global.navigator = {
getCurrentPosition : jest.fn()
}
那么如何为每次通话返回新坐标。最简单的解决方案是全球计数器
const coords = [[1, 2], [2, 3]]
let counter = -1
global.navigator = {
getCurrentPosition: jest.fn(() {
counter++
return coords[counter]
})
}
或者您可以使用模拟
的calls
属性
const coords = [[1, 2], [2, 3]]
global.navigator = {
getCurrentPosition: jest.fn(() =>
coords[global.navigator.getCurrentPosition.mock.calls.length]
)
}