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)
It seemed weird to import a class that you are mocking just to export it. So i created deepMock of PrismaClient, added it to the jest.mock and exported the deepMock.
import { PrismaClient } from '@prisma/client'
import { mockDeep, mockReset, DeepMockProxy } from 'jest-mock-extended'
const prismaMock = mockDeep<PrismaClient>();
jest.mock("../prismaClient", () => ({
__esModule: true,
default: prismaMock
}));
beforeEach(() => {
mockReset(prismaMock);
});
export { prismaMock }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With