簡體   English   中英

如何在角度單元測試中對服務進行單元測試?

[英]How to unit test a service in angular unit testing?

我的服務中有一個功能如下,

 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( 這個函數有關,但我不知道如何解決它。誰能建議我幫助。謝謝。

嘗試使用 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(); }));

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM