Search code examples
angulartypescriptjasminekarma-jasmineangular-test

Jasmine test for checkbox change handler function in angular 12


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.


Solution

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