【发布时间】:2022-11-12 14:05:25
【问题描述】:
我在单元测试时遇到问题棱镜服务.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();
});
});
});
但是,这不会测试第 8 行棱镜服务.ts:
await app.close();
因为我在嘲笑this.$on('beforeExit', 回调),以及其原始实现的副本。 即使我不嘲笑它,应用程序关闭()永远不会被调用。
有没有办法测试这条线?
【问题讨论】:
标签: unit-testing jestjs nestjs