javascript - 测试 if 路径在 angular/jasmine 中不起作用
问题描述
我正在尝试编写一个测试存在于 ngOnInit 函数中的路径。而且我认为我已经找到了查看stackoverflow的方法。该函数的代码是:
ngOnInit() {
this.route.paramMap.subscribe((params: ParamMap) => {
this.partNoKey = params.get('partNoKey');
this.from = params.get('from');
// console.log(this.partNoKey);
// console.log(this.from);
if(this.from=="ncCutterSheetEdit"){
this.fromCutterSheet=true;
}
});
我目前的测试用例是:
it('should set fromCutterSheet to true when from is ncCutterSheetEdit', () =>{
component.from = "ncCutterSheetEdit";
fixture.detectChanges();
expect(component.from).toContain('ncCutterSheetEdit');
expect(component.fromCutterSheet).toBeTrue();
})
如果我注释掉最后一个期望语句,则测试通过,但是当我取消注释该期望语句时,它会失败并出现错误“预期为真假”。
同样,在我查看覆盖率报告时编写测试用例后,它仍将 if 语句显示为未采用的路径。我猜我没有正确的例子来说明我想做的事情。
有人可以请我为这个测试用例指出一个更合适的例子。
解决方案
ngOninit
在调用第一个afterdetectChanges
之后运行TestBed.createComponent(...)
。您需要ActivatedRoute
在此之前进行模拟,尤其是paramMap
它的方面。我怀疑它永远不会进入你的subscribe
街区。
像这样的东西:
import { of } from 'rxjs';
//.....
providers: [....
{
provide: ActivatedRoute,
useValue: { paramMap: of({ partNoKey: 'hello', from: 'noCutterSheetEdit' })
}],
一个可以为您提供更多详细信息并允许您控制的答案:How to test ngrx store action dispatch on route params change?
推荐阅读
- java - 从使用不同时区的日期计算时间
- c++ - c ++“错误:传递'const std :: vector
' 因为 'this' 参数丢弃了限定符 [-fpermissive]" - scala - 在构造函数的另一个参数的类型中引用依赖于路径的参数类型
- assembly - 为什么 rcx 在输入新标签时会刷新?
- kotlin - Kotlin,我怎样才能在这个意大利面条代码中缩短我的代码?
- excel - 在 Excel 中对多个条件进行排序和索引
- android - Android 10+ android.permission.NETWORK_STACK 用于隐藏 api
- r - R Jsonlite - 如何迭代 JSON 对象列表?
- c++ - 在天蓝色管道中分离构建和测试阶段的正确机制是什么?
- php - Laravel hasMany 和 belongsToMany 关系