In the previous post we started implementing the masked input directive. We’ve written tests and the implementation of the directive’s controller. Now it’s time to add the directive itself and of course we’ll start form the tests.
Testing the directive means testing it’s interaction with the UI. These are your integration tests. We’ll want to test the controller logic and the way it reflects in the UI.
First we’d like to test that the directive’s isolated scope has the provided “mask” and “skip” values (keep in mind that in a real application you would test the existence of all the DDO values):
Some key notes from this test:
1. In order to test a directive we must create a string that represents its DOM (an element which has the directive attribute i.e.).
2. $compile service parses the element’s DOM and executes the directive function with the provided scope. So the “element” variable is now the directive with all its properties and methods.
3. We can access the scope properties using the element’s “ísolateScope” method.
Now let’s define the DDO:
Then we’d like to test that the element’s value will have the provided mask value after the DOM compiles.
And now with the link function:
In order to change the UI (the element’s value property) you have to call to $setViewValue that is a special angular method that is in charge of setting the value property of the directive element (<input type=”text” value=”this one”/>). $render is called for the UI changes to take place.
Now we add the directive to an html file and actually see all the stuff that we were testing. Add an index.html file, include angular and all the client folder except the spec files!
That’s what I’m talking about!
All that’s left is connecting our tested (TDD baby) controller functionality to every time the user presses a key.
I’ve created a keydown event using the private createKeyDownEvent method and fired it.
We subscribe to the keydown event, get the new char, call editMask and if successful re-render the UI.
That’s it! You have a functional masked input element which is fully tested.
As you can see, writing TDD with angular is extremely easy and straight forward. If you are not writing tests then you most definitely should! Just begin, it’s worth it.
Have fun TDDing,