Test Driven Development of HTML Tags in Ionic
Directives are a feature of Angular, and thus Ionic, allowing us to make tags powered by JavaScript.
Last time, we talked about using Generator M to quickly build up a mobile app.
We will now use Test Driven Development and add a directive
to our app.
What we need
- Scaffold an app with Ionic using Generator M
- Some knowledge on testing angular directives
Setting up
Make sure you’ve installed the testing pre-reqs:
Karma generator sets up test/karma.conf.js – in here we’ll want to make the following changes:
Now Karma can find everything it’s looking for
Run the tests.
karma start test/karma.conf.js
Without any tests, you should see a notice about 0 out of 0
tests passing. Good.
Writing our first test
This in a file at project/test/karma/sound-button.js
:
But what does it do?
The test that we’ve just written should be failing. You can check by re-running the karma start test/karma.conf.js
command.
Taking a look inside, we see a mock object:
The audioMock object is our gateway into the directive. It allows us to make sure methods are being called. In this case, we want to be certain the audio is started and stopped.
The beforeEach()
commands run, well, before each test.
In this case, element
and scope
get compiled together to render our sound-button
directive.
we’re using the module() and inject() helpers that comes with Angular mocks. Additionally, we’re defining the Audio object to create our mocks – primarily because Jasmine doesn’t know what the Audio tag is.
Note that our constructor for window.Audio binds SRC onto the audio mock. This is less than ideal – we can only have one active mock at a time, unless we set up an array which we aren’t going to do.
Then we get to our actual test:
This sets up our spies on the mock audio object, and then iterates over each sound-button element. During each iteration, we check to make sure that clicking the element triggers play and pause events respecitvely, and that the second event is actually a stop command (i.e. sets time to 0).
Passing the test
We actually kinda want to write a directive, right? That was the whole idea.
This directive below should make the test pass.
This file belongs in app/main/directives/sound-button.js
Basically, we define a template inside the directive, restrict the directive to element bindings (i.e. <sound-button>
), setup the audio event, and attach click handlers.
The click handlers play/pause as well as update the UI. We could have added CSS animations, but that’s a-whole-nother 1am blog post.
Running the tests again should give you an all-green.
Conclusion
Karma is powerful. It wasn’t too hard to attach Karma to our Ionic application (once you get the paths right).
The power to write tests for directives, complete with click handling, is yours!