Skip to content
jshacks.dev
Testing

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.

1 min read
Summarize in AI

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.

config.mjsJavaScript
export function apiUrl() {
  return 'https://api.example.com';
}
client.mjsJavaScript
import { apiUrl } from './config.mjs';

export function usersEndpoint() {
  return `${apiUrl()}/users`;
}
client.test.mjsJavaScript
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');
});
Shell
node --experimental-test-module-mocks --test
Text
✔ 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.

Also inNode.js
Taggednode 24
Share

More snippets

Node.js

Read a text file with fs promises

Read a text file with fs promises in Node.js: await readFile with an encoding, and catch the error code when the file is missing. Node.js 24.

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.