Jest test fails with 'Cannot access ... before initialization' in jest.mock
ReferenceError: Cannot access 'mockSoundPlayer' before initializationShort 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.
Fix it fast
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.js2Match what you see, then jump to its fix
- 1
The variable name starts with mock, and the error says it cannot be accessed before initializationThe factory returns a variable that is declared laterFix - 2
Jest 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
You only need a different return value in some testsThe behaviour can be set after the importFix
- 1
What does the error look like?
ReferenceError: Cannot access 'mockSoundPlayer' before initializationan 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.js2Fix
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.jsConfirmed by jestjs.io
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.js2Fix
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.jsConfirmed by jestjs.io
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.js2Fix
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.jsConfirmed by jestjs.io
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
ReferenceError: Cannot access __WEBPACK_DEFAULT_EXPORT__ before initialization
ReferenceError: Cannot access 'a' before initialization
The error means a module read a let, const or export before the line that creates it had run.
2 causes, each with a fixWeb 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 fixWeb apps
Apollo Server rejects a request as a potential CSRF
HTTP 400 Bad Request from the GraphQL endpoint
Apollo Server's CSRF prevention is on by default.
3 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
AxiosError Network Error with code ERR_NETWORK in a React app
Network Error
ERR_NETWORK means the request produced no readable response.
4 causes, each with a fixWeb apps
Axios get works with a URL string but ignores the object passed as the second argument
The server log shows a GET with no query string
axios.get takes a URL and an optional config object.
3 causes, each with a fix