【发布时间】:2019-09-14 19:47:02
【问题描述】:
我已经开始使用 NestJS 并且有一个关于嘲笑守卫的问题
用于单元测试。
我正在尝试测试一个基本的 HTTP controller,它有一个 Guard 附加方法。
当我向 Guard 注入服务时,我的问题就开始了(我需要 Guard 的 ConfigService)。
运行测试时,DI 无法解析 Guard
● 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.
我的力量失败守卫:
import { Injectable, CanActivate, ExecutionContext } from '@nestjs/common';
import { ConfigService } from './config.service';
@Injectable()
export class ForceFailGuard implements CanActivate {
constructor(
private configService: ConfigService,
) {}
canActivate(context: ExecutionContext) {
return !this.configService.get().shouldFail;
}
}
规格文件:
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: jest.fn(() => true) };
const app: TestingModule = await Test
.createTestingModule({
controllers: [AppController],
providers: [
AppService,
ForceFailGuard,
],
})
.overrideProvider(ForceFailGuard).useValue(mock_ForceFailGuard)
.overrideGuard(ForceFailGuard).useValue(mock_ForceFailGuard)
.compile();
appController = app.get<AppController>(AppController);
});
describe('root', () => {
it('should return "Hello World!"', () => {
expect(appController.getHello()).toBe('Hello World!');
});
});
});
我无法找到有关此问题的示例或文档。我错过了什么还是这是一个真正的问题?
感谢任何帮助, 谢谢。
【问题讨论】:
-
您找到解决方案了吗?我也面临同样的问题。
-
以后,请将相关代码粘贴到您的问题中。这使问题成为未来的证明,因为当您更改或删除您链接到的存储库时。这在这种情况下尤其需要,当这个问题是谷歌搜索“nestjs mock guard”时弹出的第一件事。
标签: unit-testing dependency-injection mocking jestjs nestjs