rxjs单元测试与retryWhen

时间:2018-12-20 02:08:54

标签: angular unit-testing rxjs jestjs

我有以下方法,我需要为其编写一些单元测试,但是我无法模拟响应,我尝试使用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))
            )
          )
          )
        )
      );
  }

1 个答案:

答案 0 :(得分:0)

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

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

我用玩笑的间谍来模拟返回值:

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

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

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

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