测试 if 路径在 angular/jasmine 中不起作用

Test of an if path not working in angular/jasmine

我打算编写一个测试,该路径存在于 ngOnInit 函数中。而且我认为我已经找到了查看 Whosebug 的方法。函数代码为:

  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();
  })

如果我注释掉最后一个 expect 语句,则测试通过,但是当我取消对该 expect 语句的注释时,它会失败并显示错误“Expected false to be true”。

此外,在我查看覆盖率报告时编写测试用例后,它仍然显示 if 语句是一条未采用的路径。我猜我没有合适的例子来说明我想做什么。

谁能给我指出一个更适合这个测试用例的例子。

ngOninit 在调用 TestBed.createComponent(...) 之后的第一个 detectChanges 之后运行。您需要在此之前模拟 ActivatedRoute,尤其是它的 paramMap 方面。我怀疑它永远不会进入你的 subscribe 块。

像这样:

import { of } from 'rxjs';
  //.....
  providers: [.... 
              {
                 provide: ActivatedRoute, 
                 useValue: { paramMap: of({ partNoKey: 'hello', from: 'noCutterSheetEdit' })
               }],

可以为您提供更多详细信息并允许您控制的答案: