如何在nestjs中测试http错误拦截器

问题描述 投票:0回答:1

我已经实现了这个拦截器来转换http错误,

    @Injectable()
    export class SolverInterceptor implements NestInterceptor {
      intercept(context: ExecutionContext, next: CallHandler): Observable<any> {
        // next.handle() is an Observable of the controller's result value
        return next.handle()
        
          .pipe(catchError(error => {
    
            if (error.response.data.method_response.status === AppFrameworkStatus.USER_ERROR) {
           
                 const response: RawJobMethodResponse = error.response.data.method_response;
              throw new InvalidSolverDataException(response);
            } else {
              const response: RawJobMethodResponse = error.response.data.method_response;
    
             throw new InvalidSolverDataException(response);
            }
          }));
      }
    }

但我不知道如何正确测试它,我已经尝试过如下所示的测试,但我不确定,请帮忙

    it('it should call', async () => {
       
        callHandler.handle.mockResolvedValueOnce('next handle');
        const actualValue = interceptor.intercept({} as any, { handle: () => of(error) });
      actualValue.subscribe({
        next: (val) => {
          expect(val).toBeInstanceOf(InvalidSolverDataException)
        },
typescript jestjs nestjs interceptor
1个回答
0
投票

为了能够测试 CallHandler 发送错误,首先我们必须让它抛出错误:

const handlerMock = {
  handle() {
    return throwError(() => new YourCustomError());
  },
} as CallHandler;

这是必要的,因为我们需要 Observable 来强制你的错误被管道上的 catchError 函数捕获:

return next.handle().pipe(catchError((error) => doErrorHandling))

然后在我们的拦截器返回上使用 subscribe 函数,并使用 Observer 接口 作为参数,而不仅仅是与错误交互的值:

next: x => console.log('Observer got a next value: ' + x),
error: err => console.error('Observer got an error: ' + err),
complete: () => console.log('Observer got a complete notification'),

我们可以忽略 next 并完成,因为我们只对错误部分感兴趣,它应该看起来与此类似:

it('Should throw InvalidSolverDataException when YourCustomError is thrown', (done) => {
const ctxMock = {
  switchToHttp: () => ({
    getRequest: () => ({}),
  }),
} as ExecutionContext;
const handlerMock = {
  handle() {
    return throwError(() => new YourCustomError());
  },
} as CallHandler;

errorInterceptor.intercept(ctxMock, handlerMock).subscribe({
  error: (error) => {
    expect(error).toEqual(
      new InvalidSolverDataException('the text that should be here'),
    );
    done();
  },
});

});

我们将done作为DoneCallback添加到测试函数中,以避免它在我们的订阅解决之前完成。默认情况下,它有 5 秒超时,但可以自定义:https://jestjs.io/docs/asynchronous

© www.soinside.com 2019 - 2024. All rights reserved.