How to Mock in Node.js Test: Simple Guide with Examples
To mock in
Node.js tests, use a testing library like Jest which provides built-in mocking functions such as jest.mock() to replace modules or functions with fake versions. This lets you isolate the code under test by controlling dependencies and their outputs.Syntax
Use jest.mock(moduleName, factory) to replace a module with a mock version. The moduleName is the path or name of the module to mock, and factory is a function returning the mocked implementation.
For mocking functions, use jest.fn() to create a mock function that tracks calls and can return controlled values.
javascript
jest.mock('moduleName', () => { return { functionName: jest.fn(() => 'mocked value') }; });
Example
This example shows how to mock a dependency module in a Node.js test using Jest. The fetchData function is mocked to return a fixed value, so the test only checks the behavior of the processData function.
javascript
import { processData } from './processData.js'; import { fetchData } from './fetchData.js'; jest.mock('./fetchData.js', () => ({ fetchData: jest.fn(() => Promise.resolve('mocked data')) })); test('processData returns processed mocked data', async () => { const result = await processData(); expect(result).toBe('Processed: mocked data'); expect(fetchData).toHaveBeenCalled(); });
Output
PASS ./processData.test.js
✓ processData returns processed mocked data (5 ms)
Common Pitfalls
- Not resetting mocks between tests can cause unexpected results; use
jest.resetAllMocks()orjest.clearAllMocks(). - Mocking the wrong module path will not replace the dependency; ensure the path matches exactly.
- For asynchronous mocks, always return a
Promiseif the original function is async.
javascript
/* Wrong: mocking wrong path */ jest.mock('./wrongPath.js', () => ({ fetchData: jest.fn() })); /* Right: mocking correct path */ jest.mock('./fetchData.js', () => ({ fetchData: jest.fn() }));
Quick Reference
| Method | Purpose | Example |
|---|---|---|
| jest.mock(moduleName, factory) | Mock entire module | jest.mock('./api.js', () => ({ get: jest.fn() })) |
| jest.fn() | Create mock function | const mockFn = jest.fn(() => 42) |
| mockFn.mockReturnValue(value) | Set return value of mock function | mockFn.mockReturnValue('test') |
| jest.resetAllMocks() | Reset all mocks between tests | jest.resetAllMocks() |
| mockFn.mockImplementation(fn) | Provide custom implementation | mockFn.mockImplementation(() => 'custom') |
Key Takeaways
Use jest.mock() to replace modules with mocks in Node.js tests.
Create mock functions with jest.fn() to control and inspect calls.
Always mock the exact module path used in your code.
Reset mocks between tests to avoid interference.
Return promises in mocks for async functions to match real behavior.