Testing AngularJS controllers
Posted on 2015-04-26
So I just blogged about writing controllers in TypeScript. Here’s how to write tests for them now.
We recently refactored all our controllers to become classes and also (quite importantly) not use
$scope.$watch anymore. We went this way after experiencing
$watch itself and testability. This blog article outlines good reasons not to do it.
With that in mind, anything that can be made to happen in a model is a straight forward test. Then, most things that can happen in a controller become easy to
test as well! There should be a very limited set of actions that a controller can do. It can
$broadcast events, it can call AJAX (via a service
ideally) and it can respond to events.
Here’s a simple sample test class for a controller.
This is a very cut down example, but it demonstrates a few things. First, mocking a service is quite easy with Jasmine. Then, using
$injector to get
other dependencies you don’t need for testing if you’re too lazy to mock them (I know I was!).
Looking back, passing null into dependencies that aren’t used in the tests would be much easier… I’ll see about that later!comments powered by Disqus