首页 > 解决方案 > Angular - 如何测试应该被召回的服务,直到它回复OK?

问题描述

我有一个维护页面,应该在运行状况检查 API 回复正常后重定向到登录页面。

我的问题是:我想测试模拟 2 个调用:

. 但我不知道如何测试它是否this.$state.go在每次调用后单独调用了该方法。

一个例子:StackBlitz

我的实现:(重要的部分)

     ngOnInit() {
      const retries = interval(30000);
      //First check
      this.recheck();
  
      this.subscriptionInterval = retries.subscribe(() => {
         this.recheck();
      });
    }
  
    private recheck(): void {
      this.httpClient.get('/health-check').subscribe(
        () => {
          //In case of success, go to login
          this.subscriptionInterval.unsubscribe();
          this.$state.go('auth.login');
      }, () => {
        // otherwise, keep retrying.
      });
    }

整个文件:https ://stackblitz.com/edit/angular-ivy-plw32n?file=src%2Fapp%2Fapp.component.ts

我的测试:

  it('should keep retrying if is receiving errors', fakeAsync(() => {

    expect(component).toBeTruthy();

    tick(component.RETRIES_AFTER_MS);
    fixture.detectChanges();

    const requests = httpTestingController.match('/elb_health_check');
    expect(requests.length).toBe(2)

    // Respond to each request with different results
    requests[0].flush({}, { status: 500, statusText: 'INTERNAL ERROR' });
    requests[1].flush({}, { status: 200, statusText: 'OK' });
     
    // How to test that in first call it has not called the mockGo, but in the seconds has done it?
    expect(mockGo).toHaveBeenCalledTimes(0);
    expect(mockGo).not.toHaveBeenCalledWith('auth.login');

    component.subscriptionInterval.unsubscribe();
    flush();
  }));

它的一个例子:https : //stackblitz.com/edit/angular-ivy-plw32n?file=src%2Fapp%2Fapp.component.spec.ts(它不起作用,Stackblitz 不识别茉莉花)

我已经看到我们应该使用 tick 来模拟时间。但是在mock最后来的HttpClientTestModule的这个结构中,我不知道该怎么做。

标签: angularrxjsjasmine

解决方案


推荐阅读