None of the answers above solved my problem, so here’s my solution:
var mockMyMethod: jest.Mock;
jest.mock('some-package', () => ({
myMethod: mockMyMethod
}));
Something about using const before the imports feels weird to me. The thing is: jest.mock is hoisted. To be able to use a variable before it you need to use var, because it is hoisted as well. It doesn’t work with let and const because they aren’t.
answered Jun 21, 2021 at 19:31
4
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.
// app.e2e.spec.ts
import { Test, TestingModule } from '@nestjs/testing';
import { INestApplication } from '@nestjs/common';
import * as request from 'supertest';
import mockPrismaClient from './utils/mockPrismaClient'; // you can assert, spy, etc. on this object in your test suites.
// must define this above the `AppModule` import, otherwise the ReferenceError is raised.
jest.mock('@prisma/client', () => {
return {
PrismaClient: jest.fn().mockImplementation(() => mockPrismaClient),
};
});
import { AppModule } from './../src/app.module'; // somwhere here, the prisma is imported
describe('AppController (e2e)', () => {
let app: INestApplication;
beforeEach(async () => {
const moduleFixture: TestingModule = await Test.createTestingModule({
imports: [AppModule],
}).compile();
app = moduleFixture.createNestApplication();
await app.init();
});
)};
answered Apr 15, 2021 at 19:07
![]()
JasonJason
2263 silver badges5 bronze badges
3
To clarify what Jason Limantoro said, move the const above where the module is imported:
const mockMethod1 = jest.fn(); // Defined here before import.
const mockMethod2 = jest.fn();
import MyClass from './my_class'; // Imported here.
import * as anotherClass from './another_class';
jest.mock('./my_class', () => {
return {
default: {
staticMethod: jest.fn().mockReturnValue(
{
method1: mockMethod1,
method2: mockMethod2,
})
}
}
});
answered May 19, 2021 at 0:49
MattMatt
4,0734 gold badges38 silver badges56 bronze badges
The problem that the documentation addresses is that jest.mock is hoisted but const declaration is not. This results in factory function being evaluated at the time when mocked module is imported and a variable being in temporal dead zone.
If it’s necessary to access nested mocked functions, they need to be exposed as a part of export object:
jest.mock('./my_class', () => {
const mockMethod1 = jest.fn();
const mockMethod2 = jest.fn();
return {
__esModule: true,
mockMethod1,
mockMethod2,
default: {
...
This also applies to manual mocks in __mocks__ where variables are accessible inside a mock only.
answered Jan 4, 2021 at 7:43
Estus FlaskEstus Flask
196k67 gold badges406 silver badges540 bronze badges
6
You should move your mocking above your imports; that could be the source of your issue. Imports are also hoisted, so multiple hoisted entries would be hoisted in order.
jest.mock('./my_class', () => {
const mockMethod = jest.fn()
const default = { staticMethod: jest.fn().mockReturnValue({ method: mockMethod }) };
return { default, mockMethod };
});
import MyClass, { mockMethod } from './my_class'; // will import your mock
import * as anotherClass from './another_class';
However, if you for some reason can’t do that, you could use doMock to avoid hoisting behaviour. If this happens on the top of your file, it should be a 1 to 1 change.
const mockMyMethod = jest.fn();
jest.doMock('some-package', () => ({ myMethod: mockMyMethod }));
answered Aug 1, 2022 at 3:57
![]()
Ricardo NoldeRicardo Nolde
32.6k4 gold badges38 silver badges39 bronze badges
This solution works for me and it’s pretty easy for vuejs+ jest.
Two points to note:
- you should declare the absolute path and not ‘@/js/network/repositories’
- the getter helps to defer the instantiation
const mockGetNextStatuses = jest.fn();
const mockUpdatePrintingStatus = jest.fn();
jest.mock('../../../../../../src/js/network/repositories/index.js', () => {
return {
get printing() {
return {
getNextStatuses: mockGetNextStatuses,
updatePrintingStatus: mockUpdatePrintingStatus,
}
}
}
});
or
jest.mock('../../../../../../src/js/network/repositories/index.js', () => ({
printing: {
getNextStatuses: jest.fn(),
updatePrintingStatus: jest.fn()
}
}));
import { printing } from '../../../../../../src/js/network/repositories/index.js';
// and mock the module
printing.getNextStatuses.mockReturnValue(['XX','YY']);
answered Aug 12, 2022 at 12:33
![]()
Example of using TypeScript with Jest and mockDebug.js module
jest.mock('debug', () => {
global.mockDebug = jest.fn();
return () => global.mockDebug;
});
// usage
describe('xxx', () => {
test('xxx', () => {
expect(global.mockDebug.mock.calls.toString()).toContain('ccc');
})
});
![]()
node_modules
4,6656 gold badges20 silver badges37 bronze badges
answered Nov 9, 2022 at 15:17
![]()
1
There is a circular dependency in @effect-ts/system:
@effect-ts/system/_traced/esm/Layer/definitions.js exports LayerSuspend,
but before it does that it will import @effect-ts/system/_traced/esm/Managed,
which imports @effect-ts/system/_traced/esm/Managed/methods/api.js,
which imports @effect-ts/system/_traced/esm/Layer/core.js,
which imports LayerSuspend from @effect-ts/system/_traced/esm/Layer/definitions.js
(which is not finished yet, as it’s circular)
and uses LayerSuspend in initialization in this line:
export const Empty = /*#__PURE__*/ new LayerSuspend(() => identity()).
Note that most of these modules are flagged as side effect free and there are also a few /*#__PURE__*/ annotations, so a lot code might be dropped when optimizations are enabled, which could «fix» this code when e. g. the Empty export is unused.
Also note that execution order might change in side effect free modules even in development mode (side effects optimization is also enable in dev mode), so you might get different behavior. There are cases where code with circular dependencies depends on a certain execution order to work properly. This kind of code has an implicit side effect of putting some modules into the module cache.
Also note that when transpiling code from ESM to CJS, it might look like that «fixes» some of the circular dependencies as exports in circular dependencies might return undefined instead of throwing a ReferenceError.
Here is a simple example of this behavior: typescript playground. The typescript transpiled code logs undefined instead of throwing a ReferenceError.
Improve Article
Save Article
Improve Article
Save Article
This JavaScript exception can’t access the lexical declaration `variable’ before initialization occurs if a lexical variable has been accessed before initialization. This could happen inside any block statement when let or const declarations are accessed when they are undefined.
Message:
ReferenceError: Use before declaration (Edge)
ReferenceError: can't access lexical declaration `variable' before
initialization (Firefox)
ReferenceError: 'variable' is not defined (Chrome)
Error Type:
ReferenceError
Cause of the error: Somewhere in the code, there is a lexical variable that was accessed before initialization.
Example 1: In this example, the const keyword is used with the variable inside the if statement, So the error has occurred.
HTML
<!DOCTYPE html>
<html>
<head>
</head>
<body style="text-align: center;">
<h1 style="color: green;">
GeeksforGeeks
</h1>
<p>
JavaScript ReferenceError -
Can't access lexical declaration`variable'
before initialization
</p>
<button onclick="Geeks();">
click here
</button>
<p id="GFG_DOWN"></p>
<script>
var el_down = document.getElementById("GFG_DOWN");
function GFG() {
const var_1 = "This is";
if (true) {
const var_1 = var_1 + "GeeksforGeeks";
}
}
function Geeks() {
try {
GFG();
el_down.innerHTML =
"'Can't access lexical declaration"+
"`variable'before initialization' "+
"error has not occurred";
} catch (e) {
el_down.innerHTML =
"'Can't access lexical declaration"+
"`variable' before initialization'"+
" error has occurred";
}
}
</script>
</body>
</html>
Output:

Example 2: In this example, the keyword is used with the variable, So the error has occurred.
HTML
<!DOCTYPE html>
<html>
<head>
</head>
<body style="text-align: center;">
<h1 style="color: green;">
GeeksforGeeks
</h1>
<p>
JavaScript ReferenceError -
Can't access lexical declaration`variable'
before initialization
</p>
<button onclick="Geeks();">
click here
</button>
<p id="GFG_DOWN"></p>
<script>
var el_down = document.getElementById("GFG_DOWN");
function GFG() {
let var_1 = 3;
if (true) {
var_1 = var_1 + 5;
}
}
function Geeks() {
try {
GFG();
el_down.innerHTML =
"'Can't access lexical declaration"+
"`variable' before initialization'"+
" error has not occurred";
} catch (e) {
el_down.innerHTML =
"'Can't access lexical declaration"+
"`variable'before initialization'"+
" error has occurred";
}
}
</script>
</body>
</html>
Output:
