简体   繁体   中英

How to unit test a service in angular unit testing?

I have a function in my service as follows,,

 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'

      );
    }
  );
}

My test case,

  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();
}));

When I run it throws me error,

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

I understood that it is realated to this.pollingServiceService.pollRequest( this function, but I am not sure how to resolve it.Can anyone please suggest me help.Thanks.

Try to mock this request with 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(); }));

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM