'ReferenceError: Cannot access 'jest_mock_extended_1' before initialization

I have the following code.

singleton.ts

import prisma from "../prismaClient";
import { mockDeep, mockReset } from "jest-mock-extended";
import { PrismaClient } from "@prisma/client";
import { DeepMockProxy } from "jest-mock-extended/lib/cjs/Mock";

jest.mock("../prismaClient", () => ({
  __esModule: true,

  default: mockDeep<PrismaClient>(),
}));

beforeEach(() => {
  mockReset(prismaMock);
});

export const prismaMock = prisma as unknown as DeepMockProxy<PrismaClient>;

prismaClient.ts

import { PrismaClient } from "@prisma/client";

const prisma = new PrismaClient({
  log: [
    {
      emit: "event",
      level: "query",
    },
    {
      emit: "stdout",
      level: "error",
    },
    {
      emit: "stdout",
      level: "info",
    },
    {
      emit: "stdout",
      level: "warn",
    },
  ],
});

export default prisma;

I am following prisma's guide to unit testing here: https://www.prisma.io/docs/guides/testing/unit-testing. I don't know why I keep getting this error:

This the error message ReferenceError: Cannot access 'jest_mock_extended_1' before initialization

       7 |   __esModule: true,
       8 |
    >  9 |   default: mockDeep<PrismaClient>(),
         |            ^
      10 | }));
      11 |
      12 | beforeEach(() => {

      at src/utils/testUtils/singleton.ts:9:12
      at Object.<anonymous> (src/utils/testUtils/singleton.ts:1:1)
      at Object.<anonymous> (src/resolvers/functions/user.test.ts:1:1)


Solution 1:[1]

The issue is that the import path and the path you are mocking are the same. That is import prisma from "../prismaClient"; gets mocked by

jest.mock("../prismaClient", () => ({
  __esModule: true,

  default: mockDeep<PrismaClient>(),
}));

So this means in the file itself mocking happens which triggers that error. If you want this to work then the path you are mocking and the path you are importing here must be different. Something like the below works

import prisma from "../prismaClient";

jest.mock("../../prismaClient", () => ({
  __esModule: true,

  default: mockDeep<PrismaClient>(),
}));

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Allen