Bird
Raised Fist0
Node.jsframework~10 mins

Mocking modules and functions in Node.js - Step-by-Step Execution

Choose your learning style10 modes available
Concept Flow - Mocking modules and functions
Test starts
↓
Import module
↓
Mock function or module
↓
Run code using mock
↓
Check mock calls or results
↓
Test ends
This flow shows how a test imports a module, replaces parts with mocks, runs code, and checks mock behavior.
Execution Sample
Node.js
import { jest } from '@jest/globals';
import fs from 'fs';

jest.mock('fs');

fs.readFileSync.mockReturnValue('mocked content');

const content = fs.readFileSync('file.txt', 'utf8');
This code mocks the fs module's readFileSync function to return 'mocked content' instead of reading a file.
Execution Table
StepActionEvaluationResult
1Import fs modulefs is real modulefs points to real fs module
2jest.mock('fs')Replace fs with mockfs.readFileSync is now a mock function
3fs.readFileSync.mockReturnValue('mocked content')Set mock returnreadFileSync returns 'mocked content' when called
4Call fs.readFileSync('file.txt', 'utf8')Call mock functionReturns 'mocked content'
5Check content variablecontent = 'mocked content'content holds mocked string
💡 Test ends after verifying mock returns expected value
Variable Tracker
VariableStartAfter Step 2After Step 3After Step 4Final
fs.readFileSyncreal functionmock functionmock function with return 'mocked content'called mock functionmock function
contentundefinedundefinedundefined'mocked content''mocked content'
Key Moments - 2 Insights
Why does fs.readFileSync return 'mocked content' instead of reading a file?
Because jest.mock replaced fs.readFileSync with a mock function, and mockReturnValue set its return to 'mocked content' (see execution_table step 3 and 4).
Does jest.mock replace the whole module or just one function?
jest.mock replaces the whole module with a mock version. Individual functions like readFileSync become mock functions you can control (see execution_table step 2).
Visual Quiz - 3 Questions
Test your understanding
Look at the execution table, what is the value of 'content' after step 4?
Aundefined
B'mocked content'
Cfile contents from disk
Dnull
💡 Hint
Check the 'content' variable in variable_tracker after step 4
At which step does fs.readFileSync become a mock function?
AStep 2
BStep 1
CStep 3
DStep 4
💡 Hint
See execution_table step 2 where jest.mock replaces fs with a mock
If we remove jest.mock('fs'), what would fs.readFileSync return at step 4?
A'mocked content'
Bundefined
CActual file content from disk
DAn error
💡 Hint
Without mocking, fs.readFileSync calls the real function (see execution_table step 1)
Concept Snapshot
Mocking modules and functions in Node.js tests:
- Use jest.mock('module') to replace a module with mocks.
- Mock functions can have return values set with mockReturnValue.
- Calls to mocked functions return mocked data, not real data.
- This helps isolate tests from real dependencies.
- Always check mock calls and results in tests.
Full Transcript
In Node.js testing, mocking means replacing real modules or functions with fake versions that return controlled data. The test starts by importing the module, then jest.mock replaces it with a mock. You can set what the mock returns using mockReturnValue. When the code calls the mocked function, it returns the fake data instead of doing the real work. This lets tests run without depending on real files or network. The execution table shows each step: importing, mocking, setting return, calling, and checking results. Variables like fs.readFileSync change from real to mock functions. This approach helps write reliable tests that focus on the code logic, not external factors.

Practice

(1/5)
1. What is the main purpose of mocking modules or functions in Node.js testing?
easy
A. To replace real modules or functions with fake ones for isolated testing
B. To speed up the production code execution
C. To permanently change the behavior of modules in the app
D. To automatically generate documentation for modules

Solution

  1. Step 1: Understand mocking concept

    Mocking means replacing real code with fake versions to test parts independently.
  2. Step 2: Identify purpose in testing

    This helps avoid slow or unreliable dependencies and focuses tests on the code itself.
  3. Final Answer:

    To replace real modules or functions with fake ones for isolated testing -> Option A
  4. Quick Check:

    Mocking = isolated testing [OK]
Hint: Mocking means faking parts to test code alone [OK]
Common Mistakes:
  • Thinking mocking speeds up production code
  • Believing mocking changes app behavior permanently
  • Confusing mocking with documentation generation
2. Which of the following is the correct syntax to mock an entire module named utils using Jest?
easy
A. jest.spyOn('utils')
B. jest.fake('utils')
C. jest.mock('utils')
D. mock('utils')

Solution

  1. Step 1: Recall Jest mocking syntax

    Jest uses jest.mock('moduleName') to mock entire modules.
  2. Step 2: Match syntax to options

    Only jest.mock('utils') uses the correct jest.mock() function with the module name.
  3. Final Answer:

    jest.mock('utils') -> Option C
  4. Quick Check:

    jest.mock() mocks modules [OK]
Hint: Use jest.mock('moduleName') to mock whole modules [OK]
Common Mistakes:
  • Using jest.spyOn for whole modules instead of functions
  • Trying mock() or jest.fake() which don't exist
  • Passing module name incorrectly as a variable
3. Given the code below, what will be the output of console.log(fetchData()) after mocking?
import * as api from './api';

jest.mock('./api', () => ({
  fetchData: () => 'mocked data'
}));

console.log(api.fetchData());
medium
A. 'real data'
B. 'mocked data'
C. undefined
D. Error: fetchData is not a function

Solution

  1. Step 1: Understand jest.mock replacement

    The jest.mock call replaces the entire './api' module with the provided object.
  2. Step 2: Check the mocked function return

    The mocked fetchData returns the string 'mocked data'.
  3. Final Answer:

    'mocked data' -> Option B
  4. Quick Check:

    Mocked function returns mocked data [OK]
Hint: Mocked functions return what you define in jest.mock [OK]
Common Mistakes:
  • Expecting original function output
  • Assuming undefined because of mocking
  • Confusing import and mock timing
4. What is wrong with this Jest mocking code snippet?
import * as math from './math';

jest.spyOn(math, 'add');

math.add.mockReturnValue(10);

console.log(math.add(2, 3));
medium
A. No error, the code works and logs 10
B. mockReturnValue cannot be used on spy without mockImplementation
C. The spy is created correctly, but math.add is not mocked properly
D. jest.spyOn should be called after calling math.add

Solution

  1. Step 1: Understand jest.spyOn usage

    jest.spyOn creates a mock function that can be controlled.
  2. Step 2: Check mockReturnValue usage

    Calling mockReturnValue(10) on the spy sets the return value to 10.
  3. Final Answer:

    No error, the code works and logs 10 -> Option A
  4. Quick Check:

    spyOn + mockReturnValue works [OK]
Hint: spyOn returns a mock you can control directly [OK]
Common Mistakes:
  • Thinking spyOn needs mockImplementation first
  • Believing spyOn must be after function call
  • Assuming spyOn does not mock return values
5. You want to mock only the sendEmail function from the notifications module to return true during tests, but keep other functions real. Which is the best approach?
hard
A. Use jest.mock('notifications') and redefine all functions manually
B. Replace the entire module with a fake object returning true for sendEmail
C. Import sendEmail separately and overwrite it directly
D. Use jest.spyOn(notifications, 'sendEmail').mockReturnValue(true)

Solution

  1. Step 1: Understand partial mocking need

    We want to mock only one function, not the whole module.
  2. Step 2: Use jest.spyOn for specific function

    jest.spyOn allows mocking a single function while keeping others real.
  3. Final Answer:

    Use jest.spyOn(notifications, 'sendEmail').mockReturnValue(true) -> Option D
  4. Quick Check:

    spyOn mocks single function only [OK]
Hint: Use jest.spyOn to mock one function, not whole module [OK]
Common Mistakes:
  • Mocking entire module unnecessarily
  • Trying to overwrite imported functions directly
  • Not using spyOn for partial mocks
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard