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?

Community
  • 1
  • 1
fwind
  • 1,274
  • 4
  • 15
  • 32

2 Answers2

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

yurzui
  • 205,937
  • 32
  • 433
  • 399
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');
Yaser
  • 5,609
  • 1
  • 15
  • 27
  • Just tested it and seems not working, however the update works fine @yurzui – Yaser Dec 19 '16 at 11:36
  • This did not work using Phantomjs 1.9.1 and TypeScript: `TypeError: 'undefined is not a function (evaluating elem.nativeElement.trigger('click')')'`. – fwind Dec 19 '16 at 12:15