Reputation: 1314
I am testing a component which has a click input on a div.
<div (click)="handleClick(someArgs)"></div>
Now I want to validate the behaviour in a test. I tried using .click()
on the native element:
const elem = fixture.debugElement.query(By.css('my-selector'));
elem.nativeElement.click();
// Check for desired changes
However this only works in specific browsers since .click()
seems to only be defined for HTMLInputElements (Relevant StackOverflow). I get the following error 'undefined' is not a function (evaluating elem.nativeElement.click()')
for a couple browsers.
What is the best way to invoke a click event on a non HTMLInputElement?
Upvotes: 3
Views: 2270
Reputation: 5719
Usually when you want to trigger click on html elements using plain js you have to call the event which is defined on the element.
UPDATE: if you are using Jasmine, you can try calling trigger
on the element:
const elem = fixture.debugElement.query(By.css('my-selector'));
elem.nativeElement.trigger('click');
Upvotes: 1
Reputation: 214047
I think the best way is calling triggerEventHandler()
on DebugElement
triggerEventHandler
Triggers the event by its name if there is a corresponding listener in the element's listeners collection. The second parameter is the event object expected by the handler.
If the event lacks a listener or there's some other problem, consider calling nativeElement.dispatchEvent(eventObject)
From testing documentation
Upvotes: 1