Mock
- Node.js course
- Intermediate
- Lesson 86/116
- 5 min
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.
Practice 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).
Starter code
// Import mock from node:test
// write here
// Create a fake function
// write here
// Call it twice
// write here
// Print "Mock ready: ..."
// write hereSample solution
const { mock } = require("node:test");
const fn = mock.fn();
fn("hello");
fn("world");
console.log("Mock ready: " + fn.mock.calls.length);Expected output
Mock hazır: 2
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 Complete the mock.fn() call
const fn = ____();
const fn = mock.fn();
Explanation: mock.fn() creates a fake function.
2 What does fn.mock.calls.length give?
fn(1); fn(2); fn(3); fn.mock.calls.length- The call arguments
- The call count Correct answer
- The return value
- The mock type
Explanation: calls.length gives the call count.
3 Match each piece to its role
| Term | Meaning |
|---|---|
mock.fn() |
Creates a fake function |
fn.mock.calls |
Call records |
calls.length |
Call count |
calls[0] |
First call arguments |