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

16,722

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.

Share:
16,722
vivek
Author by

vivek

Writing beautiful code.

Updated on June 23, 2022

Comments

  • vivek
    vivek about 2 years

    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?

  • vivek
    vivek about 10 years
    Sry, but the above code is not working from console.
  • mesteiral
    mesteiral about 10 years
    Did you get a reference to the element first? Something like: targetEl = document.getElementById('the-element'). Alternatively, can you provide the error message? All the snippets I posted are in use on the linked JSFiddle, too.