Jest React-native 如何模拟函数和 return 响应
Jest React-native How to mock a function and return a response
我是 Jest 单元测试的新手。
我想测试一个 多次调用 Geolocation getCurrentPosition() 方法的组件。
每次调用函数我都想return一个新的坐标对象。
我已经阅读了各种文章和教程,但我仍然在挣扎。
有什么想法吗?
您可以使用 global.navigator
访问导航器对象。所以要模拟 getCurrentPosition
只需给它分配一个 jest.fn
:
global.navigator = {
getCurrentPosition : jest.fn()
}
那么如何return 每次调用新坐标。最简单的解决方案是全局计数器
const coords = [[1, 2], [2, 3]]
let counter = -1
global.navigator = {
getCurrentPosition: jest.fn(() {
counter++
return coords[counter]
})
}
或者您可以使用 mock
的 calls
属性
const coords = [[1, 2], [2, 3]]
global.navigator = {
getCurrentPosition: jest.fn(() =>
coords[global.navigator.getCurrentPosition.mock.calls.length]
)
}
我是 Jest 单元测试的新手。
我想测试一个 多次调用 Geolocation getCurrentPosition() 方法的组件。
每次调用函数我都想return一个新的坐标对象。
我已经阅读了各种文章和教程,但我仍然在挣扎。
有什么想法吗?
您可以使用 global.navigator
访问导航器对象。所以要模拟 getCurrentPosition
只需给它分配一个 jest.fn
:
global.navigator = {
getCurrentPosition : jest.fn()
}
那么如何return 每次调用新坐标。最简单的解决方案是全局计数器
const coords = [[1, 2], [2, 3]]
let counter = -1
global.navigator = {
getCurrentPosition: jest.fn(() {
counter++
return coords[counter]
})
}
或者您可以使用 mock
的calls
属性
const coords = [[1, 2], [2, 3]]
global.navigator = {
getCurrentPosition: jest.fn(() =>
coords[global.navigator.getCurrentPosition.mock.calls.length]
)
}