Mocking helps you test code by replacing real parts with fake ones. This way, you can check how your code works without using the real modules or functions.
Mocking modules and functions in Node.js
import { jest } from '@jest/globals'; // Mock a whole module jest.mock('module-name'); // Mock a specific function import * as module from 'module-name'; jest.spyOn(module, 'functionName').mockImplementation(() => fakeValue);
jest.mock() replaces the whole module with a mock version.
jest.spyOn() lets you replace just one function inside a module.
jest.mock('fs');import * as math from './math'; jest.spyOn(math, 'add').mockImplementation(() => 10);
jest.mock('axios', () => ({ get: jest.fn(() => Promise.resolve({ data: 'mocked data' })) }));
This example shows how to mock the fetchData function from a module. Instead of returning 'real data', it returns 'mocked data' during the test.
import { jest } from '@jest/globals'; // Original module export function fetchData() { return 'real data'; } // Test file import * as dataModule from './dataModule'; // Mock fetchData function jest.spyOn(dataModule, 'fetchData').mockImplementation(() => 'mocked data'); console.log(dataModule.fetchData());
Always reset mocks after tests to avoid interference using jest.resetAllMocks().
Mocking helps keep tests fast and reliable by avoiding real external calls.
Use mocks carefully to not hide real bugs in your code.
Mocking replaces real modules or functions with fake ones for testing.
Use jest.mock() for whole modules and jest.spyOn() for specific functions.
Mocking helps test code in isolation and avoid slow or unreliable dependencies.
Practice
Solution
Step 1: Understand mocking concept
Mocking means replacing real code with fake versions to test parts independently.Step 2: Identify purpose in testing
This helps avoid slow or unreliable dependencies and focuses tests on the code itself.Final Answer:
To replace real modules or functions with fake ones for isolated testing -> Option AQuick Check:
Mocking = isolated testing [OK]
- Thinking mocking speeds up production code
- Believing mocking changes app behavior permanently
- Confusing mocking with documentation generation
utils using Jest?Solution
Step 1: Recall Jest mocking syntax
Jest usesjest.mock('moduleName')to mock entire modules.Step 2: Match syntax to options
Only jest.mock('utils') uses the correctjest.mock()function with the module name.Final Answer:
jest.mock('utils') -> Option CQuick Check:
jest.mock() mocks modules [OK]
- 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
console.log(fetchData()) after mocking?import * as api from './api';
jest.mock('./api', () => ({
fetchData: () => 'mocked data'
}));
console.log(api.fetchData());Solution
Step 1: Understand jest.mock replacement
Thejest.mockcall replaces the entire './api' module with the provided object.Step 2: Check the mocked function return
The mockedfetchDatareturns the string 'mocked data'.Final Answer:
'mocked data' -> Option BQuick Check:
Mocked function returns mocked data [OK]
- Expecting original function output
- Assuming undefined because of mocking
- Confusing import and mock timing
import * as math from './math'; jest.spyOn(math, 'add'); math.add.mockReturnValue(10); console.log(math.add(2, 3));
Solution
Step 1: Understand jest.spyOn usage
jest.spyOn creates a mock function that can be controlled.Step 2: Check mockReturnValue usage
CallingmockReturnValue(10)on the spy sets the return value to 10.Final Answer:
No error, the code works and logs 10 -> Option AQuick Check:
spyOn + mockReturnValue works [OK]
- Thinking spyOn needs mockImplementation first
- Believing spyOn must be after function call
- Assuming spyOn does not mock return values
sendEmail function from the notifications module to return true during tests, but keep other functions real. Which is the best approach?Solution
Step 1: Understand partial mocking need
We want to mock only one function, not the whole module.Step 2: Use jest.spyOn for specific function
jest.spyOn allows mocking a single function while keeping others real.Final Answer:
Use jest.spyOn(notifications, 'sendEmail').mockReturnValue(true) -> Option DQuick Check:
spyOn mocks single function only [OK]
- Mocking entire module unnecessarily
- Trying to overwrite imported functions directly
- Not using spyOn for partial mocks
Ready to prove it?
Pass the test and this pattern moves unknown
