Skip to content
Advertisement

jest ReferenceError: Cannot access ” before initialization

I’m getting the error:

ReferenceError: Cannot access 'myMock' before initialization

Even though i respected jest documentation about the hoisting: A limitation with the factory parameter is that, since calls to jest.mock() are hoisted to the top of the file, it's not possible to first define a variable and then use it in the factory. An exception is made for variables that start with the word 'mock'.

I’m doing this:

JavaScript

as you can see both of my variables respect the “standard” but are not hoisted properly.

Am I missing something ?

Obviously it works when I just pass jest.fn() instead of my variables, but i’m not sure how to be able to use these in my test later on.

Advertisement

Answer

The accepted answer does not handle when you need to spy on the const declaration, as it is defined inside the module factory scope.

For me, the module factory needs to be above any import statement that eventually imports the thing you want to mock. Here is a code snippet using a nestjs with prisma library.

JavaScript
User contributions licensed under: CC BY-SA
9 People found this is helpful
Advertisement