Mastering Web Application

(Rick Simeone) #1
Chapter 2

Testing AngularJS objects

Testing AngularJS objects is not much different from testing any other, regular
JavaScript class. Specific to AngularJS is its dependency injection system and the
way it can be leveraged in unit tests. To learn how to write tests leveraging the DI
machinery we are going to focus on testing services and controllers.


All the tests-related extensions and mock objects are distributed in a
separate AngularJS file named angular-mocks.js. Don't forget to
include this script in your test runner. At the same time it is important
not to include this script in the deployed version of an application.

Testing services

Writing tests for objects registered in AngularJS modules is easy but requires a bit
of initial setup. More specifically, we need to ensure that a proper AngularJS module
is initialized and the whole DI machinery brought to life. Fortunately AngularJS
provides a set of methods that make Jasmine tests and the dependency injection
system play together really nicely.


Let's break down a simple test for the notificationsArchive introduced in
Chapter 1, Angular Zen to see how to test AngularJS services. As a reminder here
is the code for the service itself:


angular.module('archive', [])
.factory('notificationsArchive', function () {

var archivedNotifications = [];
return {
archive:function (notification) {
archivedNotifications.push(notification);
},
getArchived:function () {
return archivedNotifications;
}};
});

Here is the corresponding test:


describe('notifications archive tests', function () {

var notificationsArchive;
beforeEach(module('archive'));
Free download pdf