medium

Jest mock not being called / not returning expected value

A jest.mock() or jest.fn() is not behaving as expected — either not being called, not returning the mocked value, or not intercepting the real implementation.

Common Causes

  1. 1Mock is defined after the import (hoisting issue)
  2. 2Module uses named exports but mock replaces default export
  3. 3Mock return value not configured (.mockReturnValue)
  4. 4Component imports the module before the mock is set up
  5. 5Using jest.mock with ES modules requires special handling

How to Fix

Ensure mock is hoisted above imports

// Jest automatically hoists jest.mock() calls to the top
jest.mock('./api', () => ({
  fetchUsers: jest.fn().mockResolvedValue([{ id: 1 }]),
}));

import { fetchUsers } from './api'; // Mock is already in place

jest.mock() is automatically hoisted to the top of the file. This ensures the mock is set up before any imports.

Reset mocks between tests

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

// Or globally in jest.config.ts:
export default {
  clearMocks: true,
};

Clear mock state between tests to prevent test pollution.

How ObserveOne Helps

ObserveOne validates mock configurations and detects when mocks drift from real implementations.

Start Monitoring Free

Related Errors