javascript - 如何测试函数是否被等待,而不仅仅是被调用?

标签 javascript jestjs

考虑测试以下简化函数

const functionToBeTested = async (val) => {
    await otherModule.otherFunction(val/2);
}

在我的 Jest 测试中,我想确保 otherModule.otherFunction 不仅被调用,而且还被等待。换句话说,我想编写一个测试,如果有人从 otherFunction 调用前面删除 await ,该测试将会失败。

到目前为止我已经做到了

test('should wait on otherFunction', () => {
   await functionToBeTested(6) 
   expect(otherModule.otherFunction).toHaveBeenCalledWith(3);  
}

但是 expect(otherModule.otherFunction).toHaveBeenCalledWith(3); 检查不会验证 functionToBeTested 是否已等待 otherFunction

最佳答案

这是我想到的:

const delay = duration => new Promise(resolve => setTimeout(resolve, duration));

test('should wait on otherFunction', async () => {
  let resolve;
  const mockPromise = new Promise((res) => {resolve = res;});
  otherModule.otherFunction.mockReturnValue(mockPromise);
  const resolution = jest.fn();

  functionToBeTested(6).then(resolution);

  expect(otherModule.otherFunction).toHaveBeenCalledWith(3);
  await delay(0);
  expect(resolution).not.toHaveBeenCalled();
  resolve();
  await delay(0);
  expect(resolution).toHaveBeenCalled();
}

所以,我模拟 otherFunction 返回一个开始时 Unresolved promise ,但我可以在测试期间随意解决它。然后我调用我想要测试的函数,并在完成时给它一个回调。

然后我想断言它没有调用回调,但由于 promise 解析始终是异步的,我需要添加超时 0 以使 promise 有机会解决。我选择使用 setTimeout 的 promise 版本来实现此目的。

最后,我解析了 mockPromise,设置超时 0(再次确保 Promise 有机会调用其回调),并断言现在已经调用了解析。

关于javascript - 如何测试函数是否被等待,而不仅仅是被调用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56160207/

相关文章:

javascript - 如何在 NodeJS 中运行无限阻塞进程?

javascript - Bootstrap 4 旋转木马 : Individual data-interval on each slide

javascript - 为什么显示的是 [object HTMLCollection] 而不是我创建的元素?

reactjs - 如何修复 "SyntaxError: Invalid or unexpected token @import"?

对于Jest错误 : Unexpected token import 导入

javascript - 如何从 youtube 视频制作 gif 图像?

javascript - 数组递增 Javascript/node js/mongodb

typescript - Typescript/ES6 的 Jest 预处理器

jestjs - 如何使用构造函数手动模拟模块(ioredis)

vuejs2 - 在 vue-test-utils 中测试鼠标悬停事件