DEV Community

Discussion on: NestJS + Prisma Testing with Test database

Collapse
 
afzal_s_h profile image
Afzal Shahul Hameed • Edited

I understand this post is a little old and you probably found a way to mock prisma. But in case someone stumbles here for help, the "jest-mock-extended" library can efficiently help in mocking prisma.

How:



import { mockDeep, DeepMockProxy } from 'jest-mock-extended'
import { PrismaClient } from '@prisma/client';
..
..
..

describe('Cats (e2e)', () => {
    let mockPrisma: DeepMockProxy<PrismaClient>;
    ..
    ..
    ..

    beforeEach(async () => {
        const moduleFixture: TestingModule = await Test.createTestingModule({
            imports: [AppModule],
        })
          .overrideProvider(PrismaService)
          .useValue(mockDeep<PrismaClient>())
          ..
          ..
          .compile();

        ..
        ..
        mockPrisma = moduleFixture.get(PrismaService);
        await app.init();
    })

    ..
    ..
    it('Creates a new cat', async () => {
      mockPrisma.cat.create.mockResolvedValueOnce(mockCat);
      const res = await request(app.getHttpServer()).post('/cats').send({});
      expect(res.status).toBe(201);
      expect(res.body).toStrictEqual(mockCatResponse);
    });
    ..
    ..
})
Enter fullscreen mode Exit fullscreen mode
Collapse
 
vincentjang profile image
Vincent Jang

Thanks a lot. I will try!
Have a nice day

Collapse
 
ninthsun91 profile image
Ninthsun

Thanks, this was exactly what I was looking for!