Inject dependencies and use test doubles
Quick answer
A test double replaces a dependency with a controlled substitute. A stub supplies predefined behavior; a spy records calls. These terms describe roles, and frameworks may combine them.
How it works
Inject a callable or small interface instead of reading a global service directly. A stub can return a fixed value or reject to exercise the error path. Node test mocks provide mock.fn and call metadata; use t.mock in a test callback for scoped lifecycle management. Verify important interactions only when they are part of the contract, such as sending one notification. Restore modified dependencies after each test. A fake transport does not prove real HTTP interoperability.
Local examples
Run in Node.js v22.16.0 as a CommonJS script. No interactive debugger attached; actual ByteMind editor support is unverified.
(async () => {async function load(id,lookup){const row=await lookup(id);return row.qty;}const stub=async id=>({id,qty:3});console.log(await load("x",stub));})()Expected console output:
3The injected stub supplies the expected record.
Run in Node.js v22.16.0 as a CommonJS script. No interactive debugger attached; actual ByteMind editor support is unverified.
(async () => {const {mock}=require("node:test");const send=mock.fn(x=>x.toUpperCase());const result=send("ok");console.log(result,send.mock.callCount(),send.mock.calls[0].arguments[0]);})()Expected console output:
OK 1 okThe mock records the call and retains its argument while returning the implementation result.
Common mistakes
Do not mock the function you intend to test. Avoid requiring exact private helper call order when only the final behavior is public.
Practice
Inject a repository that returns one record, then a rejecting repository, and verify both outcomes.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Inject dependencies and use test doubles — Knowledge Check
Apply the concept and reason about local example output.
What does a stub primarily provide?
What is the purpose of a spy?
Why inject a dependency rather than use a global service?
What is the exact console output in Inject dependencies and use test doubles example 1?
(async () => {async function load(id,lookup){const row=await lookup(id);return row.qty;}const stub=async id=>({id,qty:3});console.log(await load("x",stub));})()What is the exact console output in Inject dependencies and use test doubles example 2?
(async () => {const {mock}=require("node:test");const send=mock.fn(x=>x.toUpperCase());const result=send("ok");console.log(result,send.mock.callCount(),send.mock.calls[0].arguments[0]);})()