我已经实现了一个很好的中间件,它根据正则表达式检查提供的查询参数,如果没有问题,它调用 next() ,如果有问题,它调用 next(Error) 。
export class ValidateRegistrationMiddleware implements NestMiddleware {
use(req: Request, res: Response, next: NextFunction){
let reg = new RegExp('^[A-Z0-9 _]*$');
if (reg.test(req.params.registration)) {
next()
} else {
next(new InvalidRegistrationException('Invalid Registration :' + req.params.registration, HttpStatus.BAD_REQUEST));
}
}
}
我通过在模块组件的类中设置配置来使其工作。
@Module({
controllers: [MyController],
providers: [MyService]
})
export class MyModule implements NestModule {
configure(consumer: MiddlewareConsumer) {
consumer.apply(ValidateRegistrationMiddleware).forRoutes({
path: 'service/:registration',
method: RequestMethod.GET
})
}}
这很好用,但我无法实现它并在它正在处理的 Controller 的单元测试中使用它。在我的规范文件中,我在 beforeEach 中设置了模块,但我看不到在哪里设置中间件。它是在模块类中设置的,而不是在我实际模块中的 @Decorator 中。
beforeEach(async () => {
const module: TestingModule = await Test.createTestingModule({
controllers: [MyController],
providers: [MyService],
}).compile();
controller = module.get<MyController>(MyController);
service = module.get<MyService>(MyService);
});
如何在每次测试之前运行中间件?我想测试一个无效的注册表,但目前中间件没有被调用。
最佳答案
在测试模块中,您引用提供程序和 Controller ,但是您的中间件设置位于 MyModule
中,但未在任何地方指定。
如果您导入 MyModule
,我相信您的中间件配置将会初始化。
试试下面这个
beforeEach(async () => {
const module: TestingModule = await Test.createTestingModule({
imports: [MyModule],
}).compile();
controller = module.get<MyController>(MyController);
service = module.get<MyService>(MyService);
});
关于typescript - NestJS 测试 Controller 中间件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/71242992/