测试 Asynchronous Code
等待 Promise, fake timers, and control 时间当 测试异步函数.
你将学到
- Awaiting and returning Promise 内部测试
- Asserting rejections 使用拒绝.toThrow
- Using fake timers 到 control setTimeout and intervals
- Avoiding floating Promise and unhandled rejections
概念讲解
Async Is Everywhere
Modern JavaScript is full of promises, async/await, timers, and event emitters. Testing async code is not hard, but it requires discipline: the test runner must know the test is async so it waits for the work to finish before evaluating assertions and moving on.
Awaiting Promises
Mark the test function 异步 and 等待 the code under test, or 返回 the promise. In Jest and Vitest, 等待 expect(Promise).resolves.toBe(值) and 等待 expect(Promise).拒绝.toThrow(错误) assert async outcomes. Never call an async function inside a test without awaiting or returning it — the assertion runs before the promise settles and the test passes vacuously.
Fake Timers
Real setTimeout, setInterval, and Date.现在 make tests slow and non-deterministic. vi.useFakeTimers() (and jest.useFakeTimers()) replaces them with controllable fakes. You then advance time with vi.advanceTimersByTime(ms) or vi.runAllTimers() to fire callbacks instantly. Remember to vi.useRealTimers() in an afterEach so the fakes do not leak into other tests.
Floating Promises
A floating promise — one that is created but neither awaited nor returned — can reject after the test has passed, producing an unhandled rejection in a later, unrelated test. Lint with eslint-plugin-否-floating-Promise or always 等待. For code that fires-and-forgets (like logging), assert on a spy that the call was made, and let the promise be intentionally unawaited with a comment.
In Practice
Async testing rewards discipline. Make every test function 异步 and 等待 every promise, even when you are tempted to skip it — the test runner needs to know the test is not finished. For code that polls or retries, fake timers let you advance time instantly instead of waiting real milliseconds. When a test involves a sequence of async events (a fetch, then a state update, then a re-render), use waitFor or findBy queries that retry until the assertion passes or times out, rather than guessing how long to sleep. If you see an unhandled rejection in a test that should have passed, hunt for a floating promise — it is almost always the cause. Enable the 否-floating-Promise ESLint rule project-wide to catch them statically before they become runtime mysteries.
示例代码
import { describe, it, expect, vi, afterEach } from "vitest";
describe("async countdown", () => {
afterEach(() => vi.useRealTimers());
it("fires the callback after the delay", () => {
vi.useFakeTimers();
const cb = vi.fn();
schedule(cb, 1000); // calls cb after 1000ms
vi.advanceTimersByTime(1000);
expect(cb).toHaveBeenCalledTimes(1);
});
it("rejects when the id is missing", async () => {
await expect(fetchUser(0)).rejects.toThrow("not found");
});
});
async function fetchUser(id: number) {
if (id === 0) throw new Error("not found");
return { id, name: "Ada" };
}
function schedule(cb: () => void, ms: number) {
setTimeout(cb, ms);
}
Fake timers 制作 timer 测试瞬时 and deterministic. 拒绝.toThrow matcher awaits Promise and asserts 它拒绝使用正确错误.
动手试一试
- Cron Parser
理解 schedules 你的 timer-based code implements.
- JSON Formatter
Inspect 异步 payloads 你的测试等待.
常见错误
错误写法
Forgetting 到等待异步 assertion
正确做法
Use `等待 expect(p).resolves.toBe(x)` — 不使用等待, matcher Promise 是 floating and assertion 可能从不运行.
错误写法
Leaving fake timers 启用 for 下一个测试
正确做法
总是 restore 真实 timers in afterEach. Fake timers leaking 跨越测试 cause mysterious hangs and 假通过.
练习 测试 Asynchronous Code
9 个练习
查阅不认识的术语
新手友好的术语表用大白话解释编程术语——变量、函数、DOM、Promise 等等。
动手做项目
通过引导式项目应用所学,含起始代码与解决方案。
解读错误信息
用大白话解释常见错误——什么意思、为什么发生、如何修复。