Testing controllers in AngularJS ensures that they function correctly, handle scope variables, and interact with services as expected. In this guide, we’ll walk through setting up Karma and Jasmine, writing unit tests for controllers, and best practices for testing in AngularJS.
1. Setting Up Karma and Jasmine for Testing
A. Install Required Dependencies
Use npm to install necessary testing libraries:
npm install --save-dev karma karma-jasmine jasmine-core karma-chrome-launcher angular-mocks
B. Configure Karma
Create a karma.conf.js file:
module.exports = function(config) {
config.set({
frameworks: ['jasmine'],
browsers: ['Chrome'],
files: [
'node_modules/angular/angular.js',
'node_modules/angular-mocks/angular-mocks.js',
'app.js', // Your AngularJS app file
'controllers/*.js', // Your controller files
'tests/*.spec.js' // Your test files
],
reporters: ['progress'],
singleRun: true
});
};
2. Writing a Sample AngularJS Controller
A. Sample UserController
app.controller('UserController', function($scope, UserService) {
$scope.users = [];
$scope.loadUsers = function() {
UserService.getUsers().then(function(response) {
$scope.users = response.data;
});
};
});
3. Writing Unit Tests for the Controller
A. Basic Test for UserController
Create userController.spec.js inside the tests/ directory:
describe('UserController', function() {
var $controller, $scope, UserService, deferred, $q;
beforeEach(module('myApp'));
beforeEach(inject(function(_$controller_, _$rootScope_, _UserService_, _$q_) {
$scope = _$rootScope_.$new();
UserService = _UserService_;
$q = _$q_;
deferred = $q.defer();
spyOn(UserService, 'getUsers').and.returnValue(deferred.promise);
$controller = _$controller_('UserController', { $scope: $scope, UserService: UserService });
}));
it('should initialize users as an empty array', function() {
expect($scope.users).toEqual([]);
});
it('should load users from UserService', function() {
var mockUsers = [{ id: 1, name: 'John Doe' }];
deferred.resolve({ data: mockUsers });
$scope.loadUsers();
$scope.$apply(); // Resolve promises
expect($scope.users).toEqual(mockUsers);
});
});
4. Running the Tests with Karma
Execute the tests using the following command:
npx karma start karma.conf.js
