skip to content

In Node.js `node:test`, how does `mock.timers` let a test of retry or timeout logic run without waiting, and what does it not intercept?

level: middleimportance: should knowfreq 25%

answer

  1. enable() chooses which APIs
  2. tick() moves time forward
  3. Date shares the same clock
  4. destructured timer imports escape

basics

~20 s

mock.timers.enable() replaces setTimeout, setInterval, setImmediate, Date and a few related APIs with fakes on one virtual clock, and tick(ms) or runAll() fires due callbacks synchronously; timers destructured from node:timers and other time sources escape it.

solid answer

~40 s

`mock.timers.enable({ apis, now })` swaps the chosen APIs for fakes driven by one internal clock. With no `apis` list it mocks `setTimeout`, `setInterval` and `setImmediate` with their `clear*` functions, plus `Date`, on `globalThis`, `node:timers` and `node:timers/promises`; the Node 24.21 source also fakes `scheduler.wait` and `AbortSignal.timeout`. `tick(ms)` advances the clock, firing every callback that falls due and moving `Date` with it; `runAll()` fires everything pending; `setTime(ms)` moves `Date` only. On `t.mock.timers` the fakes are reset when the test ends. The gaps: a function destructured as `import { setTimeout } from 'node:timers'` is not supported, clocks such as `performance.now()` are not faked, and a `worker_threads.Worker` or child process keeps real timers of its own.

code

javascript · 22 lines
javascript
import assert from 'node:assert/strict';
import { test } from 'node:test';

function retryLater(job, delayMs) {
  return new Promise((resolve) => {
    setTimeout(() => resolve(job()), delayMs);
  });
}

test('retries after 30 s without waiting 30 s', async (t) => {
  t.mock.timers.enable({ apis: ['setTimeout', 'Date'], now: 0 });
  const job = t.mock.fn(() => 'done');
  const pending = retryLater(job, 30_000);

  t.mock.timers.tick(29_999);
  assert.equal(job.mock.callCount(), 0);

  t.mock.timers.tick(1);
  assert.equal(job.mock.callCount(), 1);
  assert.equal(Date.now(), 30_000);
  assert.equal(await pending, 'done');
});

go deeper

for a junior

Recall that mock.timers.enable() fakes setTimeout and friends, and that tick(ms) moves time forward so a timeout test finishes at once.

for a middle

Explain the apis and now options, the difference between tick(), runAll() and setTime(), and why Date and the timers share one clock.

for a senior

Spot why a fake-clock test still waits in real time, such as a destructured import, a performance.now() measurement or a worker, and fix it with a seam.

for a principal

Set the team rule that time-dependent code reads time through mockable globals or an injected clock, so the built-in fakes cover it without loader tricks.

## What `mock.timers` is for Code that waits, such as a retry with backoff, a request deadline, a cache entry that expires or an interval that flushes a buffer, is slow and flaky to test against the real clock. A test that really waits 30 seconds is useless, and one that waits 50 ms and hopes is a source of intermittent failures. The `node:test` module includes **`MockTimers`**, reachable as `mock.timers` on the top-level tracker or as `t.mock.timers` on a test context. It replaces Node's timer functions with fakes that run on a **virtual clock** the test moves by hand. `MockTimers` has been marked stable since Node 23.1.0. ## Turning it on `timers.enable([enableOptions])` takes two optional settings: - **`apis`**: which timers to fake. The API page lists `'setTimeout'`, `'setInterval'`, `'setImmediate'` and `'Date'`; the Node 24.21 source also accepts `'scheduler.wait'` and, since 24.16.0, `'AbortSignal.timeout'`, and with no list every supported name is faked. An unknown name throws `ERR_INVALID_ARG_VALUE`, and calling `enable()` twice throws `ERR_INVALID_STATE`. Faking a timer **implicitly fakes its clear function** too, so `clearTimeout` follows `setTimeout`. - **`now`**: the starting time for `Date.now()`, as a number of milliseconds or a `Date`. The default is `0`, so a test that forgets it sees dates in 1970. The fakes are installed in three places at once: the globals, the `node:timers` module and the `node:timers/promises` module. A `setTimeout` awaited through `node:timers/promises` resolves when the clock passes its delay. ## Moving time | Method | Fires due callbacks? | Moves the mocked `Date`? | |---|---|---| | `tick(ms)` | Yes, every one that falls due, in order | Yes, by `ms` (default `1`) | | `runAll()` | Yes, every pending one | Yes, to the furthest timer's time | | `setTime(ms)` | No | Yes, to exactly `ms` | `tick()` runs the callbacks **synchronously**, inside the `tick()` call, so an assertion on the next line already sees their effects. A promise resolved inside a callback still settles on the microtask queue, so the test awaits it before checking the result. `tick()` accepts only positive numbers, whereas real `setTimeout` tolerates a negative delay for web compatibility. `setTime()` is the odd one out: it moves `Date` without firing anything. The documentation's example sets the time past a pending timer's due point and shows the timer still waiting. Use it to model a clock jump, and `tick()` to model time passing. ## Cleaning up - On **`t.mock.timers`**, the runner resets the fakes after each test, as it does for every mock on the test context. - On the top-level **`mock.timers`**, call `mock.timers.reset()` yourself. `mock.reset()` resets the timers as well. - `MockTimers` implements `Symbol.dispose`, which calls `reset()`, so a `using` declaration can scope the fake clock to a block. ## What it does not intercept The fake clock is narrower than "time". Know where it stops before you trust a green test: 1. **Destructured imports.** The documentation states that destructuring, as in `import { setTimeout } from 'node:timers'`, is currently not supported. Code written that way keeps the real timer and the test waits for real, or times out. 2. **Other time sources.** Only the supported `apis` names are faked. Code that measures time some other way, for example `performance.now()` or `process.hrtime()`, still sees real time. 3. **Other threads and processes.** A `worker_threads.Worker` or a child process has its own timers, which the test's fake clock does not touch. 4. **Non-timer scheduling.** `process.nextTick()` and promise callbacks are not timers; they keep running as soon as the current operation finishes, whatever the virtual clock says. A related trap catches loops written with `await`. When code runs `await setTimeout(1000)` from `node:timers/promises` in a loop, the next timer is created only after the awaiting function resumes, and that resumption happens on the microtask queue after `tick()` has returned. A single `tick(5000)` therefore fires the first timer only. The test has to let the code resume, for example by awaiting a resolved promise, sometimes more than once, before it ticks again, or it has to await the function's own promise between steps. When a library you cannot change falls into one of these gaps, the usual fix is a seam: pass a clock or a delay function into the code under test, and give the test a fake. The ordering rules of real timers, such as `setTimeout` against `setImmediate`, belong to the event-loop lessons, not to this API.

  • A test enables `mock.timers`, calls `tick(5000)`, yet the code under test still waits five real seconds. What is the likely cause?
    The module probably destructured the timer, as in `import { setTimeout } from 'node:timers'`, which `MockTimers` does not support, so it holds the real function. Calling `timers.setTimeout()` through the module object, or using the global, puts it back under the fake clock; injecting a delay function avoids the dependency altogether.
  • When would you call `setTime()` instead of `tick()`?
    When the test needs `Date` to jump, for example to cross midnight or an expiry timestamp, without firing pending timers. `setTime()` moves only the mocked `Date`; `tick()` moves the clock and fires every timer that falls due along the way.

  • mock.timers also fakes performance.now() and process.hrtime()
  • setTime() fires every timer whose due time it passes
  • Destructuring setTimeout from node:timers is mocked like the global
  • A worker thread's timers follow the test's fake clock
  • tick() schedules callbacks for later instead of running them during the call

Assumes Node 24: MockTimers has been stable since Node 23.1.0, enable() takes the { apis, now } options object from 21.2.0, and AbortSignal.timeout became fakeable in 24.16.0.