Jest 使用指南 - - ts 文件篇
#jest
ts 文件的单测
ts 文件主要是一些工具方法的使用,然后对于其中的工具方法进行单测,比对返回的数据结构,包括基础数据类型、对象、数组、函数
异步方法
这部分直接参考 测试异步代码 · Jest
用到的 api 介绍
-
expect.assertions(1)
expect.assertions(number)验证在测试过程中是否调用了一定数量的断言。这在测试异步代码时通常很有用,以确保回调中的断言确实被调用。 -
Done
test的第二个参数是一个方法,该方法可以接收一个参数,这个参数是一个函数 done,Jest会等done回调函数执行结束后,结束测试。
Note: If a promise is returned from test, Jest will wait for the promise to resolve before letting the test complete. Jest will also wait if you provide an argument to the test function, usually called done. This could be handy when you want to test callbacks. Globals · Jest
如果测试返回了 Promise ,Jest将等待 Promise 解决,然后再完成测试。如果您向测试函数提供参数(通常称为 done ),Jest也将等待。当您要测试回调时,这可能很方便。
test('the data is peanut butter', done => {
function callback(data) {
expect(data).toBe('peanut butter');
done();
}
fetchData(callback);
});
- Promise / resolve / reject / catch
一定要返回Promise - 如果你省略 return 语句,您的测试将在 fetchData 完成之前完成。
test('the data is peanut butter', () => {
expect

这篇博客详细介绍了如何使用 Jest 对 TypeScript 文件进行单元测试,特别是针对异步方法和引入模块的情况。文中提到了 Jest 中的 `expect.assertions()` 用于验证断言次数,`done` 回调用于异步测试,并讨论了 Promise 和 async/await 在测试中的应用。同时,文章还提及了在测试中如何处理引入的外部模块。
最低0.47元/天 解锁文章
1528

被折叠的 条评论
为什么被折叠?



