How to increase branch coverage angular?

How to increase branch coverage angular?

How to increase branch coverage angular?

 

EXAMPLE (SIMPLE_FUNCTION)



 loadData(){
    if(this.faktor){ // here it should be true or false
      this.callMethod1();
    }else{
      this.callMethod2();
    }
  }

I will need to increase the test coverage and it is needed to test the branches. I tried with the example below but it is not working. I need to set the this.factor.isExist() to true. How can I do it?

How to increase branch coverage angular? How to increase branch coverage angular? How to increase branch coverage angular? How to increase branch coverage angular?

Here is my test component:

import { async, ComponentFixture, TestBed } from '@angular/core/testing';

import { ChartComponent } from './chart.component';

describe('ChartComponent', () => {
  let component: ChartComponent;
  let fixture: ComponentFixture<ChartComponent>;

  beforeEach(async(() => {
    TestBed.configureTestingModule({
      declarations: [ ChartComponent ]
    })
    .compileComponents();
  }));

  beforeEach(() => {
    fixture = TestBed.createComponent(ChartComponent);
    component = fixture.componentInstance;
    fixture.detectChanges();
  });

  it('should create', () => {
    expect(component).toBeTruthy();
  });

  it('should call method1  if factor exist', () => {
    const spy =  spyOn(component, 'callMethod1');
    component.factor.isExist() as true;
    expect(spy).toHaveBeenCalled();
  })

  it('should call method2 if factor not exist', () =>{
    const spy =  spyOn(component, 'callMethod2');
    component.factor.isExist() as false;
    expect(spy).toHaveBeenCalled();
  })
});
It is always not possible to make code coverage 100%, but yours is a very simple case, where you can cover all the code that you are showing here.
it('should call method1  if factor exist', () => {
    const spy =  spyOn(component, 'callMethod1');
    component.factor = 'Your mock data goes here'
    component.loadData();       // should execute if part
    expect(spy).toHaveBeenCalled();
  })

  it('should call method2 if factor not exist', () =>{
    const spy =  spyOn(component, 'callMethod2');
    component.factor = null;    
    component.loadData();     // should execute else part
    expect(spy).toHaveBeenCalled();
  })

Leave a Comment