Jest 异步代码 测试要注意的点

Jest 异步代码测试中,有一些点,我们记录一下。

如果要测的是回调函数,那么可以使用done 函数。

官网是如下解释的:

Instead of putting the test in a function with an empty argument, use a single argument called done. Jest will wait until the done callback is called before finishing the test.

If done() is never called, the test will fail, which is what you want to happen.

test('the data is peanut butter', done => {
  function callback(data) {
    expect(data).toBe('peanut butter');
    done();
  }

  fetchData(callback);
});

好,下面要说的是如果要测的是Promise , 要测case 是成功时,只需使用then()就好,如果是要测失败时,不仅要使用catch(),还建议添加expect.assertions。下面的测试用例中,测的是Promise 失败时的例子,使用的是catch(),当Promise 成功时,那就执行不到return 语句,因此没有assertions 行语句,这个测试用例就啥也没做,就自然通过了。因此这时我们需要加上expect.assertions 行语句。

官网解释:

If you expect a promise to be rejected use the .catch method. Make sure to add expect.assertions to verify that a certain number of assertions are called. Otherwise a fulfilled promise would not fail the test.

test('the fetch fails with an error', () => {
  expect.assertions(1);
  return fetchData().catch(e => expect(e).toMatch('error'));
});

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值