如何对这个prisma.service进行单元测试



我在单元测试prisma.service.ts文件时遇到问题:

import { INestApplication, Injectable } from '@nestjs/common';
import { PrismaClient } from '@prisma/client';
@Injectable()
export class PrismaService extends PrismaClient {
async enableShutdownHooks(app: INestApplication) {
this.$on('beforeExit', async () => {
await app.close();
});
}
}

prisma.service.spec.ts我目前的情况如下:

import { INestApplication } from '@nestjs/common';
import { NestFastifyApplication } from '@nestjs/platform-fastify';
import { Test, TestingModule } from '@nestjs/testing';
import { PrismaService } from './prisma.service';
const MockApp = jest.fn<Partial<INestApplication>, []>(() => ({
close: jest.fn(),
}));
describe('PrismaService', () => {
let service: PrismaService;
let app: NestFastifyApplication;
beforeEach(async () => {
app = MockApp() as NestFastifyApplication;
const module: TestingModule = await Test.createTestingModule({
providers: [PrismaService],
}).compile();
service = module.get<PrismaService>(PrismaService);
});
it('should be defined', () => {
expect(service).toBeDefined();
});
describe('enableShutdownHooks', () => {
it('should call $on and successfully close the app', async () => {
const spy = jest.spyOn(PrismaService.prototype, '$on')
.mockImplementation(async () => {
await app.close();
});
await service.enableShutdownHooks(app);
expect(spy).toBeCalledTimes(1);
expect(app.close).toBeCalledTimes(1);
spy.mockRestore();
});
});
});

但是,这并不能测试prisma.service.ts:的第8行

await app.close();

因为我在嘲笑这个的实现$on('beforeExit',callback(,并带有其原始实现的副本。即使我不嘲笑它,app.close((也永远不会被调用。

有办法测试这条线路吗?

你能试着使用回调吗:

jest
.spyOn(service, '$on')
.mockImplementation(async (eventType, cb) => cb(() => Promise.resolve()))
await service.enableShutdownHooks(app);
expect(service.$on).toBeCalledTimes(1);

这允许您使用回调来调用await app.close()所在的函数。

最新更新