简体   繁体   English

在非InputElement上调用Angular2单击事件

[英]Invoke Angular2 click event on non InputElement

I am testing a component which has a click input on a div. 我正在测试一个在div上有点击输入的组件。

<div (click)="handleClick(someArgs)"></div>

Now I want to validate the behaviour in a test. 现在我想验证测试中的行为。 I tried using .click() on the native element: 我尝试在原生元素上使用.click()

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 ). 但是这仅适用于特定的浏览器,因为.click()似乎只为HTMLInputElements( 相关的StackOverflow )定义。 I get the following error 'undefined' is not a function (evaluating elem.nativeElement.click()') for a couple browsers. 我得到以下错误'undefined' is not a function (evaluating elem.nativeElement.click()')为几个浏览器。

What is the best way to invoke a click event on a non HTMLInputElement? 在非HTMLInputElement上调用click事件的最佳方法是什么?

I think the best way is calling triggerEventHandler() on DebugElement 我认为最好的方法是在DebugElement上调用triggerEventHandler()

triggerEventHandler 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) 如果事件缺少监听器或存在其他问题,请考虑调用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. 通常,当您想要使用普通js触发单击html元素时,您必须调用在元素上定义的事件。

UPDATE: if you are using Jasmine, you can try calling trigger on the element: 更新:如果你使用的是Jasmine,你可以尝试在元素上调用trigger

const elem = fixture.debugElement.query(By.css('my-selector'));
elem.nativeElement.trigger('click');

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM