我已经开始使用NestJS,并且对模拟警卫有疑问
用于单元测试。
我正在尝试测试基本的HTTP controller
,该方法具有Guard附加的方法。
当我向后卫注入服务时,我的问题开始了(我需要ConfigService
用于后卫)。
https://github.com/dannyhuly/nest-mock-guard-issue/blob/master/src/force-fail.guard.ts
运行测试时,DI无法解析后卫
● AppController › root › should return "Hello World!"
Nest can't resolve dependencies of the ForceFailGuard (?). Please make sure that the argument at index [0] is available in the _RootTestModule context.
请参阅规格文件: https://github.com/dannyhuly/nest-mock-guard-issue/blob/master/src/app.controller.spec.ts
我找不到有关此问题的示例或文档。我是想念东西还是真正的问题?
感谢任何帮助, 谢谢。
答案 0 :(得分:2)
提供的示例存储库存在3个问题:
带有.overrideGuard()
的Nestjs v6.1.1中有一个错误-请参见https://github.com/nestjs/nest/issues/2070
我已经确认它已在6.5.0中修复。
ForceFailGuard
在providers
中,但是其依存关系(ConfigService
)在创建的TestingModule
中不可用。
如果您要模拟ForceFailGuard
,只需将其从providers
中删除,然后让.overrideGuard()
进行即可。
mock_ForceFailGuard
具有CanActivate
而不是canActivate
的属性。
工作示例(nestjs v6.5.0):
import { CanActivate } from '@nestjs/common';
import { Test, TestingModule } from '@nestjs/testing';
import { AppController } from './app.controller';
import { AppService } from './app.service';
import { ForceFailGuard } from './force-fail.guard';
describe('AppController', () => {
let appController: AppController;
beforeEach(async () => {
const mock_ForceFailGuard: CanActivate = { canActivate: jest.fn(() => true) };
const app: TestingModule = await Test
.createTestingModule({
controllers: [AppController],
providers: [
AppService,
],
})
.overrideGuard(ForceFailGuard).useValue(mock_ForceFailGuard)
.compile();
appController = app.get<AppController>(AppController);
});
describe('root', () => {
it('should return "Hello World!"', () => {
expect(appController.getHello()).toBe('Hello World!');
});
});
});