【问题标题】:Test of an if path not working in angular/jasmine测试 if 路径在 angular/jasmine 中不起作用
【发布时间】:2020-11-20 15:28:25
【问题描述】:

我正在尝试编写一个测试路径,该路径存在于 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 语句显示为未采用的路径。我猜我没有合适的例子来说明我想做的事情。

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

【问题讨论】:

    标签: javascript angular typescript jasmine karma-jasmine


    【解决方案1】:

    ngOninit 在调用TestBed.createComponent(...) 之后的第一个detectChanges 之后运行。您需要在此之前模拟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?

    【讨论】:

    • 谢谢,这正是我所需要的
    • 实际上我已经在每个之前都有一个激活的路线,因此在代码报告显示else路径之前。
    • ngOnInit 中发生的事情进行测试可能很困难,因为第一个detectChanges 使其运行,您必须对beforeEachdescribe 块进行创意。不幸的是会导致重复的代码。
    • 虽然重复代码并不理想,但我可以直截了当地说,无论如何都要测试两条路径。
    猜你喜欢
    • 2020-08-21
    • 2016-05-14
    • 1970-01-01
    • 1970-01-01
    • 2017-05-25
    • 1970-01-01
    • 2017-07-23
    • 2013-08-31
    • 1970-01-01
    相关资源
    最近更新 更多