问题
I had an element
<button class="next-btn" (mouseup)="someMethod()">Next</button>
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?
回答1:
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.
来源:https://stackoverflow.com/questions/47753863/triggereventhandler-in-unit-testing-angular-4