Maaz Zindani

Loading the index…

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

Jest test fails with 'Cannot access ... before initialization' in jest.mock

ErrorReferenceError: Cannot access 'mockSoundPlayer' before initialization

Short answer

Jest moves jest.mock calls to the top of the file, above your const lines. A factory that reads a variable defined below it hits the temporal dead zone and throws. Create the mock inside the factory, wrap the reference in a function so it runs later, or set the implementation in a hook.

  • Applies to Jest 29, Jest 30, babel-jest, Node.js 22
  • Updated
  • By Maaz Zindani, Senior Software Engineer

Fix it fast

  1. 1Find out which cause you have

    Find the jest.mock call named in the stack trace and look at which variables its factory uses. Each one that is declared below it, or outside the factory, is a suspect.

    npx jest path/to/failing.test.js
  2. 2Match what you see, then jump to its fix

    1. 1The variable name starts with mock, and the error says it cannot be accessed before initializationThe factory returns a variable that is declared laterFix
    2. 2Jest reports an out-of-scope variable used in the factory, and the variable name has no mock prefixThe variable does not start with mockFix
    3. 3You only need a different return value in some testsThe behaviour can be set after the importFix

What does the error look like?

  • ReferenceError: Cannot access 'mockSoundPlayer' before initialization
  • an out-of-scope variable error raised for a jest.mock factory

Cause 1 of 3

The factory returns a variable that is declared later

1Check

jest.mock calls are hoisted to the top of the file. Jest lifts its out-of-scope check for names that start with mock, but it cannot make the variable exist yet. Returning it directly reads it too early.

grep -n "jest.mock\|const mock" path/to/failing.test.js

2Fix

Return a function that reads the variable only when the mock is called, or build the mock inside the factory.

const mockPlaySoundFile = jest.fn();

jest.mock('./sound-player', () => {
  return jest.fn().mockImplementation(() => {
    return { playSoundFile: mockPlaySoundFile };
  });
});

3Verify

The test file loads and the tests run.

npx jest path/to/failing.test.js

Confirmed by jestjs.io

Did this fix it?

Cause 2 of 3

The variable does not start with mock

1Check

Because of hoisting, Jest blocks factories from reading outside variables, except those whose names start with the word mock.

grep -n "jest.mock" -A5 path/to/failing.test.js

2Fix

Rename the variable with a mock prefix and make sure it is only read inside a function. Or avoid the outside variable by creating jest.fn() inside the factory.

// before
const fakePlaySoundFile = jest.fn();
// after
const mockPlaySoundFile = jest.fn();

3Verify

Run the test again; the out-of-scope message is gone.

npx jest path/to/failing.test.js

Confirmed by jestjs.io

Did this fix it?

Cause 3 of 3

The behaviour can be set after the import

1Check

A plain jest.mock('./module') auto-mocks the module. Since it is hoisted, the imported value is already a mock when the tests run.

grep -n "mockImplementation" path/to/failing.test.js

2Fix

Skip the factory and set the implementation in beforeAll or inside the test.

import SoundPlayer from './sound-player';
jest.mock('./sound-player');

beforeAll(() => {
  SoundPlayer.mockImplementation(() => ({
    playSoundFile: () => { throw new Error('Test error'); },
  }));
});

3Verify

The failing test passes with the new implementation.

npx jest path/to/failing.test.js

Confirmed by jestjs.io

Did this fix it?

How do I stop it coming back?

  • Keep jest.mock factories small and self-contained.
  • Name any outside variable used by a factory with the mock prefix, and read it only inside a function.
  • Remember that a mock applies only to the file that calls jest.mock.

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

Web apps

tsconfig rejects allowImportingTsExtensions

An error that allowImportingTsExtensions needs noEmit or emitDeclarationOnly

allowImportingTsExtensions lets files import each other with .ts or .tsx extensions, and TypeScript only allows it together with noEmit or emitDeclarationOnly.

2 causes, each with a fix

Next step

Want this handled for good?

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