In Jest 30, what do jest.useFakeTimers, advanceTimersByTime, runAllTimers and runOnlyPendingTimers each do to code waiting on setTimeout?
answer
- a clock that moves only when told
- by a duration, to empty, or one round
- timers that schedule more timers
- restore real timers between tests
basics
~20 sjest.useFakeTimers swaps setTimeout, setInterval, Date and related APIs for a fake clock that moves only on command. advanceTimersByTime moves it by a duration, runAllTimers runs until no timers remain, and runOnlyPendingTimers runs just the timers already queued.
solid answer
~40 s`jest.useFakeTimers()` replaces the global timer functions, `Date`, `performance.now()` and a few others with versions driven by a fake clock, for every test in the file until `jest.useRealTimers()` restores them; calling `useRealTimers` in `afterEach` keeps tests independent. Nothing scheduled fires until the test moves the clock. `jest.advanceTimersByTime(1000)` moves it 1000 ms and runs every timer due in that window, including timers scheduled during it. `jest.runAllTimers()` keeps running until the queue is empty, so a timer that always schedules another one aborts with `Aborting after running 100000 timers, assuming an infinite loop!`. `jest.runOnlyPendingTimers()` runs only the timers queued at the moment of the call, one step at a time. `jest.setSystemTime()` changes what `Date` reports without firing any timer.
code
javascript · 11 lines// retryLater.js: calls attempt() after delayMs; while it returns false, tries again, up to maxAttempts
function retryLater(attempt, {delayMs, maxAttempts}) {
let tries = 0;
const run = () => {
tries += 1;
if (!attempt() && tries < maxAttempts) setTimeout(run, delayMs);
};
setTimeout(run, delayMs);
}
module.exports = {retryLater};go deeper
Recall that fake timers stop time until the test moves it, and that advanceTimersByTime moves it by a set number of milliseconds.
Explain how runAllTimers, runOnlyPendingTimers and advanceTimersByTime differ on recursive timers, and why useRealTimers belongs in afterEach.
Pick the method that matches the code's timer shape, and recognise a runaway-timer abort or a leaked fake clock from its symptom.
Weigh enabling fake timers globally for a suite against per-file opt-in, given the hangs a forgotten real-timer test can cause.
## Why fake timers exist Code that waits with `setTimeout` or `setInterval` is slow and nondeterministic to test with a real clock: a retry helper that pauses for a second between attempts would make every test take seconds, and assertions about "not yet called" would race the clock. Jest's **fake timers** replace the clock with one that **stands still until the test moves it**, so a test can check the state before a delay, move time forward, and check again, all in microseconds. ## Installing and removing the fake clock `jest.useFakeTimers()` installs the modern implementation, which is the default. It swaps out: - `setTimeout`, `clearTimeout`, `setInterval`, `clearInterval`, `setImmediate`, `clearImmediate`; - `Date`, `performance.now()` and `queueMicrotask()`; - in the `node` test environment `process.hrtime` and `process.nextTick()`, and in the jsdom environment `requestAnimationFrame()`, `requestIdleCallback()` and their cancel functions. The call is a **global operation for the whole test file**: it stays in effect, across tests, until `jest.useRealTimers()` restores the originals. The documented pattern is `jest.useRealTimers()` in an `afterEach` so one test's fake clock never leaks into the next. Calling `jest.useFakeTimers()` again resets the fake clock's state and reinstalls it with whatever options are passed, such as `{doNotFake: ['performance']}` to leave one API real, `{now: 0}` to start the clock at a fixed instant, or `{timerLimit: 5000}` to change the runaway limit. Native promise callbacks are **not** on the fake clock. That matters as soon as the code under test awaits something between timers, which is the subject of the Async variants of these methods. ## Moving the clock | Method | Runs | Stops when | |---|---|---| | `jest.advanceTimersByTime(ms)` | every timer due within the next `ms`, including ones scheduled during the advance that fall inside the window | the clock has moved `ms` | | `jest.runOnlyPendingTimers()` | only the timers already queued when it is called | those have run; timers they schedule are left pending | | `jest.runAllTimers()` | every timer, including ones scheduled by timers it runs | the queue is empty, or the timer limit (100000 by default) is hit | | `jest.advanceTimersToNextTimer(steps)` | the next timer, or the next `steps` timers | that many have fired | | `jest.clearAllTimers()` | nothing; it discards every pending timer | immediately | Two helpers make assertions easier: `jest.getTimerCount()` returns how many fake timers are still pending, and `jest.now()` returns the fake clock's current time. The choice between them follows the shape of the code: 1. For a **single delay** you want to bracket, use `advanceTimersByTime`: advance to one millisecond before the deadline and assert nothing happened, then advance one more and assert it did. 2. For a **chain of retries with a finite end**, `runAllTimers` drains them all in one call. 3. For a **timer that always reschedules itself**, such as a heartbeat built from `setInterval` or a recursive `setTimeout`, `runAllTimers` never empties the queue and aborts with `Aborting after running 100000 timers, assuming an infinite loop!`. Step through it with `runOnlyPendingTimers` or a bounded `advanceTimersByTime` instead. ## Options worth knowing `jest.useFakeTimers()` accepts an options object that changes how the fake clock behaves: - **`advanceTimers`**: `true` makes the fake clock move by itself, 20 ms for every 20 ms of real time, or by a custom delta when given a number; useful for code that must not stall when nobody moves the clock. The default is `false`. - **`doNotFake`**: a list of APIs to leave real, for example `['nextTick', 'performance']`. - **`now`**: the starting time of the fake clock, which otherwise starts at the real `Date.now()`. - **`timerLimit`**: how many timers `runAllTimers` will run before aborting, 100000 by default. - **`legacyFakeTimers`**: switches to the older implementation, which fakes fewer APIs and lacks several of the methods above. ## Changing the date without firing timers `jest.setSystemTime(new Date('2030-01-01T00:00:00Z'))` changes what `Date` and `Date.now()` report, as if a user had changed the system clock. It **does not fire timers**: a `setTimeout` scheduled for 1000 ms still fires after the clock is advanced by 1000 ms, not when the date jumps. Use it to test code that reads the current date, such as an expiry check, and use the advance methods to test code that waits. ## Common mistakes - Forgetting `jest.useRealTimers()`, so a later test in the same file that relies on a real delay hangs until its timeout. - Expecting `runAllTimers` to cope with an interval; any self-rescheduling timer needs a bounded method. - Asserting on `Date.now()` after `advanceTimersByTime` and being surprised it moved: the fake `Date` advances with the fake clock. - Calling the synchronous methods when the code under test awaits promises between timers; the Async variants exist for that case.
- How do you turn Jest's fake timers on for every test file without calling jest.useFakeTimers in each?Set the `fakeTimers` option in the Jest configuration to `{enableGlobally: true}`. The same object can carry defaults such as `timerLimit` or `doNotFake`; a `jest.useFakeTimers(options)` call in a file overrides them for that file, and `jest.useRealTimers()` still switches back to real timers.
- Why does jest.runAllTimers() throw on code that uses setInterval?An interval reschedules itself every time it fires, so the queue never empties. `runAllTimers` keeps going until it reaches the timer limit, 100000 by default, and then throws `Aborting after running 100000 timers, assuming an infinite loop!`. Use `advanceTimersByTime` for a bounded span or `runOnlyPendingTimers` to step one round.
- What do Jest's legacy fake timers change about this API?`jest.useFakeTimers({legacyFakeTimers: true})` switches to the older implementation, which replaces the timer functions with Jest mock functions and does not fake `Date`. Several methods are unavailable with it, including `jest.setSystemTime`, `jest.getRealSystemTime` and the Async variants such as `advanceTimersByTimeAsync`.
Fake timers work like a board game's turn track: nothing promised for turn five happens until a player moves the marker. advanceTimersByTime moves it a fixed number of turns, runOnlyPendingTimers plays out the moves already announced, and runAllTimers keeps playing until nobody has a move left, which never happens if every move announces another.
- jest.useFakeTimers() only affects the test it is called in.
- runAllTimers is safe for setInterval because it runs each timer once.
- jest.setSystemTime() fires every timer that falls before the new date.
- advanceTimersByTime skips timers that get scheduled during the advance.
- Fake timers also make awaited promises resolve when the clock moves.