angular - 如何测试可观察流?
问题描述
我想在 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
服务TestBed
和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();
但我不确定没有测试自己。
推荐阅读
- python - 在 Tkinter 中使用计时器制作 GUI?
- javascript - 页面中未出现 Javascript 函数结果(本地测试):如何识别问题?
- php - 如何在chrome打包的应用程序中使用php返回的数据
- c# - Unity:SignalR 连接在编辑器中工作但在设备中不工作(apk)
- docker - Docker 镜像清理如何在 Kubernetes 上工作?
- c++ - 无法在 dx11 中将两个纹理设置为着色器
- java - Spring - 使用值注释从本地配置文件中读取
- python - 创建包含年份和单词的共现矩阵
- c# - 如何在 UWP 的 TextBox 中动态更改 OpenType 功能?
- phpmyadmin - 如何在phpmyadmin中允许所有以192.168开头的IP?