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

问题描述

我找不到任何关于如何在 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();
    }
}

解决方法

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