Mastering Web Application

(Rick Simeone) #1

Building and Testing


//execute and verify results
$scope.removeTeamMember(teamMember);
expect($scope.project.teamMembers).toEqual([]);
}));
});

The removeTeamMember method that we want to test here will be defined on a
$scope and it is the ProjectsEditCtrl controller that defines this method. To
effectively test the removeTeamMember method we need to create a new scope,
a new instance of the ProjectsEditCtrl controller and link the two together.
Essentially we need to manually do the job of the ng-controller directive.


Let's turn our attention to the beforeEach section for one more moment, as there are
interesting things going on in there. Firstly we are getting access to the $rootScope
service and creating a new $scope instance ($scope.$new()). We do so to simulate
what would happen in a running application, where the ng-controller directive
would create a new scope.


To create an instance of the controller we can use the $controller service (please
notice how the inject function can be placed on the beforeEach section as well as
on the it level).


Look how easy it is to specify controller's constructor arguments while
invoking the $controller service. This is dependency injection at
its best; we can provide both a fake scope and test data to exercise
controller's implementation in complete isolation.

Mock objects and asynchronous code testing

We can see how AngularJS provides a very nice integration of its dependency
injection system with the Jasmine testing framework. But the good testability
story continues as AngularJS provides some excellent mock objects as well.


Asynchronous programming is the bread and butter of JavaScript. Unfortunately
asynchronous code tends to be hard to test. Asynchronous events are not very
predictable, and can fire in any order and trigger actions after an unknown period of
time. The good news is that the AngularJS team provides excellent mock objects that
make testing asynchronous code really easy and what is important is that they are
fast and predictable. How can this be? Let's have a look at the example test exercising
the code using the $timeout service. First at the code itself:


angular.module('async', [])
.factory('asyncGreeter', function ($timeout, $log) {
return {
Free download pdf