共享运算符导致Jest测试失败

时间:2018-10-12 09:05:01

标签: angular rxjs jestjs

我有一个发出HTTP请求的Angular服务。服务的主要工作是刷新访问令牌,如果请求结果为401,则重试该请求。该服务还能够以宽限期处理多个并发请求:如果有3个请求结果为401,则该令牌将仅刷新一次,并且将重播所有3个请求。 以下GIF总结了这种行为: enter image description here

我的问题是我似乎无法测试这种行为。最初,由于未调用我的订阅或错误方法,因此我的测试始终会因超时而失败。添加fakeAsync之后,我不再超时,但是仍然没有调用我的观察者。我还注意到,如果我从tokenObservable中删除了共享运算符,则会调用测试中的订阅,但是这样做将失去多播的好处。

这是无法正常工作的测试

it('refreshes token when getting a 401 but gives up after 3 tries', fakeAsync(() => {
const errorObs = new Observable(obs => {
  obs.error({ status: 401 });
}).pipe(
  tap(data => {
    console.log('token refreshed');
  })
);
const HttpClientMock = jest.fn<HttpClient>(() => ({
  post: jest.fn().mockImplementation(() => {
    return errorObs;
  })
}));
const httpClient = new HttpClientMock();

const tokenObs = new Observable(obs => {
  obs.next({ someProperty: 'someValue' });
  obs.complete();
});

const AuthenticationServiceMock = jest.fn<AuthenticationService>(() => ({
  refresh: jest.fn().mockImplementation(() => {
    return tokenObs;
  })
}));
const authenticationService = new AuthenticationServiceMock();

const service = createSut(authenticationService, httpClient);

service.post('controller', {}).subscribe(
  data => {
    expect(true).toBeFalsy();
  },
  (error: any) => {
    expect(error).toBe('random string that is expected to fail the test, but it does not');
    expect(authenticationService.refresh).toHaveBeenCalledTimes(3);
  }
);
}));

这是我在SUT中注入模拟内容的方式:

  const createSut = (
    authenticationServiceMock: AuthenticationService,
    httpClientMock: HttpClient
  ): RefreshableHttpService => {
    const config = {
      endpoint: 'http://localhost:64104',
      login: 'token'
    };
    const authConfig = new AuthConfig();

    TestBed.configureTestingModule({
      providers: [
        {
          provide: HTTP_CONFIG,
          useValue: config
        },
        {
          provide: AUTH_CONFIG,
          useValue: authConfig
        },
        {
          provide: STATIC_HEADERS,
          useValue: new DefaultStaticHeaderService()
        },
        {
          provide: AuthenticationService,
          useValue: authenticationServiceMock
        },
        {
          provide: HttpClient,
          useValue: httpClientMock
        },
        RefreshableHttpService
      ]
    });

    try {
      const testbed = getTestBed();
      return testbed.get(RefreshableHttpService);
    } catch (e) {
      console.error(e);
    }
  };

以下是被测系统的相关代码:

    @Injectable()
export class RefreshableHttpService extends HttpService {
  private tokenObservable = defer(() => this.authenthicationService.refresh()).pipe(share());
  constructor(
    http: HttpClient,
    private authenthicationService: AuthenticationService,
    injector: Injector
  ) {
    super(http, injector);
  }
  public post<T extends Response | boolean | string | Array<T> | Object>(
    url: string,
    body: any,
    options?: {
      type?: { new (): Response };
      overrideEndpoint?: string;
      headers?: { [header: string]: string | string[] };
      params?: HttpParams | { [param: string]: string | string[] };
    }
  ): Observable<T> {
    return defer<T>(() => {
      return super.post<T>(url, body, options);
    }).pipe(
      retryWhen((error: Observable<any>) => {
        return this.refresh(error);
      })
    );
  }

  private refresh(obs: Observable<ErrorResponse>): Observable<any> {
    return obs.pipe(
      mergeMap((x: ErrorResponse) => {
        if (x.status === 401) {
          return of(x);
        }
        return throwError(x);
      }),
      mergeScan((acc, value) => {
        const cur = acc + 1;
        if (cur === 4) {
          return throwError(value);
        }
        return of(cur);
      }, 0),
      mergeMap(c => {
        if (c === 4) {
          return throwError('Retried too many times');
        }

        return this.tokenObservable;
      })
    );
  }
}

及其继承的类:

 @Injectable()
export class HttpService {
  protected httpConfig: HttpConfig;
  private staticHeaderService: StaticHeaderService;
  constructor(protected http: HttpClient, private injector: Injector) {
    this.httpConfig = this.injector.get(HTTP_CONFIG);
    this.staticHeaderService = this.injector.get(STATIC_HEADERS);
  }

由于某些未知原因,它无法解决第二次调用refresh方法返回的可观察对象。   奇怪的是,如果您从SUT的tokenObservable属性中删除了共享运算符,它就会起作用。   它可能与时间有关。与Jasmine不同,Jest不会嘲笑Date.now,而RxJ会利用它。   一种可行的方法是尝试使用RxJs中的VirtualTimeScheduler来模拟时间,   尽管那是fakeAsync应该做的。

依赖项和版本:

  1. 角度6.1.0
  2. Rxjs 6.3.3
  3. 笑话23.6.0
  4. 节点10.0.0
  5. Npm 6.0.1

以下文章帮助我实现了该功能: RxJS: Understanding the publish and share Operators

1 个答案:

答案 0 :(得分:1)

我已经研究了这个问题,并且似乎有一些想法为什么它对您不起作用:

1)Angular HttpClient服务在异步代码中引发错误,但您是同步完成的。结果,它破坏了共享运算符。如果可以调试,则可以通过查看ConnectableObservable.ts

来查看问题。

enter image description here

在测试中,连接仍将处于打开状态,而HttpClient异步代码中的连接将退订并关闭,因此下次将创建新连接。

要解决此问题,您还可以在异步代码中触发401错误:

const errorObs = new Observable(obs => {
   setTimeout(() => {
     obs.error({ status: 404 });
   });
...

但是您必须等待使用tick执行所有异步代码后:

service.post('controller', {}).subscribe(
  data => {
    expect(true).toBeFalsy();
  },
  (error: any) => {
    expect(error).toBe('Retried too many times');
    expect(authenticationService.refresh).toHaveBeenCalledTimes(3);
  }
);

tick(); // <=== add this

2)并且您应该在RefreshableHttpService中删除以下表达式:

mergeScan((acc, value) => {
    const cur = acc + 1;
    if (cur === 4) { <== this one
      return throwError(value);
    }

因为我们不想在value上下文中引发错误。

之后,您应该接听所有刷新呼叫。

我还创建了示例项目https://github.com/alexzuza/angular-cli-jest

只需尝试npm inpm t

  Share operator causes Jest test to fail
    √ refreshes token when getting a 401 but gives up after 3 tries (41ms)

  console.log src/app/sub/service.spec.ts:34
    refreshing...

  console.log src/app/sub/service.spec.ts:34
    refreshing...

  console.log src/app/sub/service.spec.ts:34
    refreshing...

Test Suites: 1 passed, 1 total
Tests:       1 passed, 1 total
Snapshots:   0 total
Time:        4.531s, estimated 5s
Ran all test suites.

您也可以通过npm run debug

对其进行调试
相关问题