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?
- It is slow.
- It is really slow.
- 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?
- Create a MouseEvent obj.
- Init the event with the proper type.
- 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: