【问题标题】:Jasmine unit test: ngModelChange calls function or notJasmine 单元测试:ngModelChange 是否调用函数
【发布时间】:2019-09-26 15:18:19
【问题描述】:

我正在为 Angular 应用程序运行单元测试,如果函数正在运行,则在 ngModelChange 上运行,因为我正在测试该函数内部发生的一些逻辑。但是我的测试无法窥探这个函数是否被调用!!!

** component.spec.js**

it('should auto compute something', ()=>{
 component.record = "123";
 let spyOnDaemonChange = spyOn(component,'func1').and.callThrough();
 fixture.detectChanges();
 let daemonDOM = fixture.debugElement.query(By.css('#domelement'));
 daemonDOM.nativeElement.value ="123";
 fixture.detectChanges();
 expect(spyOnDaemonChange).toHaveBeenCalled(); //fails
})

component.ts

func1(){
 if(this.record == "abc"){
   this.num = 88;
 } else {
    this.num = 78; 
   }
}

**component.html**
 <td>
   <input style="width:300px;" id="domelement" type="text" class="form-control" [(ngModel)]="record" (ngModelChange) ="func1" name="record" required>
 </td>

component.record="123" 或 daemonDOM.nativeElement.value ="123";是相同的。这一定是触发了 ngModelChange 并调用了函数,对吗?

我希望测试检测到 ngModelChange 并调用函数

【问题讨论】:

  • 您应该在事件处理程序中调用该函数:(ngModelChange)="func1()"
  • 感谢 ConnorsFan

标签: javascript angular typescript unit-testing


【解决方案1】:

我可以使用 DOMelement.nativeElement.dispatchEvent(new Event('input')); 触发更改

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-01-02
    • 2020-01-26
    • 1970-01-01
    • 1970-01-01
    • 2015-09-12
    • 1970-01-01
    • 1970-01-01
    • 2021-07-20
    相关资源
    最近更新 更多