← Back to Node.js, page 3

nodejs-0059 · Medium mid

How do you create mocks, spies and fake timers with node:test?

mock.fn() creates a function that records calls and can have an implementation. mock.method(object, 'name') replaces a method and can restore it. mock.timers.enable() replaces setTimeout and setInterval so that tests move time with tick() and never wait. Mocks created in a test context are restored automatically.

Full answer

A test double stands in for a real dependency (the email service, the clock, the database) so a test is fast and predictable.

In node:test, the mock object gives you:

  • mock.fn(implementation?): a spy function. fn.mock.calls is an array of call records with arguments, result, error and this. fn.mock.callCount() returns the number of calls. fn.mock.mockImplementation(newFn) and mockImplementationOnce change behaviour.
  • mock.method(object, 'method', implementation?): replaces a method with a mock. The original is restored by mock.restoreAll() or by the test context (t.mock.method) when the test ends. Use { getter: true } or { setter: true } for accessors.
  • mock.timers.enable({ apis: ['setTimeout', 'setInterval', 'Date'] }): fake time. mock.timers.tick(ms) moves the fake clock forward and runs due timers. Always call mock.timers.reset() (or use t.mock.timers) so later tests get real timers.
  • mock.module and mock.getter are available in newer versions for module-level mocks (check your version).

Guidelines:

  • Prefer passing dependencies as arguments (dependency injection). Then a test passes a mock.fn() and needs no patching.
  • Check behaviour that matters (the email was sent once to the right address), not private details.
  • Do not mock everything. A test full of mocks proves only that the mocks work.
  • Use the context version (t.mock) inside tests so clean-up is automatic.
javascript
const { mock } = require('node:test');
const assert = require('node:assert/strict');

// Code under test: notify a student, and retry the send after 1 hour if it fails.
function createNotifier({ sendEmail, setTimeoutFn = setTimeout }) {
  return async function notify(student, message) {
    try {
      await sendEmail(student.email, message);
      return 'sent';
    } catch {
      setTimeoutFn(() => notify(student, message), 60 * 60 * 1000);
      return 'retry scheduled';
    }
  };
}

async function main() {
  // 1. A spy function with a changing behaviour.
  const sendEmail = mock.fn(async () => { throw new Error('mail server down'); });
  mock.timers.enable({ apis: ['setTimeout'] });

  const notify = createNotifier({ sendEmail });
  const student = { email: 'asha@example.com' };

  console.log('first call:', await notify(student, 'Result published'));
  console.log('send calls so far:', sendEmail.mock.callCount());

  // 2. The server recovers. Move the fake clock one hour ahead.
  sendEmail.mock.mockImplementation(async () => {});
  mock.timers.tick(60 * 60 * 1000);
  await new Promise((resolve) => setImmediate(resolve)); // let the retry promise settle
  console.log('send calls after one fake hour:', sendEmail.mock.callCount());
  console.log('arguments of the last call:', sendEmail.mock.calls.at(-1).arguments);
  mock.timers.reset();

  // 3. mock.method replaces a method and restores it.
  const calendar = { today: () => '2026-12-04' };
  mock.method(calendar, 'today', () => '2027-01-01');
  console.log('mocked method:', calendar.today());
  mock.restoreAll();
  console.log('restored method:', calendar.today());

  assert.equal(sendEmail.mock.callCount(), 2);
}

main();

No real hour passes. The fake clock moves forward and runs the retry timer at once. Save it as app.js and run it with node app.js. Output (Node.js v24.22.1, same on two runs): first call: retry scheduled send calls so far: 1 send calls after one fake hour: 2 arguments of the last call: [ 'asha@example.com', 'Result published' ] mocked method: 2027-01-01 restored method: 2026-12-04

Key points

  • mock.fn is a spy with call records.
  • mock.method replaces and restores methods.
  • mock.timers.tick moves fake time without waiting.
  • Use t.mock inside tests for automatic restore.
  • Prefer dependency injection to patching.

Common mistakes

  • Forgetting mock.timers.reset() and breaking later tests.
  • Mocking the function under test instead of its dependency.
  • Asserting on the number of calls only and not on the arguments.
  • Patching global objects without restoring them.

Follow-ups

  • How does t.mock differ from the global mock?
  • How would you mock fetch in tests?
  • What is the difference between a mock, a stub and a spy?

Tips

  • Define the three words stub, spy, mock in one line each.
  • Say you prefer injection to patching.
  • Show fake timers as the answer to slow tests.