Node.js
Mock
Learn mock functions and module mocking.
Mock functions
To check whether a function was called, how many times, or with which arguments, you use a mock. The mock object in node:test creates fake functions inside tests.
Example: const fn = mock.fn(); creates a callable fake function. After fn(1, 2); fn(3); calls, fn.mock.calls.length is 2; fn.mock.calls[0] is [1, 2]. This lets you inspect calls without touching a real database or making network requests. Mocks are automatically restored at the end of the test, so they do not affect the real function. In this lesson we learn to create a fake function with mock.fn().
Inspecting calls
After a mock function is called, the fn.mock.calls array holds call records. Each record is the array of arguments passed to that call. fn.mock.calls.length gives the call count.
Example: after fn("hello"); fn("world"); calls, fn.mock.calls.length === 2 and fn.mock.calls[1][0] === "world". This is useful to check that the right arguments were passed. You can also assign a return value to a mock: fn.mockReturnValue(42). However node:test's mock.fn() returns undefined by default. To change the return value, you mock object methods with mock.method; that is an advanced topic.
Exercise Create and call a fake function
Import mock from node:test. Create a fake function with const fn = mock.fn();. Call it twice: fn("hello") and fn("world"). Print with console.log("Mock ready: " + fn.mock.calls.length).
Show example solution
const { mock } = require("node:test");
const fn = mock.fn();
fn("hello");
fn("world");
console.log("Mock ready: " + fn.mock.calls.length);
Test yourself
-
Complete the mock.fn() call
const fn = ____();
Show answer
const fn = mock.fn();
-
What does fn.mock.calls.length give?
fn(1); fn(2); fn(3); fn.mock.calls.length
- The call arguments
- The call count
- The return value
- The mock type
Show answer
The call count — calls.length gives the call count.
-
Match each piece to its role
- mock.fn()
- Creates a fake function
- fn.mock.calls
- Call records
- calls.length
- Call count
- calls[0]
- First call arguments
Next lesson: Summary - Testing basics