3

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?

2
  • In which browsers do you get this error? Please specify Commented Dec 19, 2016 at 11:30
  • I had this issue using PhantomJS 1.9 (but not using 2.1) Commented Dec 19, 2016 at 12:11

2 Answers 2

1

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

Sign up to request clarification or add additional context in comments.

1 Comment

calling elem.triggerEventHandler('click', null) did the trick.
1

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');

2 Comments

Just tested it and seems not working, however the update works fine @yurzui
This did not work using Phantomjs 1.9.1 and TypeScript: TypeError: 'undefined is not a function (evaluating elem.nativeElement.trigger('click')')'.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.