jest.mock() works at the top of the file but not inside a test
jest.mock('./api') inside it() has no effect; the real function runsShort 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.
Fix it fast
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.js2Match what you see, then jump to its fix
- 1
The 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
A 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
The first test passes; later ones get undefined from the same mockA reset clears the mock between testsFix
- 1
What does the error look like?
jest.mock('./api') inside it() has no effect; the real function runsMock 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.jsConfirmed by jestjs.io
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.jsConfirmed by jestjs.io
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.json2Fix
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.jsConfirmed by jestjs.io
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:
- TaxiDexMy own multi-tenant taxi dispatch SaaS: API, dispatcher portal, driver and passenger apps, and the servers underneath.
- QistLockA NestJS and React SaaS driving an Android Device Owner agent that locks financed phones when payments lapse.
- TaskvareA task and project-management suite: React on the web, Flutter on mobile, TypeScript underneath.
Related fixes
Web apps
Jest test fails with 'Cannot access ... before initialization' in jest.mock
an out-of-scope variable error raised for a jest.mock factory
Jest moves jest.mock calls to the top of the file, above your const lines.
3 causes, each with a fixWeb apps
Module not found for antd/dist/antd.less after upgrading to Ant Design 5
Module not found: Error: Can't resolve 'antd/dist/antd.less'
Ant Design 5 dropped Less and the bundled CSS file for CSS-in-JS, so antd/dist/antd.less no longer exists.
3 causes, each with a fixWeb apps
Astro Code component fails inside a React component
Astro components cannot be rendered directly via function call
Astro components such as Code only exist on the server and render static HTML.
2 causes, each with a fixWeb apps
React shows Attempted import error when importing a component or function
Attempted import error:
The build found the file but not the name you asked for.
2 causes, each with a fixWeb apps
How to catch and handle a 422 from Axios in a Redux thunk
action.error.message is 'Rejected' and action.payload is undefined
A 422 means the server read the request but cannot process its content, so repeating it unchanged fails again.
4 causes, each with a fixWeb apps
axios gets 429 Too Many Requests from a React app
429 (Too Many Requests)
A 429 comes from the server or an API gateway, not from axios: your client sent too many requests in a window.
4 causes, each with a fix