异步测试
异步测试
回调函数
当执行到测试代码的尾部时,
// async/fetch.js
export const fetchApple = callback => {
setTimeout(() => callback("apple"), 300);
};
// async/fetch.test.js
import { fetchApple } from "./fetch";
test("the data is apple", done => {
expect.assertions(1);
const callback = data => {
expect(data).toBe("apple");
done();
};
fetchApple(callback);
});
Promise
如果异步代码返回
test("the data is banana", () => {
expect.assertions(1);
return fetchBanana().then(data => expect(data).toBe("banana"));
});
如果期望.catch()
:
test("the fetch fails with an error", () => {
expect.assertions(1);
return fetchError().catch(e => expect(e).toMatch("error"));
});
除此之外,还可以使用上文中提到的 .resolves
和 .rejects
。
Async/Await
如果异步代码返回
test("async: the data is banana", async () => {
expect.assertions(1);
const data = await fetchBanana();
expect(data).toBe("banana");
});
test("async: the fetch fails with an error", async () => {
expect.assertions(1);
try {
await fetchError();
} catch (e) {
expect(e).toMatch("error");
}
});
也可以将.resolves
或.rejects
结合:
test("combine async with `.resolves`", async () => {
expect.assertions(1);
await expect(fetchBanana()).resolves.toBe("banana");
});