Fixtures and mocking
Prerequisite: node-node-test-runner-and-assertions. Objective: Replace external clock. Local baseline: Node.js 22.16.0 on Linux, ESM. Each example is independent: save as main.mjs in a disposable directory and run node main.mjs. The author harness uses a five-second timeout. Static snippets are not ByteMind interactive execution.
How it works
Inject a clock or repository through a function parameter. This makes the dependency explicit and avoids changing global time. Use fresh fixtures for each test. The built-in mock tracker can record calls; a context-owned mock is restored at test completion. A mock verifies interactions with its simulated contract, not the real service. Hooks can set up and clean up resources; use try/finally when the resource is acquired inside a test.
Inject a deterministic clock
import assert from 'node:assert/strict';function valid(session, now){return now()<session.expiresAt;}const session={expiresAt:100};for(const t of [99,100,101]) console.log(t,valid(session,()=>t));assert.equal(valid(session,()=>100),false);Expected output:
99 true100 false101 falseThe contract explicitly rejects the expiry boundary, independent of wall-clock time.
Record a dependency call with the built-in mock tracker
import {mock} from 'node:test';import assert from 'node:assert/strict';const send=mock.fn(id=>({accepted:id}));function enqueue(id,send){return send(id);}try{assert.deepEqual(enqueue('job-7',send),{accepted:'job-7'});assert.equal(send.mock.callCount(),1);console.log(send.mock.calls[0].arguments[0]);}finally{mock.reset();}Expected output:
job-7The mock records the argument and returns a controlled response; no real queue receives a message.
Common mistakes
Do not mock the function under test or assert every incidental call. Global mocks shared by concurrent tests can interfere with each other.
Practice
Change the clock to the exact expiry timestamp; assert that the session is expired.
Reference candidate: node-fixtures-and-mocking-lookup (route unverified). Documentation: https://nodejs.org/download/release/v22.16.0/docs/api/test.html. Selected versioned documentation opened.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Fixtures and mocking — knowledge check
Apply the lesson to a fresh scenario and explain the evidence boundary.
Which clock makes an expiry test repeatable?
Does a mock queue verify broker delivery?
Why create a fresh fixture per test?