首页 > 解决方案 > 如何测试可观察流?

问题描述

我想在 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.我该怎么办?我提供exportToCsv服务TestBedexportDataAndGetCsv退货of('text').

标签: angularunit-testingtestingrxjsobservable

解决方案


创建一个您在以下位置替换的间谍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();

但我不确定没有测试自己。


推荐阅读