typescript - NestJS 测试 Controller 中间件

标签 typescript express nestjs

我已经实现了一个很好的中间件,它根据正则表达式检查提供的查询参数,如果没有问题,它调用 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/

相关文章:

nestjs - @Get DTO 在 NestJs 中有多个参数

javascript - 如果我们有更多记录而没有使用 angular8 中断,如何更改下拉值

Angular 2 最终版本 - ngModule 无法识别共享组件

javascript - node.js - 使用 Twilio 拨号

Nestjs - Controller 内定义的路由相互覆盖

postgresql - 应用程序容器未正确连接到部署中的 postgres 数据库

javascript - typescript 错误 TS2339 : Property 'webkitURL' does not exist on type 'Window'

html - addEventListener 到 HTMLDivElement 数组

javascript - 使用 EJS 或 jQuery 设置 HTML 标签的属性

node.js - 在 Cookie 中存储 Express Session