I have been trying to perform a test for angular 2 application that clicks a submit button which calls a function. I usually use two methods to perform the same.
element.nativeElement.click()
and
element.triggerEventHandler('click',null);
I thought both these methods were same, until I came across this situation where triggering event handler method does not work.
element = fixture.debugElement.query(By.css('.dropList li'));
element.triggerEventHandler('click',null); //Click event works here
fixture.detectChanges();
let button = fixture.debugElement.query(By.css('button'));
//button.triggerEventHandler('click',null); //Does not call function
button.nativeElement.click(); //Calls function
fixture.detectChanges();
Template for your reference:
<form (ngSubmit)="printSelection()">
<div class="dropList">
<ul>
<li *ngFor="let element of data.elements" (click)="selectElement(element)"> </li>
</ul>
</div>
<button type="submit">Submit</button>
</form>
So, are there any difference between these two approaches or do you think I may have gone wrong somewhere in my code?