Mocking and test doubles in Node
Replacing dependencies in Node tests with mock.fn, mock.method, timers and mock.module, and intercepting HTTP with nock or msw instead of stubbing fetch.
The built-in test runnerMaking HTTP requests with fetch and undiciTesting HTTP APIs with Supertest
Mocking and test doubles in Node
The player loads from youtube-nocookie.com when you press play. Nothing reaches YouTube before that.
Not started
What you'll learn
- A test double replaces a real dependency so a test is fast, deterministic and safe. Stubs return canned answers, spies record how they were called, and mocks also carry expectations.
- `mock.fn(impl)` makes a function that records `callCount()` and every call's arguments and result. `mock.method(obj, 'name')` spies on or replaces an existing method, and `restore()` puts it back.
- `mock.timers.enable({ apis: ['setTimeout'] })` and `mock.timers.tick(ms)` run timer-based code, such as debouncing and retries, without waiting.
- `mock.module(specifier, { exports })` replaces an ES module. It needs the `--experimental-test-module-mocks` flag in Node 26, and the code under test must be imported after the mock is registered, using a dynamic `import()`.
- Mock at the edges you do not own, such as the network, clock, email and payment APIs. Do not mock the code you are testing, and prefer a real database to a mocked one.
- For HTTP, intercept the request instead of replacing `fetch`. `nock` matches requests by host and path, and `msw` defines handlers like a real API. Use only one of them per test process, because both patch the global `fetch`.
Why replace anything at all
A test should fail for one reason and give the same answer every time. Real dependencies break both rules. A payment API charges real money and goes down. The clock moves. An email sender makes the test wait seconds and clutters an inbox. A test double is a stand-in that removes that variability: you swap the real thing for something under your control.
There are three flavours, and the names get blurred. A stub returns canned answers. A spy records how it was called, so you can assert afterwards. A mock also carries expectations about its use. Node’s mock object blurs them deliberately, because one function can play all three. The rule that matters more than the vocabulary: mock the edges you do not own, such as the network, time and third-party services. Do not mock the code you are testing, and prefer a real database to a fake one, as argued in testing backend services with real dependencies. Over-mocking produces tests that pass while the product is broken.
Everything below ran on Node 26 using the runner from the built-in test runner.
mock.fn and mock.method
import { test, mock } from 'node:test';
import assert from 'node:assert/strict';
test('mock.fn records calls and can change behaviour', () => {
const f = mock.fn((x) => x + 1);
assert.equal(f(1), 2);
f.mock.mockImplementationOnce(() => 100);
assert.equal(f(1), 100); // the next call only
assert.equal(f(1), 2); // back to normal
assert.equal(f.mock.callCount(), 3);
assert.deepEqual(f.mock.calls[0].arguments, [1]);
});
mock.fn() takes an optional implementation and returns a function that keeps a log in .mock. callCount(), calls[i].arguments and calls[i].result are what you assert on.
To spy on something that already exists, use mock.method:
const math = { double: (x) => x * 2 };
const spy = mock.method(math, 'double');
math.double(4);
assert.equal(spy.mock.callCount(), 1);
spy.mock.restore(); // put the original back
With no implementation passed, the original still runs and the spy only watches. Inside a test, t.mock.fn and t.mock.method are restored automatically when that test ends, which is safer than the global mock for cleanup.
Controlling time
Timer-heavy code, such as debounce, retries with backoff and timeouts, is awkward to test with real waits. The runner can fake the clock:
mock.timers.enable({ apis: ['setTimeout'] });
const fn = mock.fn();
const d = debounce(fn, 500);
d(); d(); d();
mock.timers.tick(499); assert.equal(fn.mock.callCount(), 0);
mock.timers.tick(1); assert.equal(fn.mock.callCount(), 1);
mock.timers.reset();
Three rapid calls collapse into one that fires only after the full 500 ms, and the test finishes in about a millisecond. List the APIs you fake (setTimeout, setInterval, setImmediate, Date), and call reset() afterwards.
Replacing a module
The common need is to stop a service function from calling the real mailer:
// svc.js
import { send } from './mailer.js';
export async function signup(email) { await send(email, 'welcome'); return { email }; }
import { test } from 'node:test';
import assert from 'node:assert/strict';
test('signup sends a welcome mail', async (t) => {
const send = t.mock.fn(async () => {});
t.mock.module('./mailer.js', { exports: { send } });
const { signup } = await import('./svc.js'); // imported after the mock exists
await signup('a@b.c');
assert.deepEqual(send.mock.calls[0].arguments, ['a@b.c', 'welcome']);
});
Three details cost me time while testing this. First, mock.module is not available without a flag: node --test --experimental-test-module-mocks, and it prints an ExperimentalWarning. Without the flag, t.mock.module is not a function. Second, the option for the replacement’s exports is exports. The older name namedExports still works but emits a DeprecationWarning. Third, ES modules are cached, so if any earlier test in the same file already imported svc.js, it keeps the real mailer. Register the mock first and load the code under test afterwards with a dynamic import(). The conference talk was recorded when only mock.fn, mock.method and timers existed, so it does not cover this API.
When you can avoid module mocking, do. Passing the dependency in as an argument, as in createApp(pool) from the Supertest lesson, is simpler and needs no runner features.
Mocking HTTP
Your code calls fetch against a third-party API. You could stub the global:
t.mock.method(globalThis, 'fetch', async () =>
new Response(JSON.stringify({ id: 1 }), { status: 200 }));
That works, and it is a fine quick answer. But it replaces the whole function, so it passes even if your code builds the wrong URL or forgets a header. A better approach is an interceptor that lets the real fetch run and answers at the network layer. See making HTTP requests with fetch and undici for what is being intercepted.
nock matches requests by host, method and path and replies with a fixture:
import nock from 'nock';
const scope = nock('https://api.example.com').get('/users/1').reply(200, { id: 1, name: 'Ada' });
assert.deepEqual(await getUser(1), { id: 1, name: 'Ada' });
assert.ok(scope.isDone()); // the request really happened
nock('https://api.example.com').get('/users/2').reply(503);
await assert.rejects(getUser(2), /HTTP 503/);
nock.cleanAll();
msw (Mock Service Worker) defines handlers the way a real API route is defined, and works in browsers as well:
import { setupServer } from 'msw/node';
import { http, HttpResponse } from 'msw';
const server = setupServer(
http.get('https://api.example.com/users/:id', ({ params }) =>
HttpResponse.json({ id: Number(params.id), name: 'Grace' })),
);
server.listen({ onUnhandledRequest: 'error' });
// ... tests ...
server.use(http.get('https://api.example.com/users/:id', () => new HttpResponse(null, { status: 500 })));
server.close();
onUnhandledRequest: 'error' is worth setting, because it fails the test if code calls a URL you did not describe. I ran both against Node 26’s global fetch, with nock 15 and msw 3. One gotcha: putting both in one file failed with Failed to replace a global value at "fetch": already replaced, because both patch the same global. Choose one per project. Also test the failure responses, as above with 503 and 500, since retry and error handling are where real bugs live.
What the video covers
The video is Erick Wendel’s revo.js 2023 talk “What’s New in the Node.js Native Test Runner”. Its abstract lists three topics: an overview of the Node test runner, how to mock, stub and spy functions, and how watch mode works with the runner. That lines up with the first half of this lesson. It was uploaded by a conference-recording channel of about 400 subscribers and is a 28-minute talk, so only a portion is on mocking. It was recorded in 2023 on Node 20, so module mocking, which arrived later, is not in it. Its transcript was not available, so this description comes from the abstract. Net Ninja’s “go deeper” video covers the same ideas with Vitest’s vi.fn, and may be easier if you use that runner. The module mocking and the HTTP interception sections are carried entirely by this prose.
Where this fits
Good tests let you change code with confidence. When something still goes wrong, you need to look inside a running process, which is debugging with the inspector.
Check yourself
What is the difference between a stub, a spy and a mock?
A stub returns canned values so the code under test has something to work with. A spy wraps a real or fake function and records its calls so you can assert afterwards. A mock is a spy or stub that also carries expectations about how it should be used. In practice, `mock.fn` in `node:test` is used for all three: it records calls like a spy and can be given any implementation like a stub.
You use `t.mock.module('./mailer.js', ...)` but the real mailer still runs. What went wrong?
The module under test was already imported, so it holds the real binding. With ES modules the replacement only applies to imports that happen afterwards, so register the mock first and load the code under test with `await import('./svc.js')` inside the test. The `--experimental-test-module-mocks` flag must be on, or `mock.module` is not available.
Why use nock or msw rather than stubbing `globalThis.fetch` yourself?
A hand-rolled stub replaces the whole function, so it skips URL building, headers, status handling and body parsing, and it passes even when the code calls the wrong URL. An interceptor lets the real `fetch` run and answers at the network layer, so the full request path is exercised and each handler matches a specific method and URL. `msw` handlers can also be reused across tests and in the browser.
A test passes in isolation but breaks when another test file runs first, with `Failed to replace a global value at fetch: already replaced`. Why?
Two interception libraries, here nock and msw, both patched the global `fetch` in the same process and neither had been restored. Pick one library for the project, or keep them in separate test files so each test file runs in its own process, and always close or clean up the interceptor after the test.
Go deeper
Notes
Notes are saved to your account.
Everything else on this page works without one — progress and bookmarks keep themselves in this browser and come with you when you sign in. Notes are the one thing worth not trusting to a browser you might clear.
Your notes could not be loaded.