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?
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
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');
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.