簡體   English   中英

如何測試可觀察的 stream?

[英]How to test an observable stream?

我想在 Angular 中為以下 function 編寫單元測試:

exportToCsv(query: string) {
    this.exportToCsvService.exportDataAndGetCsv(query).pipe(
      first(),
      tap(response => this.fireCsvDownload(response))
    ).subscribe();
  }

function exportDataAndGetCsv 調用 http 並返回一個字符串。 我認為我要編寫的測試應該檢查 fireCsvDownload 是否被執行。 我試過了:

it('should fire fireCsvDownload after exporting data and geting csv ', () => {
    component.exportToCsv(query);
    fixture.detectChanges();
    expect(component.fireCsvDownload).toHaveBeenCalled();
  });

但我收到一個錯誤: Error: <toHaveBeenCalled>: Expected a spy, but got Function. 我應該怎么辦? 我向TestBed提供exportToCsv服務, exportDataAndGetCsv返回of('text').

創建一個您在expect中替換的間諜:

it('should fire fireCsvDownload after exporting data and geting csv ', () => {

    const mySpy = spyOn(component, 'fireCsvDownload');
    component.exportToCsv(query);
    fixture.detectChanges();
    expect(mySpy).toHaveBeenCalled();
  });

您可能必須這樣做:

const mySpy = spyOn(component, 'fireCsvDownload').and.callThrough();

但我不確定沒有測試自己。

暫無
暫無

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

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