angular 12 中复选框更改处理函数的 Jasmine 测试

Jasmine test for checkbox change handler function in angular 12

我正在尝试为复选框更改编写简单的测试函数,但我无法 运行 它。 错误是 Spec 没有期望。并且处理函数未包含在代码覆盖范围内。

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

处理函数:

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

测试用例:

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

如何编写Jasmine测试用例来检查这个功能并覆盖if语句。

你的测试看起来不错,但问题是 spyOn 只是在方法上创建了一个间谍,returns 未定义,你丢失了实现细节。要保留实现细节(也意味着调用实际函数),您可以使用 .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();
}));