Angular單元測試之事件觸發的實現
阿新 • • 發佈:2020-01-21
=在angular專案中時常有一些click、input、focusout等事件操作,那麼如何在單元測試中觸發這些事件呢?
一、觸發Click事件
// 方法一 const ele = fixture.debugElement.query(By.css("#id")); ele.triggerEventHandler('click',null) fixture.detectChanges(); // 更新檢視 // 方法二 const ele = fixture.nativeElement.querySelector("#id"); ele.click(); fixture.detectChanges(); // 更新檢視
二、觸發input事件
觸發input事件,需要在獲取到input元素後,先給輸入框繫結值,然後去觸發輸入事件,最後更新檢視。
const input = fixture.nativeElement.querySelector("#input"); input.value = 'abc'; input.dispatchEvent(new Event('input')); fixture.detectChanges(); // 更新檢視
二、觸發focusout事件
const input = fixture.nativeElement.querySelector("#input"); input.dispatchEvent(new Event('focusout')); fixture.detectChanges(); // 更新檢視
以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支援我們。