Home > Enterprise >  Angular test - how to mock IF conditions
Angular test - how to mock IF conditions

Time:12-08

I am trying to mock the below method in my component but the tests don't seem to enter the if conditions

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

Here is my test in spec file-

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

How to test all the 4 if conditions in my method . I have tried by assigning the values to it but it still doesnt cover.

CodePudding user response:

When you fire onChange() method this.selectedType and this.selectedTypeLabel get new value from

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

if you didn't assigne value to typeCtrl prop, so selectedType and selectedTypeLabel will be undefined.

Try component component.typeCtrl = new FormControl('Org'); and your test should enter if statement

  • Related