TriggerEventHandler在单元测试角度4 [英] TriggerEventHandler in unit testing angular 4
问题描述
我有一个元素
<button class="next-btn" (mouseup)="someMethod()">Next</button>
我想在测试中模拟mouseup事件并且我这样做
I want to simulate mouseup event in testing and i do this
const nextBtnElem = fixture.debugElement.nativeElement;
const elem = nextBtnElem.getElementsByTagName('button')[1]
elem.triggerEventHandler('mouseup', null);
它不起作用,但如果我这样更改
it doesn't work, but if i change it like this
const nextBtnElem = fixture.debugElement.query(By.css('.next-btn');
nextBtnElem.triggerEventHandler('mouseup', null);
现在它正在工作。我无法理解为什么第一个选项不起作用?
Now its working. I can't understand why first optional doesn't work?
推荐答案
triggerEventHandler
是一个存在于Angular的上的函数DebugElement
。在你的第一个代码片段中,你在DOM对象上调用 triggerEventHandler
,它不提供这个功能。在DOM对象上,你可以使用< a href =https://developer.mozilla.org/en-US/docs/Web/Guide/Events/Creating_and_triggering_events =nofollow noreferrer> dispatchEvent 但您必须致电 fixture.detectChanges();
在触发事件和断言之间。
triggerEventHandler
is a function that exists on Angular's DebugElement
. In your first code snippet you are calling triggerEventHandler
on a DOM object, that does not provide this functionality. On DOM objects you could use dispatchEvent but you must call fixture.detectChanges();
between triggering your event and your assertions then.
这篇关于TriggerEventHandler在单元测试角度4的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!