angular unit test - directive with DOM events

You finally finished writing your directive. A very interactive piece of UI, with a lot of mouse events. How do you test it?

Your directive

Probably looks somthing like this:

Now, how do you test it? The obvious solution will be to use some browser testing framework like protractor or selenium in order to simulate mouse events.

We really don’t want to depend on it… Why?

  1. It is slow.
  2. It is really slow.
  3. When you’re trying to click the browser automatically, you start to encounter some annoying scrolling issues…

Let’s do it in unit testing - without clicking!

Creating DOM event in javascript

The key here is to create a DOM event using pure javascript:

What do we have here?

  1. Create a MouseEvent obj.
  2. Init the event with the proper type.
  3. Dispatch the event on your element.

Testing your directive element

As we’ve seen in previous post, we can use angular jqLite in order to get the DOMElement. Take this and dispatch you event on it:

Take a look at the live example: