Faking Mouse Events in D3

!D3

D3 is a great library but one of the challenges I have found is with unit testing anything based on event handlers.

In my specific example I was trying to show a tooltip when the user hovered over an element.

hoverTargets
  .on('mouseover', showTooltip(true))
  .on('mousemove', positionTooltip)
  .on('mouseout', closeTooltip);

D3 doesn’t currently have the ability to trigger a mouse event so in order to test the behaviour I have had to roll my own very simple helper to invoke these events.

$.fn.triggerSVGEvent = function(eventName) {
  var event = document.createEvent('SVGEvents');
  event.initEvent(eventName, true, true);
  this[0].dispatchEvent(event);
  return $(this);
};

This is implemented as jQuery plugin that directly invokes the event as if it had come from the browser.

You can use it as below:

$point.triggerSVGEvent('mouseover').triggerSVGEvent('mousemove');

It will probably change over time as I need to do more with it but for now this works as a way to test my tooltip behaviour.