A Jest 30 test of an async retry helper calls jest.advanceTimersByTime(2000), yet the second attempt never runs. Why, and how do the Async timer methods fix it?
answer
- promise callbacks are not timers
- no timer exists yet to fire
- let microtasks run between timers
- attach the rejects check first
basics
~20 sThe helper only schedules its setTimeout after the awaited attempt settles, and the synchronous advance runs before any promise callback can, so it finds no timer to fire. Awaiting jest.advanceTimersByTimeAsync lets promise callbacks run before and between the timers.
solid answer
~40 sFake timers control the clock, not promises. The retry helper calls the task, `await`s it, and only then calls `setTimeout` for the pause. `jest.advanceTimersByTime(2000)` runs synchronously right after the helper starts, while the first attempt's promise is still waiting for its microtask turn, so at that moment no timer exists and nothing fires; `jest.getTimerCount()` would return 0. `await jest.advanceTimersByTimeAsync(1000)` lets scheduled promise callbacks run before the timers, so the attempt fails, the pause is scheduled, the clock reaches it and the next attempt starts. `runAllTimersAsync`, `runOnlyPendingTimersAsync` and `advanceTimersToNextTimerAsync` do the same for their counterparts. Two more rules: do not `await` the helper before moving the clock, or the test hangs until its timeout; and attach any `.rejects` assertion before running the timers, or Jest 30's default unhandled-rejection tracking can fail the test.
code
javascript · 32 linesconst {fetchJson, retry} = require('./fetchJson'); // fetchJson rejects on a 5xx; retry awaits each attempt, then waits delayMs with setTimeout
afterEach(() => {
jest.useRealTimers();
});
test('retries after each one-second wait', async () => {
jest.useFakeTimers();
const get = jest
.fn()
.mockResolvedValueOnce({status: 500, body: null})
.mockResolvedValueOnce({status: 500, body: null})
.mockResolvedValueOnce({status: 200, body: {id: 7}});
const result = retry(() => fetchJson(get, '/users/7'), {attempts: 3, delayMs: 1000});
await jest.advanceTimersByTimeAsync(1000);
expect(get).toHaveBeenCalledTimes(2);
await jest.advanceTimersByTimeAsync(1000);
expect(get).toHaveBeenCalledTimes(3);
await expect(result).resolves.toEqual({id: 7});
});
test('gives up after three failures', async () => {
jest.useFakeTimers();
const get = jest.fn().mockResolvedValue({status: 500, body: null});
const result = retry(() => fetchJson(get, '/users/7'), {attempts: 3, delayMs: 1000});
const assertion = expect(result).rejects.toThrow('Server error 500');
await jest.runAllTimersAsync();
await assertion;
expect(get).toHaveBeenCalledTimes(3);
});go deeper
Recall that fake timers move timers, not promises, and that the Async timer methods must be awaited.
Explain why a timer scheduled after an await does not exist yet when a synchronous advance runs, and which Async variant replaces each method.
Diagnose stalled retries, deadlocked awaits and late-attached rejects under fake timers, and choose between early assertions and waitForUnhandledRejections.
Decide whether shared test helpers standardise on the Async clock methods, weighing one uniform pattern against the extra awaits it adds to purely synchronous timer tests.
## The setup A typical **retry helper** awaits an attempt, and if it fails, waits before the next one: ```js async function retry(task, {attempts, delayMs}) { let lastError; for (let i = 1; i <= attempts; i++) { try { return await task(); } catch (error) { lastError = error; if (i < attempts) await new Promise(resolve => setTimeout(resolve, delayMs)); } } throw lastError; } ``` A test installs fake timers, makes the task fail twice through a fetch wrapper that rejects on a 500, starts `retry(...)` without awaiting it, and calls `jest.advanceTimersByTime(2000)` expecting three attempts. Only one happens. ## Why the synchronous advance finds nothing to run Jest's fake clock replaces timer functions such as `setTimeout`; it does **not** replace native promises. A promise's continuation, the code after an `await`, runs as a **microtask**, and microtasks only run when the currently executing JavaScript yields. The sequence is: 1. `retry(...)` calls the task, which returns a pending promise, and `retry` suspends at `await task()`. 2. The test continues synchronously and calls `jest.advanceTimersByTime(2000)`. 3. The fake clock moves 2000 ms and looks for due timers. **There are none**: the `setTimeout` for the pause is only created after the first attempt's rejection has been processed, and that has not happened yet. `jest.getTimerCount()` at this point returns 0. 4. Only when the test yields do the microtasks run: the attempt rejects, `retry` creates the pause timer, and that timer then sits on a fake clock nobody is moving. ## The Async variants Jest pairs each clock-moving method with an Async variant that returns a promise and lets **scheduled promise callbacks run before the timers**, yielding between steps: | Synchronous | Async variant | |---|---| | `jest.advanceTimersByTime(ms)` | `await jest.advanceTimersByTimeAsync(ms)` | | `jest.runAllTimers()` | `await jest.runAllTimersAsync()` | | `jest.runOnlyPendingTimers()` | `await jest.runOnlyPendingTimersAsync()` | | `jest.advanceTimersToNextTimer(steps)` | `await jest.advanceTimersToNextTimerAsync(steps)` | With `await jest.advanceTimersByTimeAsync(1000)`, the first attempt rejects, the pause is scheduled, the clock reaches it, and the second attempt starts; a second call drives the third. The Async variants must themselves be **awaited**; an unawaited `jest.advanceTimersByTimeAsync(1000)` is just another promise the test ignores, and the assertions on the next line run before the clock has moved. They are unavailable with legacy fake timers. ## Two more traps in the same test - **Awaiting too early.** `await retry(...)` before moving the clock deadlocks: the helper waits for a timer, and the test waits for the helper, so nothing moves the clock and the test fails at its timeout (5000 ms by default). Start the helper, keep the promise, move the clock, then await the result. - **Attaching the rejection check late.** For the give-up path, the helper's promise rejects while the clock is being run. If the test only writes `await expect(result).rejects.toThrow(...)` **after** `await jest.runAllTimersAsync()`, the promise spends a moment rejected with no handler. The runtime reports that as an unhandled rejection, and Jest 30's default does not wait for the later `rejectionHandled` signal, so the test fails with the helper's own error although it does assert on it. The fix is to create the assertion first, `const assertion = expect(result).rejects.toThrow('Server error 500')`, run the timers, then `await assertion`. Jest 30 also has a **`waitForUnhandledRejections`** option, also available as a CLI flag, which gives one event-loop turn for `rejectionHandled`, `uncaughtException` or `unhandledRejection` to arrive before Jest decides, and so stops this kind of false failure. It is **off by default**, and the documentation warns it can add noticeable overhead to a fast suite; attaching the assertion early is the cheaper fix. ## A checklist for timer-plus-promise code - Never `await` the code under test before the clock has been moved; keep its promise. - Use the **Async** clock methods whenever an `await` sits between timers. - Attach `.resolves` or `.rejects` assertions before running the timers when the promise may settle during the run. - Use `jest.getTimerCount()` when a timer does not fire, to see whether it was ever scheduled. - Restore real timers with `jest.useRealTimers()` in `afterEach`. - When several promises chain between two timers, prefer one `await jest.advanceTimersByTimeAsync(ms)` per expected pause over sprinkling `await Promise.resolve()` calls: the number of microtask turns a chain needs is an implementation detail of the code under test, and a hand-counted number breaks when that code changes.
- How can you confirm that the synchronous advance ran before the retry timer existed?Call `jest.getTimerCount()` straight after `jest.advanceTimersByTime(2000)`. It returns 0, and the task mock shows a single call: the pause timer had not been created yet because the first attempt's rejection was still waiting as a microtask. After `await jest.advanceTimersByTimeAsync(1000)` the count of task calls rises to two.
- When would you turn on waitForUnhandledRejections in a Jest 30 suite?When code legitimately attaches handlers to rejected promises a moment late and rewriting every such test is not practical. It gives the runtime one event-loop turn to report `rejectionHandled` before Jest decides, which removes those false failures, at the cost of noticeable overhead in a fast suite. Attaching assertions before running timers is cheaper where you control the test.
- Fake timers make pending promises resolve when the clock moves.
- advanceTimersByTime(2000) always runs every attempt due within two seconds.
- Awaiting the retry helper first and then advancing the clock works fine.
- An awaited rejects assertion can never fail on an unhandled rejection.
- Jest 30 always waits an extra event-loop turn before reporting unhandled rejections.
Assumes Jest 30: its waitForUnhandledRejections option is off by default, so a rejection handled after the timers run can still fail the test; the Async timer methods themselves predate 30.