Maaz Zindani

Loading the index…

↑↓ move↵ openesc close4072 pages
Next.js and React

jest.mock() works at the top of the file but not inside a test

Errorjest.mock('./api') inside it() has no effect; the real function runs

Short answer

Jest hoists jest.mock() only to the top of its own code block. Inside a test, the module was already imported at the top of the file, so your test still gets the real one. Mock at the top level and change behaviour per test with mockImplementation, or use jest.doMock with a require after it.

  • Applies to Jest 29, Jest 30, babel-jest, React 19
  • Updated
  • By Maaz Zindani, Senior Software Engineer

Fix it fast

  1. 1Find out which cause you have

    Check where the jest.mock call sits and where the module is imported. The mock must be set up before the first import of that module is evaluated.

    grep -n "jest.mock\|^import\|require(" src/__tests__/profile.test.js
  2. 2Match what you see, then jump to its fix

    1. 1The real module code runs, or a real network call is attempted, from a test that calls jest.mockjest.mock is inside a test, so the import already ranFix
    2. 2A module-level jest.mock factory returns one value, and tests need different onesYou need a different mock per test and the factory is fixedFix
    3. 3The first test passes; later ones get undefined from the same mockA reset clears the mock between testsFix

What does the error look like?

  • jest.mock('./api') inside it() has no effect; the real function runs
  • Mock works in one test and returns undefined in the next

Cause 1 of 3

jest.mock is inside a test, so the import already ran

1Check

With babel-jest, calls to mock are hoisted to the top of the code block they are in. Inside it() that means the top of the test function, which runs after the file's imports.

// fails: imported at file top, mocked too late
import { getUser } from './api';
it('shows name', () => {
  jest.mock('./api');
  // getUser here is still the real one
});

2Fix

Move jest.mock to the top level of the test file, then control each test's result through the mock function.

import { getUser } from './api';
jest.mock('./api');

it('shows name', async () => {
  jest.mocked(getUser).mockResolvedValue({ name: 'Sam' });
  // render and assert
});

3Verify

Run the test file. The real module no longer runs.

npx jest src/__tests__/profile.test.js

Confirmed by jestjs.io

Did this fix it?

Cause 2 of 3

You need a different mock per test and the factory is fixed

1Check

A hoisted jest.mock at the top of the file fixes the module for the whole file. To vary the module itself between tests, use jest.doMock, which is not hoisted.

grep -rn "doMock" src/

2Fix

Reset the module registry, call doMock, then require the module after it, inside the test. With ES imports the page also needs __esModule: true for default exports.

beforeEach(() => {
  jest.resetModules();
});

test('first value', () => {
  jest.doMock('./config', () => ({ __esModule: true, default: { mode: 'a' } }));
  const config = require('./config').default;
  expect(config.mode).toBe('a');
});

3Verify

Both tests pass in either order.

npx jest src/__tests__/profile.test.js

Confirmed by jestjs.io

Did this fix it?

Cause 3 of 3

A reset clears the mock between tests

1Check

mockReset replaces the implementation with an empty function that returns undefined. The resetMocks config option does that automatically before each test.

grep -rn "resetMocks\|restoreMocks" jest.config.* package.json

2Fix

Set the return value in beforeEach or inside each test, or use clearMocks, which clears the call history and leaves the implementation.

beforeEach(() => {
  jest.mocked(getUser).mockResolvedValue({ name: 'Sam' });
});

3Verify

Run the whole file; every test sees the value.

npx jest src/__tests__/profile.test.js

Confirmed by jestjs.io

Did this fix it?

How do I stop it coming back?

  • Keep jest.mock calls at the top level of the file, directly under the imports.
  • Vary per-test behaviour with mockResolvedValue or mockImplementation, not by re-mocking.
  • Use jest.mocked() to get typed access to the mock in TypeScript.

Sources

How was this page made?

I drafted this page with AI assistance from the official documents listed under Sources. Every cause above names the document that confirms it. I have not reproduced this fix on a machine of my own yet, so read it as documented guidance, not a test report. Found a mistake? Tell me.

Which stack is behind this page?

Projects of mine built on the same technologies:

Related fixes

Next step

Want this handled for good?

I look after servers, apps and releases end to end. Tell me what keeps breaking.