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.

1
  • 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 Commented Jul 16, 2021 at 14:01

1 Answer 1

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();
}));
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.