Mocking $http calls in unit tests

Loading

Mocking $http calls in AngularJS unit tests ensures that tests do not make real API requests, allowing for controlled and predictable test scenarios. In this guide, we’ll cover how to use $httpBackend (from angular-mocks) to mock HTTP requests in unit tests.


1. Setting Up AngularJS Unit Testing Environment

A. Install Required Dependencies

Ensure the necessary dependencies are installed:

npm install --save-dev karma karma-jasmine jasmine-core karma-chrome-launcher angular-mocks

B. Configure Karma

Update karma.conf.js to include necessary files:

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',
'services/*.js', // Service files
'tests/*.spec.js' // Test files
],
reporters: ['progress'],
singleRun: true
});
};

2. Sample AngularJS Service with $http Calls

A. UserService with $http Call

app.service('UserService', function($http) {
this.getUsers = function() {
return $http.get('/api/users');
};
});

3. Writing Unit Tests with $httpBackend

A. Testing UserService with Mocked $http Calls

Create tests/userService.spec.js and mock the API calls using $httpBackend:

describe('UserService', function() {
var UserService, $httpBackend;

beforeEach(module('myApp'));

beforeEach(inject(function(_UserService_, _$httpBackend_) {
UserService = _UserService_;
$httpBackend = _$httpBackend_;
}));

afterEach(function() {
$httpBackend.verifyNoOutstandingExpectation();
$httpBackend.verifyNoOutstandingRequest();
});

it('should return a list of users from API', function() {
var mockUsers = [{ id: 1, name: 'John Doe' }];

// Mocking the API response
$httpBackend.whenGET('/api/users').respond(200, mockUsers);

var response;
UserService.getUsers().then(function(res) {
response = res.data;
});

$httpBackend.flush(); // Resolve the HTTP call

expect(response).toEqual(mockUsers);
});

it('should handle error responses', function() {
$httpBackend.whenGET('/api/users').respond(500, { message: 'Server error' });

var errorResponse;
UserService.getUsers().catch(function(err) {
errorResponse = err.data;
});

$httpBackend.flush();

expect(errorResponse).toEqual({ message: 'Server error' });
});
});

4. Running the Tests with Karma

Execute the tests using:

npx karma start karma.conf.js

Leave a Reply

Your email address will not be published. Required fields are marked *