【问题标题】:How to unit test a service in angular unit testing?如何在角度单元测试中对服务进行单元测试?
【发布时间】:2020-07-10 11:12:11
【问题描述】:

我的服务中有一个功能如下,,,

 exportPayGapDetails(filterObject: PayGapDetailFilter): void {
  const url = `${this.payGapDetailExportUrls[filterObject.type]}`;

  this.http
  .post<PollInitResponse>(
    `/adpi/rest/v2/sb/pe/v1/export/1/getStatusValue/222`,
    {}
  )
  .subscribe(
    res => {
      if (res) {
        this.pollingServiceService.pollRequest(
          `/adpi/rest/v2/sb/pe/v1/export/1/status`,
          this.ReadytoDownload.bind(this),
          this.PollCondition.bind(this)
        );
      } else {
        this.showToastMessage('error found);
      }
    },
    () => {
      this.showToastMessage('error found'

      );
    }
  );
}

我的测试用例,

  it('should call gender pay gap details init api when we pass type as GENDER_GAP on Export', fakeAsync(() => {
  spyOn(pollingService, 'pollRequest').and.callThrough();
  payGapDetailsService.exportPayGapDetails(filterDetailObject);
  // pollingService.pollSubscriptions.unsubscribe();
  tick();
  const req = http.expectOne(
    request =>
      request.method === 'POST' &&
      request.url === '/adpi/rest/v2/sb/pe/v1/export/1/getStatusValue/222'
  );
  req.flush(exportInitSucessResponse);
  http.verify();
}));

运行时会报错,

Error: Expected no open requests, found 1: GET /adpi/rest/v2/sb/pe/v1/export/1/status

我知道它与 this.pollingServiceService.pollRequest( 这个函数有关,但我不知道如何解决它。谁能给我建议帮助。谢谢。

【问题讨论】:

    标签: javascript angular jasmine karma-jasmine angular-unit-test


    【解决方案1】:

    尝试用 HttpTestingController 模拟这个请求:

      it('should call gender pay gap details init api when we pass type as GENDER_GAP on Export', fakeAsync(() => {
     spyOn(pollingService, 'pollRequest').and.callThrough();
     payGapDetailsService.exportPayGapDetails(filterDetailObject);
     httpMock = TestBed.get(HttpTestingController);
     tick();
     const request = httpMock.expectOne('/adpi/rest/v2/sb/pe/v1/export/1/getStatusValue/222');
     expect(request.request.method).toEqual('POST');
     req.flush(exportInitSucessResponse);
     http.verify();
    }));

    【讨论】:

    • 尝试使用 httpMock 并刷新到两个请求(内部请求也是),也许有帮助。
    猜你喜欢
    • 2019-05-15
    • 1970-01-01
    • 2012-01-08
    • 2021-03-11
    • 2021-12-01
    • 2010-09-07
    • 1970-01-01
    • 2014-05-10
    • 1970-01-01
    相关资源
    最近更新 更多