After successfully implementing a middleware that checks query params against a regex pattern, I encountered some issues with integrating it into my unit tests. The middleware either calls next() if there are no issues 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));
}
}
}
To implement the middleware properly and use it in my tests, I had to configure it within the module component class.
@Module({
controllers: [MyController],
providers: [MyService]
})
export class MyModule implements NestModule {
configure(consumer: MiddlewareConsumer) {
consumer.apply(ValidateRegistrationMiddleware).forRoutes({
path: 'service/:registration',
method: RequestMethod.GET
})
}}
While this setup worked well for the application, I struggled to ensure the middleware ran before every test in the controller. I tried setting up the module in the beforeEach block of my spec file, but couldn't figure out how to include the middleware. Since the middleware was configured inside the module class, not as a decorator in the actual module, I faced this challenge.
beforeEach(async () => {
const module: TestingModule = await Test.createTestingModule({
controllers: [MyController],
providers: [MyService],
}).compile();
controller = module.get<MyController>(MyController);
service = module.get<MyService>(MyService);
});
If you have any suggestions on how to make the middleware run before each test in a controller, especially when testing invalid registration scenarios, please share your insights as the current setup doesn't trigger the middleware as expected.