首页 > 解决方案 > 如何在角度单元测试中对服务进行单元测试?

问题描述

我的服务中有如下功能,

 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( 这个函数有关,但我不知道如何解决它。谁能给我建议帮助。谢谢。

标签: javascriptangularjasminekarma-jasmineangular-unit-test

解决方案


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


推荐阅读