首页 > 解决方案 > 测试 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 语句显示为未采用的路径。我猜我没有正确的例子来说明我想做的事情。

有人可以请我为这个测试用例指出一个更合适的例子。

标签: javascriptangulartypescriptjasminekarma-jasmine

解决方案


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?


推荐阅读