Unit testing is crucial for maintaining reliable and bug-free AngularJS applications. Jasmine is a powerful testing framework used to test AngularJS components, including controllers, services, directives, and filters.
1. Setting Up Jasmine for AngularJS
To unit test AngularJS components, you need:
✔ Jasmine – Testing framework
✔ Karma – Test runner (optional but recommended)
✔ Angular Mocks – Simulate AngularJS dependencies
A. Install Required Packages
npm install --save-dev jasmine-core karma karma-jasmine karma-chrome-launcher angular-mocks
B. Include Dependencies in Your Test File
require('angular');
require('angular-mocks');
2. Writing a Simple Jasmine Test
Jasmine uses describe() and it() functions to structure tests.
Example: Basic Jasmine Test
describe('Basic Jasmine Test', function() {
it('should add numbers correctly', function() {
var sum = 5 + 3;
expect(sum).toBe(8);
});
});
3. Testing AngularJS Controllers
A. Sample Controller
app.controller('MainController', function($scope) {
$scope.message = 'Hello, AngularJS!';
});
B. Unit Test for Controller
describe('MainController', function() {
var $controller, $rootScope;
beforeEach(module('myApp')); // Load Angular module
beforeEach(inject(function(_$controller_, _$rootScope_) {
$controller = _$controller_;
$rootScope = _$rootScope_;
}));
it('should initialize message correctly', function() {
var $scope = $rootScope.$new();
var controller = $controller('MainController', { $scope: $scope });
expect($scope.message).toBe('Hello, AngularJS!');
});
});
4. Testing AngularJS Services
A. Sample Service
app.service('MathService', function() {
this.add = function(a, b) {
return a + b;
};
});
B. Unit Test for Service
describe('MathService', function() {
var MathService;
beforeEach(module('myApp'));
beforeEach(inject(function(_MathService_) {
MathService = _MathService_;
}));
it('should add two numbers correctly', function() {
expect(MathService.add(2, 3)).toBe(5);
});
});
5. Testing HTTP Requests with $httpBackend
A. Sample Service Making API Call
app.service('UserService', function($http) {
this.getUser = function(id) {
return $http.get('/api/users/' + id);
};
});
B. Unit Test with $httpBackend
describe('UserService', function() {
var UserService, $httpBackend;
beforeEach(module('myApp'));
beforeEach(inject(function(_UserService_, _$httpBackend_) {
UserService = _UserService_;
$httpBackend = _$httpBackend_;
}));
it('should fetch user data', function() {
var mockUser = { id: 1, name: 'John Doe' };
$httpBackend.expectGET('/api/users/1').respond(200, mockUser);
var result;
UserService.getUser(1).then(function(response) {
result = response.data;
});
$httpBackend.flush(); // Simulates server response
expect(result).toEqual(mockUser);
});
afterEach(function() {
$httpBackend.verifyNoOutstandingExpectation();
$httpBackend.verifyNoOutstandingRequest();
});
});
6. Testing AngularJS Directives
A. Sample Directive
app.directive('customGreeting', function() {
return {
template: '<h1>{{greeting}}</h1>',
scope: {
greeting: '@'
}
};
});
B. Unit Test for Directive
describe('customGreeting Directive', function() {
var $compile, $rootScope;
beforeEach(module('myApp'));
beforeEach(inject(function(_$compile_, _$rootScope_) {
$compile = _$compile_;
$rootScope = _$rootScope_;
}));
it('should display correct greeting text', function() {
var element = $compile('<custom-greeting greeting="Hello, World!"></custom-greeting>')($rootScope);
$rootScope.$digest(); // Trigger AngularJS digest cycle
expect(element.html()).toContain('Hello, World!');
});
});
7. Testing AngularJS Filters
A. Sample Filter
app.filter('capitalize', function() {
return function(input) {
return input.charAt(0).toUpperCase() + input.slice(1);
};
});
B. Unit Test for Filter
describe('capitalize Filter', function() {
var capitalize;
beforeEach(module('myApp'));
beforeEach(inject(function($filter) {
capitalize = $filter('capitalize');
}));
it('should capitalize the first letter of a string', function() {
expect(capitalize('hello')).toBe('Hello');
});
});
8. Running Tests with Karma
Karma Configuration (karma.conf.js)
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
'tests/*.spec.js' // Your test files
],
reporters: ['progress'],
singleRun: true
});
};
Run Tests with Karma
npx karma start karma.conf.js
