Chapter 2
Testing controllers
A test for a controller follows similar a pattern to the one for a service. Let's have a look
at the fragment of the ProjectsEditCtrl controller from the sample application. This
controller in question is responsible for the editing projects in the administration part
of the application. Here we are going to test methods of the controller responsible for
adding and removing project's team members:
angular.module('admin-projects', [])
.controller('ProjectsEditCtrl', function($scope, project) {
$scope.project = project;
$scope.removeTeamMember = function(teamMember) {
var idx = $scope.project.teamMembers.indexOf(teamMember);
if(idx >= 0) {
$scope.project.teamMembers.splice(idx, 1);
}
};
//other methods of the controller
});
The logic of the presented controllers is not complex and will let us to focus on the
test itself:
describe('ProjectsEditCtrl tests', function () {
var $scope;
beforeEach(module('admin-projects'));
beforeEach(inject(function ($rootScope) {
$scope = $rootScope.$new();
}));
it('should remove an existing team member', inject(function
($controller) {
var teamMember = {};
$controller('ProjectsEditCtrl', {
$scope: $scope,
project: {
teamMembers: [teamMember]
}
});
//verify the initial setup
expect($scope.project.teamMembers).toEqual([teamMember]);