Skip to content

Jest Partial Module Mock Fix

DodaTech Updated 2026-06-24 2 min read

In this tutorial, you'll learn about Jest Partial Module Mock Fix. We cover key concepts, practical examples, and best practices.

You need to mock only one function from a module while keeping the rest real — but jest.mock() replaces the entire module, causing other functions to break.

The Problem

// WRONG — jest.mock replaces everything
jest.mock('./utils', () => ({
  formatDate: jest.fn(() => '2024-01-01'),
  calculateTotal: jest.fn(), // Oops — this breaks real calculations
}));

The calculateTotal function is now a mock that returns undefined, breaking any test that needs its real implementation.

Step-by-Step Fix

1. Use jest.requireActual

// RIGHT — keep real implementations, mock only what you need
jest.mock('./utils', () => ({
  ...jest.requireActual('./utils'),
  formatDate: jest.fn(() => '2024-01-01'),
}));

import { formatDate, calculateTotal } from './utils';

test('uses real calculateTotal with mocked formatDate', () => {
  expect(formatDate(new Date())).toBe('2024-01-01');
  expect(calculateTotal(10, 20)).toBe(30); // Real implementation
});

2. Spy on specific methods

// RIGHT — spy replaces only one method
import * as utils from './utils';

beforeEach(() => {
  jest.spyOn(utils, 'formatDate').mockReturnValue('2024-01-01');
});

afterEach(() => {
  jest.restoreAllMocks();
});

test('formatDate is mocked, others are real', () => {
  expect(utils.formatDate(new Date())).toBe('2024-01-01');
  expect(utils.calculateTotal(5, 5)).toBe(10);
});

3. Mock non-existent exports safely

// RIGHT — conditional spread
jest.mock('./config', () => {
  const actual = jest.requireActual('./config');
  return {
    ...actual,
    getFeatureFlag: jest.fn(() => true),
  };
});

4. Partial mock with __esModule flag

// RIGHT — ES module partial mock
jest.mock('./services', () => {
  const actual = jest.requireActual('./services');
  return {
    __esModule: true,
    ...actual,
    sendEmail: jest.fn(),
  };
});

Expected output:

PASS  tests/partial.test.js
  ✓ uses real calculateTotal with mocked formatDate (6 ms)
  ✓ formatDate is mocked, others are real (4 ms)

Prevention Tips

  • Use jest.requireActual() to preserve real implementations
  • Use jest.spyOn() for mocking individual exports
  • Use the spread operator to merge real and mocked exports
  • Always import the module in each test that needs partial mocks
  • Set __esModule: true for ES module compatibility

Common Mistakes with mock partial

  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

### Does jest.requireActual work with ES modules?

Yes, but you need __esModule: true in the returned object. Jest's jest.requireActual() loads the real module and returns its exports, which you can then spread into your mock object.

Can I use jest.unmock to selectively restore modules?

No — jest.unmock() only prevents a module from being mocked in the first place. To selectively mock within a module, use the jest.requireActual() pattern with spread operator.

How do I mock a function in a namespace import?

Use jest.spyOn(namespace, 'functionName') where namespace is the result of import * as namespace from './module'. This replaces only the specific function while keeping the rest intact.

Built by the developers of DodaTech

Doda Browser, DodaZIP & Durga Antivirus Pro