Concept Explanation
Async code is the #1 source of flaky tests. If your test finishes before the Promise resolves, it passes even when the real code is broken — a false green. The fix is to make your test wait for the async work, then assert.
Think of baking: you can't judge the cake the instant it goes in. You wait for the timer, then check. Testing frameworks give you tools to "wait for the timer" reliably.
Syntax or Core Structure
The cleanest way — async/await:
test("fetches a user", async () => {
const user = await getUser(1);
expect(user.name).toBe("Ada");
});
Testing that a Promise rejects:
test("throws on bad id", async () => {
await expect(getUser(-1)).rejects.toThrow("Not found");
});
Real World Example
waitFor: When testing UI, an element may appear only after data loads. Libraries give you await waitFor(() => expect(screen.getByText("Done")).toBeVisible()), which retries until it's there or times out.
Common Mistakes
- Forgetting await: Without
await(orreturn), the test ends early and the assertion never runs. - No Rejection Test: Teams test the happy path and forget the error path. Test both.
- Real Delays:
await new Promise(r => setTimeout(r, 3000))makes suites crawl. Use fake timers instead.
Best Practices
- Prefer async/await: It reads top-to-bottom and avoids callback nesting.
- Always Return or Await: Ensure the framework knows the test isn't done yet.
- Set Timeouts: Give async tests a sensible timeout so a hang fails fast instead of blocking CI.
Practice Exercises
- The Awaiter: Test an
asyncfunction that resolves to a value usingawait. - The Rejecter: Test that a function rejects, using
.rejects.toThrow(). - The Poller: Research
waitForand write a test that waits for a value to change before asserting.