Jest Mock Module Import Fix
In this tutorial, you'll learn about Jest Mock Module Import Fix. We cover key concepts, practical examples, and best practices.
Your jest.mock() call doesn't seem to take effect — the real module is still used and your test fails because network requests or filesystem operations run for real.
The Problem
// WRONG — jest.mock called after imports
import axios from 'axios';
import { getUser } from './userService';
jest.mock('axios');
test('fetches user', async () => {
axios.get.mockResolvedValue({ data: { name: 'Alice' } });
const user = await getUser(1);
expect(user.name).toBe('Alice');
});
Error: Network Error
at createError (node_modules/axios/lib/core/createError.js:16)
Jest hoists jest.mock() calls to the top of the file during transformation, but imports are also hoisted. The real module is already loaded. Your mock needs to be defined before the module is imported.
Step-by-Step Fix
1. Place jest.mock before all imports
// RIGHT — jest.mock is hoisted by Jest's transform
jest.mock('axios');
import axios from 'axios';
import { getUser } from './userService';
test('fetches user', async () => {
axios.get.mockResolvedValue({ data: { name: 'Alice' } });
const user = await getUser(1);
expect(user.name).toBe('Alice');
});
Jest's jest.mock() calls are hoisted to the top of the file by the transformer, regardless of where you write them. However, keeping them at the top makes the intent clear.
2. Provide a manual mock factory
// RIGHT — custom mock implementation
jest.mock('fs', () => ({
readFileSync: jest.fn().mockReturnValue('mock data'),
existsSync: jest.fn().mockReturnValue(true),
}));
import fs from 'fs';
test('checks file exists', () => {
const result = fs.existsSync('/tmp/test.txt');
expect(result).toBe(true);
expect(fs.readFileSync('/tmp/test.txt')).toBe('mock data');
});
3. Use mocks directory for auto-mocks
// __mocks__/axios.js
export default {
get: jest.fn(),
post: jest.fn(),
};
Then in your test:
jest.mock('axios');
import axios from 'axios';
4. Mock only specific exports
jest.mock('./logger', () => ({
__esModule: true,
info: jest.fn(),
warn: jest.fn(),
error: jest.fn(),
}));
Expected output:
PASS tests/userService.test.js
✓ fetches user (15 ms)
✓ checks file exists (5 ms)
Prevention Tips
- Keep
jest.mock()at the top of test files before imports - Use
__mocks__/directory for reusable auto-mocks - Provide factory functions for custom mock behavior
- Clear mocks between tests with
jest.clearAllMocks() - Use
jest.unmock()to selectively restore modules
Common Mistakes with test mock module
- Overlapping type class instances that cause GHC to reject the program with ambiguous dispatch errors
- Non-exhaustive pattern matches that compile with warnings then crash at runtime
- Misunderstanding that
Stringis[Char]with poor performance for large text operations
These mistakes appear frequently in real-world JEST code. DodaTech's contributors have identified these patterns through analysis of open-source projects and production systems.
Practice Exercise
Write a pure function that safely divides two integers using Maybe, then test it with edge cases like division by zero and negative numbers.
This exercise reinforces the concepts covered in this guide. Try implementing it before checking online solutions.
FAQ
Built by the developers of DodaTech
Doda Browser, DodaZIP & Durga Antivirus Pro