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 的语法糖。