mardi 25 août 2020

Nestjs request, interceptor in testing

I have RateUpInterceptor and this add count rate 1

@Injectable()
export class RateUpInterceptor implements NestInterceptor {
  constructor() {}

  intercept(context: ExecutionContext, next: CallHandler<any>): Observable<any> | Promise<Observable<any>> {
    const http = context.switchToHttp();
    const req = http.getRequest<IRequestAugmented>();
    const res = http.getResponse<Response>();
    return next.handle().pipe(
      tap(async () => {
        /** COUNT PLUS 1 **/
        console.log('A');
      }),
      catchError((e) => {
        return throwError(e);
      }),
    );
  }
}

describe('RateUpInterceptor', () => {
  let app: INestApplication;
  let module: TestingModule;

  beforeAll(async () => {
    module = await Test.createTestingModule({
      imports: [UserModule],
      providers: [
        {
          provide: APP_INTERCEPTOR,
          useFactory: () => {
            return new RateUpInterceptor();
          },
        },
      ],
    }).compile();

    app = module.createNestApplication();
    await app.init();

  });
  
  it('test', async () => {
    request(app.getHttpServer())
      .get(`valid url`)
      .auth(token, { type: 'bearer' })
      .expect(200).end(async () => {
        console.log('B');      
      });
  });  
});

I tested this interceptor by e2e test using request.

I thought that after global interceptor "console.log('B')" executes

but result was different... result wait this

B
A

How can I fix this order?

Aucun commentaire:

Enregistrer un commentaire