我正在开发一个 Nest JS 项目。我想使用 jest 为 Nest JS 编写单元测试。在我的实际控制器中,我使用了 @UseFilters 注释。所以我也必须在我的测试控制器上包含过滤器。这是代码。
这是我的控制器代码
@Controller({ path: 'path', version: '1' })
@UseFilters(new AppErrorExceptionFilter())
export class MyController {
constructor(private readonly MyService: MYService) {}
@Post('data')
public async lsitData(
@Body() requestBody: RequestDto
) {
return this.myService.listData(requestBody)
}
}
这是我的测试控制器
describe('MyController',()=>{
let myController:MyController;
let myService:MyService;
beforeEach(async () => {
const module: TestingModule = await Test.createTestingModule({
controllers: [MyController],
providers: [MyService],
}).overrideFilter(AppErrorExceptionFilter).compile()
myController = module.get<MyController>(MyController);
myService = module.get<MyService>(MyService);
});
)}
此代码给出以下错误
Property 'compile' does not exist on type 'OverrideBy'.ts(2339)
any
这是我的nestjs版本“@nestjs/cli”:“^9.0.0”.
这是我第一次使用 jest 编写测试用例。所以我不知道测试的语法。我不确定我在哪里做错了,或者是否有其他方法来处理这个问题。
请看一下这个问题。我在这个问题上花了太多时间。
提前致谢。
注意:在NestJS 9.0.0及以上版本中,.compile()方法已从TestingModuleBuilder中删除。您不再需要显式调用 .compile() ;模块创建本身会编译所有内容。
使用 overrideFilter 时,您需要提供将要使用的内容,例如:
因此您的代码在 compile() 之前缺少上述其中一项。