如何使用 Jest 在 Nestjs 中测试超时拦截器

时间:2021-04-21 09:44:54

标签: node.js typescript jestjs nestjs nestjs-testing

我找不到任何关于如何在 NestJS 中测试拦截器的解释。

请帮我用jest测试拦截器?

import { Injectable, NestInterceptor, ExecutionContext, CallHandler, RequestTimeoutException } from "@nestjs/common";
import { Observable, throwError, TimeoutError } from "rxjs";
import { catchError, timeout } from "rxjs/operators";

@Injectable()
export class TimeoutInterceptor implements NestInterceptor {
    constructor(private readonly interval: number) {}

    intercept(_context: ExecutionContext, next: CallHandler): Observable<any> {
        if (this.interval > 0) {
            return next.handle().pipe(
                timeout(this.interval),
                catchError((error) => {
                    if (error instanceof TimeoutError) {
                        return throwError(new RequestTimeoutException(`The operation timed out. `));
                    }
                    return throwError(error);
                }),
            );
        }
        return next.handle();
    }
}

1 个答案:

答案 0 :(得分:0)

我曾尝试为这个拦截器编写单元测试,但我不喜欢它:/看:https://gist.github.com/micalevisk/33d793202541f044d8f5bccb81049b94