pri_91
pri_91

Reputation: 79

If statements not covered in a function unit testing- Jasmine

I am writing jasmine test cases for a certain code. I have covered the functions in the component but the if statements in the functions are not covered. Below are the if statements from a function which are not covered.

 ngOnChanges(changes: SimpleChanges) {
 this.branchuserRole = this.userService.getUser().getId();
 if (this.data) {
  if (this.branchuserRole === this.TEST) {
    this.data = this.data.filter(task => task.assignedUser !== null);
    this.data = this.data.filter(task => task.assignedRole === this.TEST);
    this.summaryListLength = this.data.length;
  } else {
    this.summaryListLength = this.data.length;
  }

The whole if else part is not covered in the code-coverage. Below is the code I tried.

it('should call ngOnChanges function', () => {
    const changes: any = '';
    spyOn(component, 'ngOnChanges').and.callThrough();
    component.ngOnChanges(changes);
    expect(component.ngOnChanges).toHaveBeenCalled();
});
it('should set the value of data', () => {
    const changes: any = '';
    component.ngOnChanges(changes);
    component.branchuserRole = TEST;
    expect(component.data).toBeTruthy();
    expect(component.data).toEqual(component.data.filter(task => task.assignedUser !== null));
    expect(component.taskData).toEqual(component.taskData.filter(
        task => task.assignedRole === TEST));
    expect(component.summaryListLength).toEqual(component.data.length);
});

Upvotes: 0

Views: 8571

Answers (2)

Robert Tab
Robert Tab

Reputation: 174

Don't forget that you have a service which should return the branchuserRole. So you have to initialize the service in TestBed, then you need a spy over it and return the value you want. That is why you can't skip the if statement with branchUserRole. Now you just initialize the branchUserRole with TEST(I have no idea what test ist), but when you call the NgOnChanges the value of branchUserRole is overwriten or you recieve an error because the service is not initialized.

Upvotes: 1

Sachila Ranawaka
Sachila Ranawaka

Reputation: 41387

need to set the branchuserRole and data before calling the ngOnChanges

it('should set the value of data', () => {
    const changes: any = '';
    component.branchuserRole = TEST;
    component.data= []; // should not be null
    component.ngOnChanges(changes);
    expect(component.data).toBeTruthy();
    expect(component.data).toEqual(component.data.filter(task => task.assignedUser !== null));
    expect(component.taskData).toEqual(component.taskData.filter(
        task => task.assignedRole === TEST));
    expect(component.summaryListLength).toEqual(component.data.length);
});

Upvotes: 1

Related Questions