Skip to content
jshacks.dev
Node.js

Mock fetch with node:test mock

Replace globalThis.fetch inside a test with t.mock.method from node:test, then assert the URL it was called with. Works on Node.js 24 with no library.

2 min read
Summarize in AI

A function that calls fetch should not hit the network in a unit test. The built-in test runner can swap globalThis.fetch for a fake and put the original back when the test ends.

fetch.test.mjsJavaScript
import { test } from 'node:test';
import assert from 'node:assert/strict';

async function getUser(id) {
  const res = await fetch(`https://api.example.test/users/${id}`);
  return res.json();
}

test('getUser reads the JSON body', async (t) => {
  const fetchMock = t.mock.method(globalThis, 'fetch', async () =>
    Response.json({ id: 7, name: 'Ada' }),
  );

  const user = await getUser(7);

  assert.deepEqual(user, { id: 7, name: 'Ada' });
  assert.equal(fetchMock.mock.callCount(), 1);
  assert.equal(fetchMock.mock.calls[0].arguments[0], 'https://api.example.test/users/7');
});
Text
$ node --test fetch.test.mjs
✔ getUser reads the JSON body (1.8ms)
ℹ tests 1
ℹ suites 0
ℹ pass 1
ℹ fail 0
ℹ cancelled 0
ℹ skipped 0
ℹ todo 0
ℹ duration_ms 52.4

t.mock.method(object, name, implementation) wraps the property with a spy and records every call in mock.calls, so you assert on arguments instead of reading a log. Because the mock hangs off the test context t, the runner restores the real fetch when the test finishes, and one test cannot leak a fake into the next. Timings differ per run. See MockTracker.

The fake returns a real Response, so res.json() and res.ok behave as in production. It only intercepts code that reads the global fetch at call time; a module that captured const { fetch } = globalThis at import keeps the original. To test real HTTP behaviour, such as retries on a 503, start a local server instead.

Taggednode 24
Share

More snippets

APIs

Fetch JSON and handle HTTP errors

Fetch JSON in the browser or Node.js 24 and throw on 404 or 500 yourself, because fetch only rejects on network failure and does not check the status.

1 min read

Get new posts by email

We send one email when a new post is published. No spam.

Unsubscribe in one click. No spam, ever.