0
0
NodejsHow-ToBeginner · 3 min read

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() or jest.clearAllMocks().
  • Mocking the wrong module path will not replace the dependency; ensure the path matches exactly.
  • For asynchronous mocks, always return a Promise if 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

MethodPurposeExample
jest.mock(moduleName, factory)Mock entire modulejest.mock('./api.js', () => ({ get: jest.fn() }))
jest.fn()Create mock functionconst mockFn = jest.fn(() => 42)
mockFn.mockReturnValue(value)Set return value of mock functionmockFn.mockReturnValue('test')
jest.resetAllMocks()Reset all mocks between testsjest.resetAllMocks()
mockFn.mockImplementation(fn)Provide custom implementationmockFn.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.