I am working in a NestJS project and had a question about that.
I'm not that fluent yet in writing unit test cases, I have written some generic ones for my controllers such as users.controller.spec.ts
and for the services users.service.spec.ts
. I was wondering, how would I go about writing the test file for the prisma.service.spec.ts
? I have a prisma.service.ts
file that looks like this:
import { PrismaClient } from '@prisma/client';
import { Injectable, OnModuleDestroy, OnModuleInit } from '@nestjs/common';
import { ConfigService } from '@nestjs/config';
@Injectable()
export class PrismaService
extends PrismaClient
implements OnModuleInit, OnModuleDestroy
{
constructor(config: ConfigService) {
super({
datasources: {
db: {
url: config.get<string>('DATABASE_URL'),
},
},
});
}
async onModuleInit() {
await this.$connect();
}
async onModuleDestroy() {
await this.$disconnect();
}
async cleanDatabase() {
if (process.env.NODE_ENV === 'production') return;
const models = Reflect.ownKeys(this).filter((key) => key[0] !== '_');
return Promise.all(models.map((modelKey) => this[modelKey].deleteMany()));
}
}
And NestJS CLI generates this generic spec.ts
file when you create a service
that looks like this:
import { Test, TestingModule } from '@nestjs/testing';
import { PrismaService } from './prisma.service';
describe('PrismaService', () => {
let service: PrismaService;
beforeEach(async () => {
const module: TestingModule = await Test.createTestingModule({
providers: [PrismaService],
}).compile();
service = module.get<PrismaService>(PrismaService);
});
it('should be defined', () => {
expect(service).toBeDefined();
});
});