首页 > 解决方案 > 如何使用 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只调用了一次。

标签: jestjs

解决方案


您将需要等待所有迭代完成。

尝试这样的事情:

it('should call doSomething twice', async () => {
  const doSomething = jest.fn();
  const items = [{a: 'a'}, {b: 'b'}];
  // Waiting
  await myFunc(items);
  expect(doSomething).toBeCalledTimes(2);
})

推荐阅读