Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Dispatch event on the angular element in jasmine test is not working

In my test case I am trying something like this:

element = angular.element('<div></div>')
element.trigger('mouseenter');

But, there is error saying "undefined is not a function". I think its because I am not using jquery. I also, tried this:

goog.events.dispatchEvent(element[0], 'mouseenter');

But, it says that "Assertion failed: Can not use goog.events.dispatchEvent with non-goog.events.Listenable instance"

Is there any work around?

like image 272
vivek Avatar asked Oct 18 '25 19:10

vivek


1 Answers

What you're after is triggering mouse events programatically. No workarounds or libraries are needed for this. The objects or methods to be used depend on the environments that you want to target.

Triggering events programatically involves creating custom events. Since you control this custom event, you also decide whether it's cancelable or bubbles. Note that mouseenter on IE does not bubble.

The element event target below is not wrapped by any DOM library - it's just a reference to a DOM element named targetEl.

Current spec: Use the MouseEvent constructor.

var event = new MouseEvent('mouseenter', { 
  'view': window, 
  'bubbles': true, 
  'cancelable': true 
});
targetEl.dispatchEvent(event);

Older spec: Use document.createEvent and event.initEvent.

var event = document.createEvent('MouseEvents');
event.initEvent('mouseenter', true /*bubbles*/, true /*cancelable*/);
targetEl.dispatchEvent(event);

IE 8 and below: Use document.createEventObject and fireEvent.

var event = document.createEventObject();
targetEl.fireEvent('onmouseenter', event);

JSFiddle


For the part of your question that involved Closure: goog.events.dispatchEvent will not take a raw DOM element as event target, as it expects an object implementing a specific interface (a Listenable). As for Angular, its jqLite implementation doesn't include jQuery's .trigger() method.

The above approach is the way to go unless you are specifically evaluating the ability of libraries to trigger custom events (in contrast to responding to them) in your test environment.

like image 77
mesteiral Avatar answered Oct 22 '25 03:10

mesteiral



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!