用Jest测试承诺链 [英] Test promise-chain with Jest

查看:76
本文介绍了用Jest测试承诺链的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I'm trying to test promises-chain sequence with Jest:

someChainPromisesMethod: function() {
    async()
      .then(async1)
      .then(async2)
      .then(result)
      .catch(error);
}

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

While testing single promise is good documented not sure what is a proper way (not sure what to do TBO) to test this kind of chain. Let's assume all asyncs are mocked and just resolves promises (Promise.resolve) in theirs body.

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

So I need something that will test whole sequence.

推荐答案

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

You can use jest.fn() to mock implementation and check what the function has been called with and return what you want. You need to mock all async functions you have in your function and return what you want.

例如

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

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

async2 = jest.fn(() => {
  return Promise.resolve('Final Value');
});

您可以在测试中使用此项

You can use this in your test as

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

但是,如果你有自己的逻辑,我会压扁你的链并单独测试它们,就像你一样可以轻松测试所有可能性。

However, I would flatten your chain and test them separately if you have logic in them, that way you can test all possibilities easily.

这篇关于用Jest测试承诺链的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆