[英]Nestjs - Unit testing for a controller that is inherited from CrudController
[英]NestJS Unit Testing for Controller: Mocking the Delete from Service Not Working
我目前正在對我的 NestJS 服務進行單元測試。 我的實體稱為“用戶”,我建立了一個基本服務,允許我與 MS SQL 服務器交互,並在我的 Controller 中建立 GET 和 POST 端點。
我的 Controller 文件中有一個delete
方法,它基本上只是從我的服務中調用delete
方法:
@Injectable()
export class ServiceName {
constructor(@InjectEntityManager() private manager: EntityManager) {}
async delete(id: number): Promise<any> {
return await this.manager.delete(User, id);
}
// some other functions
為了測試我的 Controller 的delete
方法,我從服務中模擬了相同的方法。 但是,當我為服務中的刪除方法定義了一個明確的模擬返回值時,這個模擬返回值與 Controller 中刪除方法的返回值不匹配,盡管它們應該是相同的。
這是我在 spec.ts 文件中的配置:
const mockService = {
delete: jest.fn(),
};
beforeEach(async () => {
const module: TestingModule = await Test.createTestingModule({
controllers: [ControllerName],
providers: [ServiceName],
})
.overrideProvider(ServiceName)
.useValue(mockService)
.compile();
service = module.get<ServiceName>(ServiceName);
controller = module.get<ControllerName>(ControllerName);
});
這是我的 spec.ts 文件中的測試用例:
it('testing delete', async () => {
mockService.delete.mockReturnValue(5);
expect(controller.delete(5)).toEqual(5);
})
上面的測試用例失敗了,下面顯示了錯誤信息:
expect(received).toEqual(expected) // deep equality
Expected: 5
Received: {}
122 | it('testing delete', async () => {
123 | mockService.delete.mockReturnValue(5);
> 124 | expect(controller.delete(5)).toEqual(5);
| ^
125 | })
126 | });
127 | });
任何幫助是極大的贊賞!
作為提醒,雖然您可以直接通過provider
,但我建議您在單元測試中提供提供程序的模擬。 因此,您將擁有providers: [ServiceName]
而不是
{
provide: ServiceName,
useValue: {
delete: jest.fn().mockResolvedValue(5)
}
}
這樣,您就可以從測試中了解正在使用的所有內容。 此外,當提供者擁有自己的依賴項(可能需要也可能不需要模擬)時,這種模式將使您避免遇到問題。 有關更多示例,您可以查看我的測試存儲庫
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.