Mock a module with mock.module in node test
Replace an imported module in a test with mock.module from node:test, behind the experimental module mocks flag, and import the code under test afterwards.
Sometimes the thing to fake is an import, such as a config reader. mock.module swaps the module for one you define, but it is experimental, so it needs a flag.
export function apiUrl() {
return 'https://api.example.com';
}import { apiUrl } from './config.mjs';
export function usersEndpoint() {
return `${apiUrl()}/users`;
}import test, { mock } from 'node:test';
import assert from 'node:assert/strict';
test('uses the mocked config', async () => {
mock.module('./config.mjs', {
namedExports: { apiUrl: () => 'http://localhost:3000' },
});
const { usersEndpoint } = await import('./client.mjs');
assert.equal(usersEndpoint(), 'http://localhost:3000/users');
});node --experimental-test-module-mocks --test✔ uses the mocked config (4.2ms)Timings will differ. The specifier is resolved relative to the test file, and namedExports and defaultExport define what the fake module exposes. The code under test must be imported after the mock exists, which is why client.mjs is loaded with a dynamic import(). A static import at the top would load the real module first. See mock.module.
The API can change between releases, so pin your Node.js version. If you can pass the dependency as an argument instead, do that: a function parameter needs no mock at all.