Skip to content
Tutorials Center
My learning

Topics

Lesson 102 of 133 ยท Testing

Mocks, Spies and Fake Timers

Learn mocking in Node.js with node:test - mock.fn, mock.method, spies, fake timers with mock.timers, dependency injection and hand-written fakes.

Real programs talk to things you do not want to touch during a test: a payment API, the clock, a database, the file system, a random number generator. A good test must be fast, repeatable and independent of the outside world. The tools that make this possible are test doubles: stand-ins that replace a real dependency while the test runs.

Node.js has them built in. The node:test module (see The Built-in Test Runner) provides mock.fn() and mock.method() for function mocks and spies, and mock.timers for controlling time. This lesson explains the vocabulary, shows every tool, and then spends equal time on the design side, because the best way to test code is to write it so that it barely needs mocks. Assertions are covered in The assert Module.

A quick vocabulary

People use these words loosely, but the distinctions help you choose.

  • A stub returns canned answers. "When asked for the weather, always say 18 degrees."
  • A spy records how it was called (arguments, results, how many times) while usually running the real code.
  • A mock in the strict sense is a spy with expectations: it knows what calls it should receive.
  • A fake is a simplified working implementation, such as an in-memory database that behaves like the real one.

Node's mock.fn() creates a function that does all of the first three: it can have any behavior you give it and it records every call. Whether you call the result a stub or a spy depends on how you use it.

mock.fn: a function that remembers

mock.fn(implementation) returns a function. Call it like any function; afterwards inspect fn.mock, which holds a calls array with one entry per call, and helpers such as callCount(). Each entry has arguments, result, error, this and stack.

Node.js mock.fn records every call

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

If you call mock.fn() with no argument, you get a function that does nothing and returns undefined, which is perfect when you only care that something was called (a callback, an event handler, a logger).

Changing behavior in the middle of a test

Error handling code is hard to reach with real dependencies. A mock lets you script the sequence: succeed once, fail once, succeed again. Use fn.mock.mockImplementationOnce(impl, onCall) for a one-time behavior and fn.mock.mockImplementation(impl) for a permanent replacement.

Node.js Scripting a flaky dependency

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

Without a mock you would have had to spin up a flaky server to test the retry loop. Here the whole scenario is three lines.

mock.method: spying on and replacing methods

mock.method(object, 'name', replacement?) replaces a method on an existing object with a mock. If you pass no replacement, the mock wraps the original: it still runs the real code but records the calls, which makes it a spy. Call .mock.restore() to put the original back.

Node.js Spying on a real object

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

For properties that are getters or setters, pass { getter: true } or { setter: true } as the options, or use the shortcuts mock.getter() and mock.setter(). mock.property() does the same for plain data properties, but it is newer, so check that your Node version has it before depending on it.

Always restore

A mock installed on a shared object or on a module's exports stays installed until you remove it, and the next test inherits the leftovers. The safest habit is to create mocks through the test context: inside a test, t.mock.fn(), t.mock.method() and t.mock.timers are restored automatically when that test ends. Use the global mock import only for quick scripts, and call mock.reset() or mock.restoreAll() yourself if you do.

NODE
import { test } from 'node:test';
import assert from 'node:assert/strict';

// sketch: signUp is your own function
test('sends a welcome email', (t) => {
  const send = t.mock.fn();          // restored after this test
  t.mock.method(console, 'log');     // restored after this test

  signUp({ email: '[email protected]' }, send);

  assert.equal(send.mock.callCount(), 1);
});

Dependency injection: the design that makes mocking easy

Look at the examples above: checkout(cart, log) and fetchWithRetry(fetchPage, 5) receive their collaborators as parameters. That is dependency injection, and it is just a fancy name for "do not reach for a global, ask for it". Production code passes the real thing; tests pass a mock. No patching of modules, no magic.

Compare two versions of a function that expires old sessions:

NODE
// Hard to test: hidden dependencies on the clock and the store
import { store } from './store.js';
export function expireSessions() {
  const now = Date.now();
  for (const s of store.all()) {
    if (s.expiresAt < now) store.remove(s.id);
  }
}
NODE
// Easy to test: everything it needs is passed in
export function expireSessions(store, now) {
  for (const s of store.all()) {
    if (s.expiresAt < now) store.remove(s.id);
  }
}

The second version needs no mock library at all. A test can pass a plain object and a fixed number.

Node.js Injection beats patching

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

A sensible default for the clock, the random generator or a file path is a parameter with a default value: function createId(random = Math.random). Callers do not notice; tests inject a deterministic function.

Fake timers

Code that waits (a debounce, a retry delay, a 30-second timeout, a cache that expires) is painful to test with real time: the test is slow, and slow tests are skipped. mock.timers replaces the timer functions with versions you control by hand.

Call mock.timers.enable({ apis: [...] }). The apis array lists what to fake: 'setTimeout', 'setInterval', 'setImmediate' and 'Date'. Then move time forward with mock.timers.tick(milliseconds). Timers whose moment arrives during the tick fire, in order, synchronously. When finished, call mock.timers.reset() (or use t.mock.timers, which resets itself).

Node.js Advancing time by hand

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

The whole script runs instantly, yet the output shows what would happen over a full second. The interval fires at 400 ms and again at 800 ms, so the second tick(600) prints one more interval tick and then the one-shot at 1000 ms, in the order their times come due.

Faking the date

Adding 'Date' to apis fakes Date.now() and new Date(). By default the fake clock starts at 0 (January 1, 1970); pass now (a number or a Date) to start somewhere else. tick() advances the date together with the timers.

Node.js A fake clock for Date

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

Timers and promises

Async code usually waits through a promise wrapper around the global setTimeout, and faking 'setTimeout' covers that. Start the waiting call without awaiting it, tick the clock, then await the result.

The promise-returning setTimeout from node:timers/promises also resolves under fake time, but in Node 24.22 a real timer is still left running behind it, so a script can stay alive until the real delay passes. In tests that fake time, wrap the global setTimeout yourself as shown below.

Node.js Fake timers with async code

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

Fake timers affect the whole process. Two tests running at the same time, both faking timers, will confuse each other, and node:test itself uses timers for its own bookkeeping in some situations. Keep tests that fake time sequential, enable the fakes at the start of the test and reset them at the end (the t.mock.timers form does this for you).

Module mocking

You will often want to replace a whole imported module, for example node:fs or your own ./db.js. Node has mock.module(specifier, options) for this, but at the time of Node 24 it is experimental and gated behind a flag (--experimental-test-module-mocks). Our in-browser runner cannot pass flags, so mock.module is not available here: the function does not even exist on mock unless the flag is on.

Terminal
# On your machine, with the flag:
node --experimental-test-module-mocks --test
NODE
// Read-only: needs the flag above
import { test, mock } from 'node:test';

test('uses a mocked module', async (t) => {
  t.mock.module('./clock.js', {
    namedExports: { now: () => 1_700_000_000_000 },
  });
  const { stamp } = await import('./report.js'); // import AFTER mocking
  // ...
});

Treat it as a last resort. Module mocking couples a test to the file layout and import order, and it behaves differently for CommonJS and ES modules. Dependency injection works in every Node version and has no flags.

How much mocking is too much?

A test with more mock setup than assertions is a warning sign. Pitfalls professionals learn the hard way:

  • Testing the mock. If everything in the test is a mock, the test only proves that your mock does what you told it to. Keep at least one layer real.
  • Brittle call assertions. assert.equal(db.query.mock.callCount(), 3) breaks when someone adds a harmless cache. Assert outcomes (the returned value, the stored data) before asserting interactions (which functions were called).
  • Mocks that drift. A hand-written stub keeps returning the old response format after the real API changed, and tests stay green while production breaks. Share one fake between tests and verify it against the real service in an occasional integration test.
  • Mocking what you do not own. Wrapping a third-party library in a small module of your own and mocking that wrapper is safer than mocking the library's internals.
  • Leaking mocks. Use t.mock so everything is restored automatically.

Prefer real, cheap things when you can: an in-memory SQLite database is both real and fast, and a real HTTP server on a loopback port (see Testing HTTP Servers and CLIs) beats a mocked fetch. Use a mock when the real thing is slow, random, costly, dangerous (sends emails), or hard to put into the failure state you want to test.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. What does fn.mock.calls[0].arguments contain after fn(1, 2)?

    Each entry in mock.calls records the arguments array of that call. The return value is in result, the receiver in this.
  2. 2. How do you turn mock.method(obj, 'save') into a spy that still runs the original code?

    Without a replacement, mock.method wraps the original method, so calls are recorded and the real behavior still happens.
  3. 3. Why prefer t.mock.fn() inside a test over the global mock.fn()?

    The test context tracks what it created and restores it at the end, so one test cannot leak a mock into the next.
  4. 4. With mock.timers enabled for setTimeout, what advances a pending timer?

    Fake timers never fire on their own. tick(ms) moves the fake clock forward and runs every timer that becomes due, in order.
  5. 5. Which design change makes a function easiest to test without any mocking library?

    That is dependency injection: the test hands the function a plain fake or a fixed value, and no patching is needed.

Summary

  • Test doubles replace slow, random or dangerous dependencies: stubs return canned values, spies record calls, fakes are simplified working versions.
  • mock.fn() creates a recording function; inspect fn.mock.calls and callCount(), script behavior with mockImplementationOnce.
  • mock.method() without a replacement spies on the real method; with one it stubs it; restore() undoes it.
  • Create mocks with t.mock inside tests so they clean up automatically.
  • mock.timers.enable({ apis }) plus tick(ms) runs timers and a fake Date instantly and deterministically.
  • mock.module needs --experimental-test-module-mocks in Node 24 and does not run in our editor.
  • Design with dependency injection first, mock second, and assert outcomes before interactions.

Next: Testing HTTP Servers and CLIs