Home > front end >  NestJS Testing Controller Middleware
NestJS Testing Controller Middleware

Time:02-24

I have implemented a nice piece of middleware which checks a supplied query param against a regex, it calls next() if no issue or next(Error) if there is an issue.

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));
    }
}

}

I get it to work by setting the configure inside the class of the module component.

@Module({
controllers: [MyController],
providers: [MyService]
})
export class MyModule implements NestModule {
  configure(consumer: MiddlewareConsumer) {
    consumer.apply(ValidateRegistrationMiddleware).forRoutes({
     path: 'service/:registration',
     method: RequestMethod.GET
     })
  }}

This works great, but I can't implement it and use it in my unit test of the controller it is working on. In my spec file I set up the module in the beforeEach, but I can't see where to setup the middleware. It is setup inside the module class not in the @Decorator in my actual module.

beforeEach(async () => {

const module: TestingModule = await Test.createTestingModule({
  controllers: [MyController],
  providers: [MyService],
}).compile();

controller = module.get<MyController>(MyController);
service = module.get<MyService>(MyService);

});

How do I get the middleware to run before every test? I want to test an invalid reg but currently the middleware does not get called.

CodePudding user response:

In the testing module, you reference providers and controllers however your middleware setup lives in MyModule which is not specified anywhere.

If you import MyModule instead I believe your middleware configuration will initialize.

Try this below

beforeEach(async () => {

  const module: TestingModule = await Test.createTestingModule({
    imports: [MyModule],
  }).compile();

  controller = module.get<MyController>(MyController);
  service = module.get<MyService>(MyService);

});
  • Related