Angular 2+ Observable retry在单元测试时

时间:2017-05-18 13:17:27

标签: angular observable angular2-observables

我正在尝试对一个返回带有retryWhen的observable的函数进行单元测试。我能够测试,如果错误与401,403或500不同,我最终会抛出一个错误,但我不知道如何检查是否有10次重试。

this.http.post(keepAliveUrl, {refreshToken: token.refreshToken} , options)
      .map(response => {
        return this.save(new Token(response.json()));
      })
      .retryWhen((errors) => {
        let errorCount = 0;
        return errors
          .mergeMap((error) => {
            if (errorCount >= 10 || error.status === 401 || error.status === 403 || error.status === 500) {
              return this.errorService.handleObservableError(error, 'token.service - refresh');
            } else {
              errorCount ++;
              return Observable.of(error);
            }
          });
      });

单元测试

it('[other error] => retry', fakeAsync(() => {
    let result: Token;
    let catchedError: any;

    this.tokenService.refresh(token)
      .subscribe(
        (token: Token) => result = token,
        (error: Error) => catchedError = error
      );

    tick();

    this.lastConnection.mockError(mockError({
      status: 409,
      statusText: 'Conflict',
    }));

    tick();

    expect(result).toEqual(undefined);
    expect(catchedError).toBeDefined();
  }));

0 个答案:

没有答案