【问题标题】:Angular test - how to mock IF conditions角度测试 - 如何模拟 IF 条件
【发布时间】:2022-01-12 16:52:25
【问题描述】:

我试图在我的组件中模拟以下方法,但测试似乎没有进入 if 条件

onChange(){
    this.selectedType = this.typeCtrl.value;
    this.selectedTypeLabel = this.typeCtrl.value;
    
    if(this.selectedType === 'Org')
        this.loadOrg();
    else  if(this.selectedType === 'Rep'){
        this.loadRep();
    }
    else if(this.selectedType === 'Teis'){
      this.loadTeis();
    }

    else if(this.selectedType === 'All'){
      this.data();
    }
    
  }

这是我在规范文件中的测试-

it('call onChange', () => {
  const spySubscribable = spyOn(component, 'fetch');
  const spySubscribable1 = spyOn(component, 'loadOrg');

 fixture.debugElement.componentInstance.orgCtrl.setValue('Org');
  let val = fixture.debugElement.componentInstance.orgCtrl.value;
  component.onChange();
  component.selectedType = val;
  component.selectedTypeLabel = val;
  component.loadOrg();
  expect(component.selectedType).toEqual(val);
  expect(spySubscribable1).toHaveBeenCalled();

  val = 'Rep';
  component.selectedType = val;
  component.selectedTypeLabel = val;
  component.onChange();
  fixture.detectChanges();
  component.loadRep();
  expect(component.selectedType).toEqual(val);

  val = 'Teis';
  component.selectedType = val;
  component.selectedTypeLabel = val;
  component.onChange();
  fixture.detectChanges();
  component.loadTeis();
  expect(component.selectedType).toEqual(val);

  val = 'All;
  component.selectedType = val;
  component.selectedTypeLabel = val;
  component.onChange();
  fixture.detectChanges();
  expect(component.selectedType).toEqual(val);
  expect(spySubscribable).toHaveBeenCalled();
  
});

如何在我的方法中测试所有 4 个 if 条件。我已经尝试将值分配给它,但它仍然没有覆盖。

【问题讨论】:

    标签: angular angular-test


    【解决方案1】:

    当您触发 onChange() 方法时,this.selectedTypethis.selectedTypeLabel 从中获取新值

     this.selectedType = this.typeCtrl.value;
     this.selectedTypeLabel = this.typeCtrl.value;
    

    如果您没有为 typeCtrl 属性赋值,那么 selectedTypeselectedTypeLabel 将是 undefined

    尝试组件component.typeCtrl = new FormControl('Org');,你的测试应该进入if语句

    【讨论】:

    • 你是对的..这解决了这个问题。非常感谢!
    猜你喜欢
    • 2022-01-10
    • 1970-01-01
    • 1970-01-01
    • 2021-06-19
    • 1970-01-01
    • 2020-06-24
    • 2019-06-05
    • 2023-04-02
    • 1970-01-01
    相关资源
    最近更新 更多