1

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))
            )
          )
          )
        )
      );
  }
skyboyer
  • 22,209
  • 7
  • 57
  • 64
Mush
  • 2,326
  • 2
  • 16
  • 22
  • 2
    Please post your latest attempt at a unit test. StackOverflow expects you to [try to solve your own problem first](https://meta.stackoverflow.com/questions/261592/how-much-research-effort-is-expected-of-stack-overflow-users), as your attempts help us to better understand what you want. – dmcgrandle Dec 20 '18 at 08:10

1 Answers1

3

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

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

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

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

Mush
  • 2,326
  • 2
  • 16
  • 22