【问题标题】:How to test an observable stream?如何测试可观察流?
【发布时间】:2019-09-26 13:03:41
【问题描述】:

我想在 Angular 中为以下功能编写单元测试:

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

函数 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').

【问题讨论】:

    标签: angular unit-testing testing rxjs observable


    【解决方案1】:

    创建一个你在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();
    

    但如果不测试自己,我不确定。

    【讨论】:

    • 好的,我会留下它,以防其他人将来可能需要添加它。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-01-13
    • 2018-03-02
    • 2021-03-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多