Testing AngularJS services is crucial to ensure your application’s business logic functions correctly. Karma (test runner) and Jasmine (testing framework) provide a powerful combination for unit testing services 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
'services/*.js', // Your service files
'tests/*.spec.js' // Your test files
],
reporters: ['progress'],
singleRun: true
});
};
2. Writing a Sample AngularJS Service
A. Sample MathService
app.service('MathService', function() {
this.add = function(a, b) {
return a + b;
};
this.subtract = function(a, b) {
return a - b;
};
});
3. Writing Unit Tests for the Service
A. Basic Test for MathService
Create mathService.spec.js
inside the tests/
directory:
describe('MathService', function() {
var MathService;
beforeEach(module('myApp')); // Load Angular module
beforeEach(inject(function(_MathService_) {
MathService = _MathService_;
}));
it('should add two numbers correctly', function() {
expect(MathService.add(2, 3)).toBe(5);
});
it('should subtract two numbers correctly', function() {
expect(MathService.subtract(5, 3)).toBe(2);
});
});
4. Testing a Service with API Calls ($httpBackend
)
A. Sample UserService
Making HTTP Request
app.service('UserService', function($http) {
this.getUser = function(userId) {
return $http.get('/api/users/' + userId);
};
});
B. Unit Test Using $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(); // Simulate server response
expect(result).toEqual(mockUser);
});
afterEach(function() {
$httpBackend.verifyNoOutstandingExpectation();
$httpBackend.verifyNoOutstandingRequest();
});
});
5. Running the Tests with Karma
Execute the tests using the following command:
npx karma start karma.conf.js