首页 > 解决方案 > 带有 retryWhen 的 rxjs 单元测试

问题描述

我有以下方法,我需要为它编写一些单元测试,但我无法模拟响应,我尝试使用 TestScheduler 但它没有成功,任何帮助将不胜感激。我在开玩笑。

protected waitForResponse(id: number, requestId: string) {
    return this.service.getData(id, requestId)
      .pipe(
        mergeMap((resp: ResponseModel) => {
          if (resp.status !== 'WAITING') {
            return of(resp);
          }
          return throwError(resp);
        }),
        retryWhen(errors => errors.pipe(
          concatMap((e, i) =>
            iif(
              () => i > 11,
              // max number of 11 attempts has been reached
              throwError(new HttpErrorResponse({status: HttpStatusCode.TOO_MANY_REQUESTS})),
              // Otherwise try again in 5 secs
              of(e).pipe(delay(5000))
            )
          )
          )
        )
      );
  }

标签: angularunit-testingrxjsjestjs

解决方案


我设法通过使用以下功能获得了解决方案:

const mockFunction = (times) => {    
    let count = 0;
    return Observable.create((observer) => {
        if (count++ > times) {
            observer.next(latestData);
        } else {
            observer.next(waitingData);
        }
    });
};

我用 jest spy 来模拟返回值:

jest.spyOn(service, 'getData').mockReturnValue(mockFunction(4));

这将返回 4 个等待响应,它们是最新的一个。

jest.spyOn(service, 'getData').mockReturnValue(mockFunction(20));

任何超过 11 的数字都将导致超过我的最大尝试次数


推荐阅读