Testing Asynchronous Code
Await promises, fake timers, and control time when testing async functions.
What you'll learn
- Awaiting and returning promises inside tests
- Asserting rejections with rejects.toThrow
- Using fake timers to control setTimeout and intervals
- Avoiding floating promises and unhandled rejections
Concept
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 async and await the code under test, or return the promise. In Jest and Vitest, await expect(promise).resolves.toBe(value) and await expect(promise).rejects.toThrow(Error) 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.now 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-no-floating-promises or always await. 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 async and await 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 no-floating-promises ESLint rule project-wide to catch them statically before they become runtime mysteries.
Example
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 make the timer test instant and deterministic. The rejects.toThrow matcher awaits the promise and asserts it rejects with the right error.
Try it
- Cron Parser
Understand the schedules your timer-based code implements.
- JSON Formatter
Inspect the async payloads your tests await.
Common mistakes
The mistake
Forgetting to await an async assertion
The fix
Use `await expect(p).resolves.toBe(x)` — without await, the matcher promise is floating and the assertion may never run.
The mistake
Leaving fake timers enabled for the next test
The fix
Always restore real timers in afterEach. Fake timers leaking across tests cause mysterious hangs and false passes.
Practice Testing Asynchronous Code
9 exercises
Look up unfamiliar terms
A beginner-friendly glossary explains jargon in plain English — variables, functions, DOM, Promise, and more.
Build real projects
Apply what you learned by building guided projects with starter code and solutions.
Decode error messages
Plain-English explanations of common errors — what they mean, why they happen, and how to fix them.