如何在角度单元测试中对服务进行单元测试?

时间:2020-03-30 05:24:28

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

我的服务具有以下功能,

 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(这个函数,但是我不确定如何解决它。有人可以建议我帮忙。谢谢。

1 个答案:

答案 0 :(得分:0)

尝试使用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();
}));