When working with NestJS it can sometimes be difficult to figure out how to write tests around the dependency injection system. In searching for how I could write unit tests for services when using Prisma I found a lot of wild and hacky workarounds. But by consulting Prisma documentation I found a very simple, and clean answer.
First thing, let's say we have this code that creates a new user. You'll notice we're using dependency injection to bring in a PrismaService which connects to the database.
1constructor(private readonly prisma: PrismaService) {}
First we need to follow the Prisma documentation to create mock objects. Most importantly for our case is creating the singleton.ts file.
1import { PrismaClient } from '@prisma/client'
We can then use the exported prismaMock as a provider in our unit test.
1let service: UserService;
Then just return to the Prisma documentation to keep following their example to write a test for creating a new user with the singleton method.
1test('should create new user ', async () => {