Jest 08 ๐ Testing Async Code โ Callbacks, Promises, and async/await
Jest has supported asynchronous tests since its first release, and the three patterns it accepts are the same three the JavaScript ecosystem has used for the same period: the done callback, the returned Promise, and async/await. The first is the legacy form, the second is the Promise form, and the third is the syntactic sugar that the second desugars to. All three make Jest wait for the test to complete, and all three fail the test when the asynchronous operation rejects. The failure modes are the ones that make an async test pass when it should fail: a missing done, a missing return, and a missing await.
This chapter covers the three patterns, the failure modes that make an async test silently pass, and the fake timer integration that tests a setTimeout-based operation without waiting for the real clock. The sections that follow walk through the callback and Promise forms, the async/await form and the missing-await problem, and the timer and matcher utilities for the edge cases.
Key point: A Jest test must signal completion by calling done, returning a Promise, or using async/await; a test that does none of these completes before the asynchronous operation, and the assertion fails after the test has been reported as passing.
a. The callback and Promise forms
The done callback is the oldest form. The test function receives a done function as its argument, and the test calls done() when the asynchronous operation completes. Jest waits until done is called or the timeout expires. If done is called with an error, the test fails.
test("calls the callback with the result", (done) => {
fetchData((error, result) => {
if (error) {
done(error); // fail with the error
return;
}
expect(result).toEqual({ id: 1 });
done(); // signal completion
});
});
The done form has a failure mode that is easy to miss: if an assertion inside the callback throws, the throw propagates to the callback’s caller, not to Jest, and the test can time out instead of failing with the assertion. The done(error) form is the correct way to pass the error, and the try/catch around the assertion is the safe pattern.
The returned-Promise form is the modern replacement. The test returns a Promise, and Jest waits for it to settle. A resolved Promise passes; a rejected Promise fails.
test("resolves with the result", () => {
return fetchData().then((result) => {
expect(result).toEqual({ id: 1 });
});
});
The returned Promise is what the async keyword produces implicitly, and it is the form that the async/await syntax desugars to. The return is not optional: a test that calls fetchData().then(...) without returning the Promise completes before the .then callback runs.
b. async/await and the missing-await problem
The async/await form is the recommended one. The test function is declared async, the asynchronous operation is awaited, and the assertion runs after the value resolves.
test("resolves with the result", async () => {
const result = await fetchData();
expect(result).toEqual({ id: 1 });
});
The missing await is the failure mode. A test that calls the async function without awaiting it completes before the operation resolves, and the assertion either runs after the test has passed or never runs at all.
// WRONG: missing await
test("fails silently", async () => {
fetchData().then((result) => {
expect(result).toEqual({ id: 1 }); // may run after the test passes
});
});
// RIGHT: await
test("fails correctly", async () => {
const result = await fetchData();
expect(result).toEqual({ id: 1 });
});
The .resolves and .rejects matchers are the other form. They unwrap the Promise and apply the chained matcher to the resolved or rejected value, and the test must await them.
// Resolved value
await expect(fetchData()).resolves.toEqual({ id: 1 });
// Rejected Promise
await expect(fetchData("missing")).rejects.toThrow("Not found");
// Rejection with an asymmetric matcher
await expect(fetchData("missing")).rejects.toMatchObject({
message: expect.stringContaining("Not found"),
});
The await on the .resolves / .rejects matcher is required. Without it, the assertion runs after the test completes, and the test passes before the matcher has a chance to fail.
c. Fake timers and the timeout
A test that depends on a setTimeout or setInterval waits for the real clock unless it uses fake timers. Jest’s jest.useFakeTimers() replaces the timer functions with mocks, and jest.advanceTimersByTime(ms) moves the clock forward without waiting.
beforeEach(() => {
jest.useFakeTimers();
});
afterEach(() => {
jest.useRealTimers();
});
test("calls the callback after the delay", () => {
const callback = jest.fn();
setTimeout(callback, 1000);
jest.advanceTimersByTime(1000);
expect(callback).toHaveBeenCalled();
});
The fake timers also work with await through jest.advanceTimersByTimeAsync(ms), which flushes the microtasks between the timer advances. It is the form for a test that combines a timer with a Promise.
The test timeout is the other configuration. The default is 5 seconds, and the third argument to test sets a per-test timeout.
test("slow operation", async () => {
await slowOperation();
}, 10_000);
The jest.setTimeout(ms) call sets the default for the file, and the --testTimeout CLI flag sets it for the run. A test that times out fails with a message that names the timeout, and the failure is often the symptom of a missing await rather than a genuinely slow operation.
The expect.assertions(n) assertion is the guard for the async test. It asserts that the test called expect exactly n times, which catches the case where the assertion never ran because the Promise rejected before it.
test("rejects", async () => {
expect.assertions(1);
await expect(fetchData("missing")).rejects.toThrow("Not found");
});
The guard is the mechanism that turns a silently passing test into a failing one. A test that expects a rejection and does not use expect.assertions passes if the code under test resolves instead of rejecting, because the await completes and the test ends without an assertion.
Complete Example Session
// ============================================
// PART 1: THE ASYNC FUNCTION
// ============================================
async function fetchUser(id) {
if (id === "999") throw new Error("User not found");
return { id, name: "Ana" };
}
// ============================================
// PART 2: async/await
// ============================================
describe("fetchUser", () => {
test("returns the user", async () => {
const user = await fetchUser("1");
expect(user.name).toBe("Ana");
});
});
// ============================================
// PART 3: .resolves / .rejects
// ============================================
describe("promise matchers", () => {
test("resolves to the user", async () => {
await expect(fetchUser("1")).resolves.toEqual({ id: "1", name: "Ana" });
});
test("rejects for a missing user", async () => {
await expect(fetchUser("999")).rejects.toThrow("User not found");
});
});
// ============================================
// PART 4: expect.assertions
// ============================================
describe("assertion guard", () => {
test("rejects", async () => {
expect.assertions(1);
await expect(fetchUser("999")).rejects.toThrow("User not found");
});
});
// ============================================
// PART 5: FAKE TIMERS
// ============================================
describe("timers", () => {
beforeEach(() => { jest.useFakeTimers(); });
afterEach(() => { jest.useRealTimers(); });
test("calls after the delay", () => {
const callback = jest.fn();
setTimeout(callback, 1000);
jest.advanceTimersByTime(1000);
expect(callback).toHaveBeenCalled();
});
});
The parts covered the async function, the async/await test, the promise matchers, the assertion guard, and the fake timers.
Quick Reference
Async Test Forms
| Form | Jest Waits |
|---|---|
test("...", (done) => { ...; done(); }) | Yes (done called) |
test("...", () => { return promise; }) | Yes (Promise) |
test("...", async () => { await promise; }) | Yes (Promise) |
test("...", () => { promise.then(...); }) | No (missing return) |
Promise Matchers
| Matcher | Asserts |
|---|---|
.resolves.toBe(v) | Resolved value |
.rejects.toThrow(msg) | Rejection message |
.rejects.toThrow(ErrorClass) | Rejection class |
.rejects.toMatchObject(obj) | Rejection shape |
Timer Utilities
| Call | Effect |
|---|---|
jest.useFakeTimers() | Replace timers |
jest.advanceTimersByTime(ms) | Move clock |
jest.useRealTimers() | Restore |
jest.advanceTimersByTimeAsync(ms) | Flush microtasks |
Best Practices
โ Do This:
// Await the async call
test("...", async () => { const u = await fetchUser("1"); }); // โ
// Await the promise matcher
await expect(fetchUser("999")).rejects.toThrow("not found"); // โ
// Guard the rejection
expect.assertions(1); // โ
โ Don’t Do This:
// Forget the await
test("...", async () => { fetchUser("1").then((u) => expect(u).toBeDefined()); }); // โ
// Assert on the Promise
expect(fetchUser("1")).toEqual({ id: "1" }); // โ
// Forget `done`
test("...", (done) => { fetchData(() => { expect(...); }); }); // never calls done // โ
Common Pitfalls
| Pitfall | Why It Happens | Fix |
|---|---|---|
| Test passes but assertion failed | Missing await/return | Await or return the Promise |
| Test times out | done never called | Call done() |
| Rejection not caught | No expect.assertions | Add the guard |
| Test waits for the real clock | No fake timers | jest.useFakeTimers() |
Real-World Examples
1. Await the call
test("...", async () => { const u = await fetchUser("1"); });
2. .resolves
await expect(fetchUser("1")).resolves.toEqual({ id: "1", name: "Ana" });
3. .rejects
await expect(fetchUser("999")).rejects.toThrow("not found");
4. done callback
test("...", (done) => { fetchData((err, r) => { if (err) return done(err); done(); }); });
5. Return the Promise
test("...", () => fetchUser("1").then((u) => expect(u).toBeDefined()));
6. expect.assertions
expect.assertions(1);
7. Fake timers
jest.useFakeTimers(); jest.advanceTimersByTime(1000);
8. Per-test timeout
test("slow", async () => { ... }, 10_000);
9. jest.setTimeout
jest.setTimeout(10_000);
10. Async timer
await jest.advanceTimersByTimeAsync(1000);
Visual
The Missing-Await Failure
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
โ test("...", () => { โ
โ fetchUser("1").then((u) => { โ
โ expect(u.name).toBe("Wrong"); โ
โ }); โ
โ }); โ
โ โ โ
โ โผ โ
โ Test returns undefined โ Jest reports PASS โ
โ โ โ
โ โผ โ
โ Promise resolves โ assertion fails in the background โ
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
The Three Forms
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
โ done callback โ
โ test("...", (done) => { asyncOp(done); }) โ
โ โ
โ Returned Promise โ
โ test("...", () => asyncOp().then(...)) โ
โ โ
โ async/await โ
โ test("...", async () => { await asyncOp(); }) โ
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
expect.assertions Guard
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
โ expect.assertions(1); โ
โ await expect(fetchUser("999")).rejects.toThrow(); โ
โ โ
โ If the Promise resolves instead of rejecting, โ
โ the rejection matcher fails โ the test fails โ
โ instead of passing with no assertion. โ
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
Fake Timers
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
โ jest.useFakeTimers(); โ
โ setTimeout(callback, 1000); โ
โ jest.advanceTimersByTime(1000); โ
โ โ โ
โ โผ โ
โ callback runs without waiting 1000ms โ
โ โ
โ jest.useRealTimers(); // restore โ
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
Summary
| Item | Value |
|---|---|
| Callback form | done argument |
| Promise form | Return the Promise |
| Async form | async/await |
| Resolved matcher | .resolves |
| Rejected matcher | .rejects |
| Guard | expect.assertions(n) |
| Fake timers | jest.useFakeTimers() |
| Default timeout | 5s |
Key takeaways:
- A test must signal completion. The
donecallback, the returned Promise, andasync/awaitare the three forms, and all three make Jest wait. A test that uses none of them completes before the asynchronous operation. - The missing
awaitis the silent-pass failure. A test that calls an async function without awaiting it reports passing before the assertion runs. The lint rule@typescript-eslint/no-floating-promisescatches the pattern. .resolvesand.rejectsmust be awaited. The matchers return a Promise, and a test that does not await them completes before the assertion.expect.assertions(n)guards a rejection test. It asserts that the test calledexpectexactlyntimes, which catches the case where the Promise resolved instead of rejecting and the assertion never ran.- Fake timers remove the real-clock wait.
jest.useFakeTimers()andjest.advanceTimersByTime(ms)move the clock forward instantly, andjest.advanceTimersByTimeAsync(ms)flushes the microtasks for a test that combines a timer with a Promise.
Remember: An async test is only as reliable as the signal that sequences it. The done callback, the returned Promise, and the await are the three signals, and the missing one is the test that passes without asserting. Await the call, await the matcher, guard the rejection, and use fake timers for the operations that wait on a clock. The test that passes without running its assertion is worse than the test that fails, because it hides the failure it was written to catch.
Stop using slow, ad-bloated tool sites! ๐คฎ
๐ Search “KandZ Tools” on Google to use many professional utilities for free.
KandZ.me is the ultimate minimalist hub for:
โ
Finance (Mortgage, Interest, Inflation)
โ
Tech (Base64, JSON, Dev Suite, IP)
โ
Health (BMI, BMR, TDEE)
โ
Productivity (Timer, Workspace, QR)
โก๏ธ Fast & Private
๐ No data leaves your device
๐ 100% Free
๐ Use it now: https://tools.kandz.me
๐ Bookmark itโyouโll need it later!