首页 > 解决方案 > Nestjs请求,测试中的拦截器

问题描述

我有 RateUpInterceptor 和这个添加计数率 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');      
      });
  });  
});

我使用请求通过 e2e 测试测试了这个拦截器。

我以为在全局拦截器“console.log('B')”执行后

但结果不同......结果等等

B
A

我该如何解决这个订单?

标签: testingrequestnestjs

解决方案


推荐阅读