Jest Reference Error: Cannot Access ‘’ Before Initialization

This problem is only fixable by changing the location of import and jest.Mock. It creates the problem, because when we import depA and bring it to our module’s runtime, it already read all the…

A Clown Smiling To The Camera

Photo by Dawin Rizzo on Unsplash

I faced with this issue when I tried to mock a module imported by my imported module. So I was importing dependencyA and dependencyA was importing dependencyB. I tried to mock dependencyB and faced with this issue. Code example that shows jest error

Do not care about the names etc. This is the error I received.

// ❌ It throws an error "Reference Error: Cannot access 'depB' before initialization"

import { depA } from "./depA";

const myMock = jest.fn().mockReturnValueOnce(true);
jest.mock("../depB", () => ({
  depB: myMock,
}));

This problem is only fixable by changing the location of import and jest.Mock. It creates the problem, because when we import depA and bring it to our module’s runtime, it already read all the dependencies of the depB. So Jest just locks it and doesn’t allow you to change.
Error message here is not really meaningful, but that’s how mostly things work in JS Universe 😄

// ✅ It passes without a problem

const myMock = jest.fn().mockReturnValueOnce(true);
jest.mock("../depB", () => ({
  depB: myMock,
}));

import { depA } from "./depA";

A Special Warning

When I was wandering around the web, trying to solve this issue, I saw many people referencing a special warning in jest documentation I immediately tried changing the naming of my variable from myMock to mockMy but it had 0 effect on me, it failed as previous

// ❌ It throws an error "Reference Error: Cannot access 'initRabbitMock' before initialization"

import { depA } from "./depA";

const mockMy = jest.fn().mockReturnValueOnce(true);
jest.mock("../depB", () => ({
  depB: mockMy,
}));

So the only solution to this problem is actually changing the order of imports and mocks.

Enjoyed this article?

Share it with your network to help others discover it

Continue Learning

Discover more articles on similar topics