Anelook Anelook - 3 years ago 62
AngularJS Question

How do I call triggerHandler with a specific fake 'event' parameter?

I'm trying to test that on a link click 'preventDefault' is called. However, I have difficulties to replace a real 'event' object with one I can spy on:

Here is how I trigger the click event:

var e = jasmine.createSpyObj('e', [ 'preventDefault' ]);
$element.triggerHandler('click', [e]);

However, when the directive code is being run, the event element is not replaced with a fake one:

$element.on('click', function(event) {

I tried different ways of adding a second parameter to triggerHandler - as an array, as an object, just some line, etc. Neither worked.. It is also not that many examples of triggerHandler together with additional parameters, so I feel a little bit lost...

Thanks in advance!

Answer Source

The docs say that triggerHandler() passes a dummy object to the handler:

If you check the source, you can see that triggerHandler() creates its own event object, and then passes your second argument as the event data, not the actual event object:

Relevant code:

var event = [{
  preventDefault: noop,
  stopPropagation: noop

forEach(eventFns, function(fn) {
  fn.apply(element, event.concat(eventData));

I've used jQuery's internal event simulator for creating my own events. That may work for you:

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download