Testing Async Code
Testing async code means the test waits for promises, timers, or events before asserting. If it does not wait, the runner can pass before the work runs.
Detailed Explanation
Jest and Vitest treat a test as done when the function returns, unless that return is a promise. async function tests are promises. await the unit. Assert with await expect(p).resolves.toBe(...) or try/catch plus expect.
The failure mode is a test that returns undefined while work is still queued. doWork() without await is green and useless. forEach(async () => ...) inside a test does not wait. Use for...of plus await, or Promise.all.
Timers: setTimeout in the unit will not fire during a test unless you fake the clock (vi.useFakeTimers(), jest.useFakeTimers()) and advanceTimersByTime(ms) or runAllTimers(). Fake timers plus real promises need await vi.runAllTimersAsync() in current Vitest so microtasks flush. Remember useRealTimers() in afterEach.
Events and React state updates settle in microtasks. await Promise.resolve() or await expect.poll / waitFor from Testing Library is the usual hop. setTimeout(done, 0) as a wait is brittle.
Unhandled rejections fail the run in modern runners if they escape the test. Attach .catch or await expect(p).rejects.
What it costs you: flakes. A real 200 ms timeout in CI is slow and races load. Fake the clock. A test that sometimes waits "long enough" is not a test. Prefer determinism over sleep.
Reach for async/await in every test that touches promises. Reach for fake timers for debounce and animation. Reach for Testing Library's waitFor when the DOM updates after fetch.
Race the unit against a deferred you control. If the code should not finish before a user token arrives, resolve the deferred in the test after you have asserted the loading state. That is clearer than waitFor with a timeout that sometimes trips on a slow CI box.
For WebSocket or EventSource units, fake the socket object and emit events in order. Real network in a unit test is an integration test you did not name.
Code Examples
async function load() {
return "ok";
}
test("resolves", async () => {
await expect(load()).resolves.toBe("ok");
});
test("rejects", async () => {
await expect(Promise.reject(new Error("no"))).rejects.toThrow("no");
});function delay(fn, ms) {
return new Promise((resolve) => {
setTimeout(() => resolve(fn()), ms);
});
}
test("timer", async () => {
vi.useFakeTimers();
const p = delay(() => 1, 1000);
await vi.advanceTimersByTimeAsync(1000);
await expect(p).resolves.toBe(1);
vi.useRealTimers();
});Common Gotchas
Not awaiting is a false pass
the runner cannot see a rejection that happens after the test function finished.
`done` callbacks plus promises double-complete
pick `async` or `done`, not both.
Fake timers can stall promises
flush with the `*Async` timer helpers after you advance.
`sleep(n)` in tests is a flake factory
use fake timers or a resolvable deferred.