AngularJS unit testing with Jasmine

I am currently working on a hybrid mobile app using Ionic which is based on AngularJS. AngularJS, just like my favorite ActionScript 3 framework Robotlegs, was designed to be testable. With helps of dependency injection and built in mocks, it is quite easy to write tests but still can be painful to get everything sorted out. Here are some tips to make life easier. Like a template (in WebStorm) to setup a test for a service:

1
2
3
4
5
6
7
describe('$MODULE$.$NAME$', function () {
var $NAME$;
beforeEach(module('$MODULE$'));
beforeEach(inject(function (_$NAME$_) {
$NAME$ = _$NAME$_;
}));
});

Mock dependencies

At start of tests when we load the module we can mock dependencies at the same time:

1
2
3
4
5
var $VALUE$;
beforeEach(module('$MODULE$', function ($provide) {
$VALUE$ = {$END$};
$provide.value('$VALUE$', $VALUE$);
}));

Test controllers

Unlike services, controllers can not be injected so we need to instantiate them ourselves.

Read More