【问题标题】:Jasmine test for checkbox change handler function in angular 12Jasmine 测试 Angular 12 中的复选框更改处理程序功能
【发布时间】:2021-09-25 08:04:10
【问题描述】:

我正在尝试为复选框更改编写简单的测试函数,但我无法运行它。 错误是 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 语句。

【问题讨论】:

  • 您需要 1) 在测试中找到输入,2-a) 传递一个包含 target.checked 的模拟事件来满足第一个条件,2-b) 传递另一个包含 event.target 的模拟事件.检查为假

标签: angular typescript jasmine karma-jasmine angular-test


【解决方案1】:

您的测试看起来不错,但问题是 spyOn 只是在该方法上创建了一个间谍并返回 undefined 并且您丢失了实现细节。要保留实现细节(也就是调用实际函数),您可以使用.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();
}));

【讨论】:

    猜你喜欢
    • 2017-06-26
    • 2018-01-31
    • 2012-04-08
    • 1970-01-01
    • 2023-03-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多