DEV Community

Lumin
Lumin

Posted on

Mock Prisma with Jest in NestJS

Concept:

  • Define a type for the mock object
  • Assign mock value in the provider

Let's say you have a NestJS service:

class TheServiceYouWantToTest { constructure( private readonly prisma: PrismaService // <- the Prisma service contains its client (models) ){} } 
Enter fullscreen mode Exit fullscreen mode

To test TheServiceYouWantToTest, you might need to mock PrismaService.

This is the pattern in test code that I use for mock PrismaService:

type MockPrismaService = { model: { // define only the method I'll use in the implementation code findMany: jest.Mock ... } } describe('some sort of service', () => { let prisma: MockPrismaService beforeEach(() => { // create the test module with our service undertest and the mock service const mockPrismaService: MockPrismaService = { model: { findMany: jest.fn(), ... } } const module = await Test.createTestingModule({ providers: [ TheServiceYouWantToTest, { provide: PrismaService, useValue: mockPrismaService, } ], }) // get the mock object that is already binding with the test module // the object type will be MockPrismaService prisma = module.get(PrismaService) }) // and then we can ... // mock it prisma.model.findMany.mockResolvedValue(...) // spy it expect(prisma.model.findMany).toHaveBeenCalled() // without type error }) 
Enter fullscreen mode Exit fullscreen mode

Top comments (0)