typescript - NestJS Denetleyici Ara Katman Testi


Sağlanan bir sorgu parametresini bir regex ile kontrol eden güzel bir ara katman (middleware) uyguladım, sorun yoksa next() çağırır, sorun varsa next(Error) çağırır.

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

}

Modül bileşeninin sınıfının içinde yapılandırmayı ayarlayarak çalıştırıyorum.

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

Bu harika çalışıyor, ama bunu uygulayıp çalıştığı controller'ın birim testinde kullanamıyorum. Spec dosyamda beforeEach içinde modülü kuruyorum, ama middleware'i nerede kuracağımı göremiyorum. Middleware modül sınıfının içinde kurulmuş, gerçek modülümdeki @Decorator içinde değil.

beforeEach(async () => {

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

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

});

Ara yazılımın her testten önce çalışmasını nasıl sağlarım? Geçersiz bir kayıt test etmek istiyorum ama şu anda ara yazılım çağrılmıyor.

Cevap #1

Test modülünde, sağlayıcıları ve denetleyicileri referans gösteriyorsunuz, ancak ara katman (middleware) kurulumunuz MyModule içinde yer alıyor ve bu herhangi bir yerde belirtilmemiş.

Bence MyModule'ü ithal ederseniz, ara yazılım yapılandırmanız başlatılacaktır.

Aşağıdakini dene

beforeEach(async () => {

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

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

});