In Node.js `node:test`, how do `mock.fn()` and `mock.method()` record calls, and when does the original behaviour come back?
answer
- a Proxy with a mock property
- calls entries: arguments, result, error, this
- t.mock versus the top-level mock
- restored when the test ends
basics
~20 sBoth return a Proxy whose .mock property records every call's arguments, result, error and this; mocks made through the test context's t.mock are restored when the test ends, while the top-level mock keeps its mocks until mock.reset() or mock.restoreAll().
solid answer
~40 s`mock.fn(original, implementation, { times })` wraps a function, and `mock.method(object, name, implementation)` replaces `object[name]` with the same kind of wrapper, calling the original when you give no implementation. Each returns a Proxy whose `.mock` is a `MockFunctionContext`: `calls` gives a copy of every call's `arguments`, `result`, `error`, `this`, `target` and `stack`, `callCount()` counts them, and `mockImplementation()`, `mockImplementationOnce()` and `resetCalls()` change behaviour mid-test. Restoration depends on the tracker. Mocks made with `t.mock` are reset automatically when that test finishes. The top-level `mock` export is shared by the whole file, so its mocks persist until you call `mock.reset()` or `mock.restoreAll()`. Replacing a whole module needs `mock.module()` and the `--experimental-test-module-mocks` flag.
code
javascript · 25 linesimport assert from 'node:assert/strict';
import { test } from 'node:test';
const mailer = {
send(to, body) {
throw new Error('no network in tests');
},
};
function notify(user) {
return mailer.send(user.email, `Hi ${user.name}`);
}
test('notify sends one mail to the user', (t) => {
const send = t.mock.method(mailer, 'send', () => 'queued');
assert.equal(notify({ email: '[email protected]', name: 'Ann' }), 'queued');
assert.equal(send.mock.callCount(), 1);
assert.deepEqual(send.mock.calls[0].arguments, ['[email protected]', 'Hi Ann']);
assert.equal(send.mock.calls[0].this, mailer);
});
test('the stub is gone in the next test', () => {
assert.throws(() => mailer.send('x', 'y'), /no network/);
});go deeper
Recall that mock.fn() wraps a function and mock.method() replaces one on an object, and that assertions read .mock.calls and .mock.callCount().
Explain the difference between t.mock and the top-level mock, what each calls entry records, and how times and mockImplementationOnce() change behaviour for a set number of calls.
Diagnose order-dependent failures caused by a global mock that was never reset, and explain why a destructured import escapes mock.method() and what to do instead.
Decide how far a team leans on mock.module() while it is behind an experimental flag, and prefer injected seams that keep tests independent of loader behaviour.
## Two ways to make a mock The `node:test` module ships its own mocking API, so a test can spy on or stub a function without any library. Every mock is created by a **`MockTracker`**, and there are two of them to choose from: - the **top-level `mock` export** (`import { mock } from 'node:test'`), one tracker shared by everything in the file; - the **test context's tracker**, `t.mock`, a fresh `MockTracker` for each test. The functions are the same on both. The difference is who cleans up, which is covered below. ## `mock.fn()`: a recording function `mock.fn([original[, implementation]][, options])` returns a **Proxy** around a function. With no arguments it wraps a no-op. With `original` alone, calls run `original`. With both, calls run `implementation` instead, and the `times` option limits that: after `times` calls the mock goes back to `original` on its own. The Proxy carries a `mock` property, a **`MockFunctionContext`**, which is where assertions look: | Member | What it gives you | |---|---| | `calls` | A copy of the call log; each entry has `arguments`, `result`, `error`, `this`, `target` (the class, for a constructor call) and `stack` | | `callCount()` | The number of calls, cheaper than `calls.length` because `calls` copies the array | | `mockImplementation(fn)` | Swaps the behaviour for every later call | | `mockImplementationOnce(fn[, onCall])` | Swaps it for one call number only, then reverts | | `resetCalls()` | Clears the log but keeps the mock in place | | `restore()` | Puts the original behaviour back | For an `async` function, `result` holds the promise it returned, so a test awaits that value or asserts on the resolved data separately. ## `mock.method()`: replacing a property on an object `mock.method(object, methodName[, implementation][, options])` swaps `object[methodName]` for a mock. When you pass no implementation the mock **calls the original**, so it acts as a spy: the real behaviour runs and the calls are recorded. When you pass one, it is a stub. A few details matter in practice: - If `object[methodName]` is not a function, `mock.method()` throws. - `mock.getter()` and `mock.setter()` are shorthands for `mock.method()` with the `getter` or `setter` option. - `mock.property(object, name[, value])`, added in Node 24.3.0, mocks a plain value and records each read and write in `accesses`. - Only the property on that object changes. Code that copied the function out beforehand, for example `const { readFile } = fsPromises` at module load, still holds the original and is not observed. ## When the original comes back This is where the two trackers differ: 1. **`t.mock`**: after each test completes, the runner calls `reset()` on that test's tracker, so every mock it created is restored with no cleanup code. 2. **Top-level `mock`**: nothing is restored automatically. A stub installed in one test is still active in the next test of the same file. The documentation recommends calling `mock.reset()` yourself when you use the global tracker heavily. 3. **`mock.reset()` versus `mock.restoreAll()`**: both restore the originals. `reset()` also disassociates the mocks from the tracker, so the tracker can no longer manage them; `restoreAll()` keeps the association. Under the default process isolation, leftovers cannot cross into another file, because each file is a separate process. They still leak between tests inside one file, which is the usual source of a test that passes alone and fails when run with its neighbours. ## Scoping a stub to some calls Not every stub should last the whole test. Three tools narrow it: - the **`times`** option on `mock.fn()` or `mock.method()`, which uses the replacement for the first *n* calls and then returns to the original by itself; - **`mockImplementationOnce(fn, onCall)`**, which changes one specific call number, for example making the second call to a client throw so the retry path runs; - **`restore()`** on a single mock's context, which puts that one function back while other mocks in the test stay active. Together they let one test walk a failure-then-success sequence without writing a stateful fake by hand. ## Mocking a whole module `mock.method()` cannot replace what a module exports to its importers. For that, `mock.module(specifier, { exports })` mocks an ECMAScript, CommonJS, JSON or builtin module, but only when Node runs with **`--experimental-test-module-mocks`**, and its stability is still *early development* in Node 24. It does not reach back in time: references to the original module taken before the mock are unaffected, which is why the module under test is loaded with a dynamic `import()` after `mock.module()` runs. In Node 24 the `defaultExport` and `namedExports` options are deprecated in favour of `exports`.
- A stub made with the top-level `mock` in one test leaks into the next test of the same file. How do you fix it?Either switch to `t.mock`, whose tracker the runner resets after each test, or keep the global tracker and call `mock.reset()` or `mock.restoreAll()` in an `afterEach` hook. `t.mock` is the cleaner default, because the cleanup cannot be forgotten.
- Why does `mock.method(fsPromises, 'readFile')` not see calls from a module that destructured `readFile` at load time?`mock.method()` replaces the property on that object. A module that ran `const { readFile } = fsPromises` copied the original function into its own binding before the mock existed, so its calls never touch the property. Mock at a seam the code reads at call time, inject the dependency, or use `mock.module()` before that module loads.
- Mocks created with the top-level mock are restored after every test
- mock.method with no implementation stops calling the real method
- mock.module works without any command-line flag in Node 24
- Mocking a method also changes references other modules copied earlier
- For an async mock, calls[0].result holds the resolved value
Assumes Node 24: mock.property arrived in 24.3.0, and mock.module still needs --experimental-test-module-mocks, with defaultExport and namedExports deprecated in favour of exports.