用Jest测试承诺链

Лёш*_* Ан 5 javascript promise jestjs

我正试图用Jest测试promises-chain序列:

someChainPromisesMethod: function() {
    async()
      .then(async1)
      .then(async2)
      .then(result)
      .catch(error);
}
Run Code Online (Sandbox Code Playgroud)

虽然测试单一承诺是好的记录,但不确定什么是正确的方法(不知道该怎么做TBO)来测试这种链.让我们假设所有的asyncs都是嘲笑的,只是在他们的身体里解决了Promises(Promise.resolve).

所以我需要能测试整个序列的东西.

grg*_*gmo 11

您可以使用jest.fn()来模拟实现并检查调用函数的内容并返回您想要的内容.您需要模拟async函数中的所有函数并返回所需的函数.

例如

async = jest.fn(() => {
  return Promise.resolve('value');
});

async1 = jest.fn(() => {
  return Promise.resolve('value1');
});

async2 = jest.fn(() => {
  return Promise.resolve('Final Value');
});
Run Code Online (Sandbox Code Playgroud)

您可以在测试中使用它

it('should your test scenario', (done) => {
  someChainPromisesMethod()
    .then(data => {
      expect(async1).toBeCalledWith('value');
      expect(async2).toBeCalledWith('value1');
      expect(data).toEqual('Final Value');
      done(); 
  });
});
Run Code Online (Sandbox Code Playgroud)

但是,如果你有逻辑,我会把你的链变平并分别测试它们,这样你就可以轻松地测试所有可能性.


Lui*_*uiz 5

使用 done 不能解决问题,它会给你一个误报测试。如果由于任何原因预期失败,您的测试将超时,您将不会得到真正的结果。

正确的解决方案是返回您的 Promise,因此 Jest 将能够正确评估预期结果。

遵循@grgmo 示例,更好的方法可能是:

it('should your test scenario', () => {
  return someChainPromisesMethod()
    .then(data => {
      expect(async1).toBeCalledWith('value');
      expect(async2).toBeCalledWith('value1');
      expect(data).toEqual('Final Value');
  });
});
Run Code Online (Sandbox Code Playgroud)