2

I am trying to write simple test function for check box change, but I am unabled to run it. The error is Spec has no expectations. and the handler function is not covered in code coverage,.

template: <input type="checkbox" (change)="handleChange($event)">

handler function:

handleChange(event:any){
     if(event.target.checked){
        this.myVariable= true;
     }else{
       this.myVariable = false;
     }
}

Test case:

it('checkbox change should set the myVariable value',fakeAsync(()=>{
 myCheckBox = fixture.debugElement.query(By.css('#myCheckBox'));
 spyOn(component, 'handleChange'); 
 myCheckBox.triggerEventHandler('change',{target: myCheckBox.nativeElement});
 tick();
 fixture.detectChanges();
 expect(component.myVariable).toBetrue;
}));

How should I write Jasmine test case to check this function and also cover if statement.

LoneWolf
  • 119
  • 1
  • 11
  • 1
    You need to 1) find the input in your tests, 2-a) pass a mocked event containing target.checked to fullfill the first condition and 2-b) pass another mocked event containing event.target.checked at false – TLd Jul 16 '21 at 14:01

1 Answers1

3

Your test seems good but the issue is that spyOn just creates a spy on the method and returns undefined and you lose implementation details. To keep the implementation details (meaning call the actual function as well), you can use .and.callThrough()

it('checkbox change should set the myVariable value',fakeAsync(()=>{
 myCheckBox = fixture.debugElement.query(By.css('#myCheckBox'));
 // change this line
 const handleSpy = spyOn(component, 'handleChange').and.callThrough(); 
 // change this line as well to mock the object
 myCheckBox.triggerEventHandler('change', { target: { checked: true });
 tick();
 fixture.detectChanges();
 expect(component.myVariable).toBeTrue();
 expect(handleSpy).toHaveBeenCalled();
}));
AliF50
  • 16,947
  • 1
  • 21
  • 37