rxjs单元测试与retryWhen [英] rxjs unit test with retryWhen

查看:367
本文介绍了rxjs单元测试与retryWhen的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下方法,我需要为其编写一些单元测试,但是我无法模拟响应,我尝试使用TestScheduler,但未成功,将不胜感激.我在开玩笑.

I have the following method and I need to write some unit tests for it, but I cannot mock the response, I've tried using the TestScheduler but it was not successful, any help would be appreciated. I'm using jest.

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))
            )
          )
          )
        )
      );
  }

推荐答案

我已经设法通过使用以下函数来获取解决方案:

I've managed to get a solution by using the following function:

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

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

And them I've used jest spy on to mock the return value:

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

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

This will return 4 waiting responses and them the latest one.

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

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

Any number above 11 will result in exceeding my max number of attempts

这篇关于rxjs单元测试与retryWhen的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆