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.
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.
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');
});$ 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.4t.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.