Skip to content

Jest Mock Module Import Fix

DodaTech Updated 2026-06-24 3 min read

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

  1. Overlapping type class instances that cause GHC to reject the program with ambiguous dispatch errors
  2. Non-exhaustive pattern matches that compile with warnings then crash at runtime
  3. Misunderstanding that String is [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

### Why isn't my jest.mock working for a third-party module?

Jest can only mock modules that are resolvable via the module system. Check that the module name is correct and not aliased. For scoped packages like @org/package, use the full name: jest.mock('@org/package'). Also verify the module uses CommonJS or is compatible with Jest's mocking.

Should I use jest.mock or jest.spyOn for mocking?

Use jest.mock() to replace entire modules. Use jest.spyOn() to wrap specific methods on an object. For third-party dependencies like axios or fs, jest.mock() is the right approach because it replaces the module at the import level.

How do I mock only some exports from a module?

Pass a factory function to jest.mock() that returns only the exports you need. For example, jest.mock('./utils', () => ({ formatDate: jest.fn() })) replaces only formatDate while keeping other exports — wait, this actually replaces all exports. To preserve other exports, use jest.requireActual(): jest.mock('./utils', () => ({ ...jest.requireActual('./utils'), formatDate: jest.fn() })).

Built by the developers of DodaTech

Doda Browser, DodaZIP & Durga Antivirus Pro