angular - 如何编写测试用例来覆盖订阅回调函数中的行
问题描述
在我的组件中,我有以下代码:
setTakenNcatsNames(): void {
if (this.settings.route){
this.dataService.getAll(this.settings.route).subscribe(result =>
{
console.log('in herer');
this.arrTakenNcatsNames = result
});
}
}
如何编写测试用例来覆盖 .subscribe() 回调中的行?无论我尝试什么,我在 .subscribe 中的行总是显示为未覆盖。[2]
我的报道总是告诉我这个:
`
setTakenNcatsNames(): void {
Eif (this.settings.route){
this.dataService.getAll(this.settings.route).subscribe(result => {
**console.log('in herer');**
**this.arrTakenNcatsNames = result**
});
}
}
`
这是我的测试用例,我在这里缺少什么?
describe('setTakenNcatsNames()', () => {
fit('sets the array for taken NCATS names', fakeAsync(() => {
component.setTakenNcatsNames();
}));
});
解决方案
添加间谍dataService.getAll
fit('sets the array for taken NCATS names', fakeAsync(() => {
const service: DataService = TestBed.get(DataService);
spyOn(service, "getAll").and.returnValue(of('test');// create a mock result instead of test
component.setTakenNcatsNames();
expect(component.arrTakenNcatsNames ).toBe('test');// or mock result
}));
这样你就可以在 subscribe 下测试区块
推荐阅读
- oracle - Execute Immediate 语句可以嵌套在另一个 Execute Immediate 中吗
- c# - VS Code C# - 无法在调试控制台中运行控制台应用程序,但可以在集成终端中运行
- excel - 对图像使用 VLOOKUP
- mongodb - 在 Mongo 3.4 中重命名数组文档
- python - 通过具有 NaN 值的数据帧更新数据帧
- javascript - 由于没有 Access-Control-Allow-Origin 标头导致的浏览器错误
- tensorflow - 是否可以在冻结的推理图上用 FusedBatchNorm 替换 Batchnorm?
- reporting-services - 报告服务器上的错误,但 SSRS 或 SSMS 中没有
- c++ - C字符串在C++的显式构造函数中赋值?
- node.js - Keystonejs:更新用户资料时出错;姓名、电子邮件、通行证等