Jest 异步代码测试

Callback

回调是一种最常见的异步编程模式。

错误示例:

// 不要这么做!
test('the data is peanut butter', () => {
  function callback(data) {
    expect(data).toBe('peanut butter');
  }

  fetchData(callback);
});

问题处在于,一旦 fetchData 执行完毕,测试随即完毕,而不会等待 callback 回调的执行。

正确示例:

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

  fetchData(callback);
});

使用一个名为 done 的参数,Jest 会一直等待 done 回调的执行,一旦 done 回调执行完毕,测试即完成。如果 done 一直没有被回调,那么测试失败。

Promise

如果使用的是 promise,测试将更加简单。只需要在测试中返回一个 promise,Jest 会自动等待 promise 被解析处理,如果 promise 被拒绝,那么测试失败。

示例:

test('the data is peanut butter', () => {
  expect.assertions(1);
  return fetchData().then(data => {
    expect(data).toBe('peanut butter');
  });
});

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

注意:确保返回 promise,如果忽略掉 return,那么测试会在 fetchData 完成之前完成。

点击查看 expect.assertions(number) 的更多信息。

.resolve / .reject

示例:

test('the data is peanut butter', () => {
  expect.assertions(1);
  return expect(fetchData()).resolves.toBe('peanut butter');
});

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

Async/Await

同样,您也可以在测试中使用 async 和 await 关键字。想要编写异步测试,只需要在传递给 test 的函数前加上 async 关键字。

示例:

test('the data is peanut butter', async () => {
  expect.assertions(1);
  const data = await fetchData();
  expect(data).toBe('peanut butter');
});

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

您也可以将 async / await 与 .resolve 或 .reject 结合起来使用。

示例:

test('the data is peanut butter', async () => {
  expect.assertions(1);
  await expect(fetchData()).resolves.toBe('peanut butter');
});

test('the fetch fails with an error', async () => {
  expect.assertions(1);
  await expect(fetchData()).rejects.toMatch('error');
});

async 和 await 其实是 promise 的语法糖。

参考资料

©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

  • JavaScript中经常有异步运行的代码。如果你要测试异步的代码,Jest需要知道他测试的代码是否已经完成异步动...
    人头原子弹阅读 5,811评论 0赞 0
  • 异步编程对JavaScript语言太重要。Javascript语言的执行环境是“单线程”的,如果没有异步编程,根本...
    呼呼哥阅读 7,476评论 5赞 22
  • Promise 对象 Promise 的含义 Promise 是异步编程的一种解决方案,比传统的解决方案——回调函...
    neromous阅读 8,884评论 1赞 56
  • 本文配图选自2007年剧情片《追风筝的孩子》改编自阿富汗作家卡勒德·胡赛尼 03年出版的同名小说。影片关键词:友谊...
    贝塔姐阅读 624评论 0赞 1
  • 众所周知,现在开发软件已经变得不难,因为现在软件项目通常使用大量的依赖库。开发者虽然非常容易开发项目,简单而又方便...
    非著名程序员阅读 1,324评论 2赞 5

友情链接更多精彩内容