jestjs - 如何使用 Jest 计算对循环 Promise 函数的调用
问题描述
我有一个功能:
myFunc = async () => {
for (let item of items) {
await doSomething(items);
}
}
我使用for of
循环是因为它尊重等待。
我的测试:
it('should call doSomething twice', () => {
const doSomething = jest.fn();
const items = [{a: 'a'}, {b: 'b'}];
myFunc(items);
expect(doSomething).toBeCalledTimes(2);
})
它失败了,因为doSomething
只调用了一次。
解决方案
您将需要等待所有迭代完成。
尝试这样的事情:
it('should call doSomething twice', async () => {
const doSomething = jest.fn();
const items = [{a: 'a'}, {b: 'b'}];
// Waiting
await myFunc(items);
expect(doSomething).toBeCalledTimes(2);
})
推荐阅读
- rest - etags 和普通浏览器提供的缓存有什么区别?
- swift - `@Published var name: ClassType` 在 SwiftUI / 手动触发之外_不起作用?
- reactjs - TypeError:未定义不是对象(评估'route.params')
- google-cloud-platform - “80端口被占用;” 在谷歌计算引擎上:(
- c# - 如何让 Serilog 使用来自 json 配置文件的自定义丰富器
- python - 当我在 Windows Powershell 中运行命令时,“访问被拒绝”
- kubernetes - 如何向我的 AKS 发送 Postmanrequest?
- svg - SVG 剪辑“随你”
- node.js - 无法建立隧道套接字
- javascript - 如何等待cropperjs、.getCroppedCanvas() 和.toBlob 完成