![translation](https://cdn.durumis.com/common/trans.png)
This is an AI translated post.
Mocking Prisma Client for Unit Testing in NestJS
- Writing language: Korean
- •
-
Base country: All countries
- •
- Information Technology
Select Language
Summarized by durumis AI
- It is important to remove external dependencies for unit testing.
- You can easily mock Prisma Client of Prisma ORM using the jest-mock-extended package.
- Unit testing has become more convenient after mocking.
It is a principle that application unit tests should be conducted in isolation, so it is a good idea to remove external dependencies that can affect test results, such as network I/O, databases, and other external dependencies.
This time, I am using Prisma ORM for a toy project, so I'm writing this post to record how to simply mock Prisma Client for unit testing.
Installing jest-mock-extended package
This is the package that is recommended in the official Prisma documentation, so install it with the above command.
Mocking Prisma Client
describe('UserService', () => {
let service: UserService;
let prismaMock: DeepMockProxy;
beforeEach(async () => {
prismaMock = mockDeep();
const module: TestingModule = await Test.createTestingModule({
providers: [
UserService,
{
provide: PrismaService,
useValue: prismaMock,
},
],
}).compile();
service = module.get(UserService);
Unit test example code
describe('create', () => {
it('If user creation is successful, it should return user information.', async () => {
// Arrange
const newUser = {
email: 'test@test.com',
password: 'test1234',
};
prismaMock.user.create.mockResolvedValue({
id: 1,
email: 'test@test.com',
password: 'test1234',
});
// Act
const result = await service.create(newUser);
// Assert
expect(result).toEqual({
id: 1,
email: 'test@test.com',
password: 'test1234',
});
});
After mocking, type support is also provided, so it was very convenient to write unit tests.