我在對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();
因為我正在嘲笑this.$on('beforeExit', callback)的實作,并帶有其原始實作的副本。即使我不嘲笑它,app.close()也永遠不會被呼叫。
有沒有辦法測驗這條線?
uj5u.com熱心網友回復:
你可以嘗試使用回呼:
jest
.spyOn(service, '$on')
.mockImplementation(async (eventType, cb) => cb(() => Promise.resolve()))
await service.enableShutdownHooks(app);
expect(service.$on).toBeCalledTimes(1);
這允許您使用回呼來呼叫所在的函式await app.close()。
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/532525.html
標籤:单元测试开玩笑的巢穴
上一篇:在vs代碼(windows)中運行和除錯-通過launch.json的Mochagrep選項給出錯誤:未找到測驗檔案(或運行所有測驗而不是模式)
