View source Improve this doc

$httpBackend

service in module ngMock

Description

Fake HTTP backend implementation suitable for unit testing applications that use the $http service.

Note: For fake HTTP backend implementation suitable for end-to-end testing or backend-less development please see e2e $httpBackend mock.

During unit testing, we want our unit tests to run quickly and have no external dependencies so we don’t want to send XHR or JSONP requests to a real server. All we really need is to verify whether a certain request has been sent or not, or alternatively just let the application make requests, respond with pre-trained responses and assert that the end result is what we expect it to be.

This mock implementation can be used to respond with static or dynamic responses via the expect and when apis and their shortcuts (expectGET, whenPOST, etc).

When an Angular application needs some data from a server, it calls the $http service, which sends the request to a real server using $httpBackend service. With dependency injection, it is easy to inject $httpBackend mock (which has the same API as $httpBackend) and use it to verify the requests and respond with some testing data without sending a request to real server.

There are two ways to specify what test data should be returned as http responses by the mock backend when the code under test makes http requests:

  • $httpBackend.expect - specifies a request expectation
  • $httpBackend.when - specifies a backend definition

Request Expectations vs Backend Definitions

Request expectations provide a way to make assertions about requests made by the application and to define responses for those requests. The test will fail if the expected requests are not made or they are made in the wrong order.

Backend definitions allow you to define a fake backend for your application which doesn't assert if a particular request was made or not, it just returns a trained response if a request is made. The test will pass whether or not the request gets made during testing.

Request expectationsBackend definitions
Syntax .expect(…).respond(…) .when(…).respond(…)
Typical usage strict unit tests loose (black-box) unit testing
Fulfills multiple requests NO YES
Order of requests matters YES NO
Request required YES NO
Response required optional (see below) YES

In cases where both backend definitions and request expectations are specified during unit testing, the request expectations are evaluated first.

If a request expectation has no response specified, the algorithm will search your backend definitions for an appropriate response.

If a request didn't match any expectation or if the expectation doesn't have the response defined, the backend definitions are evaluated in sequential order to see if any of them match the request. The response from the first matched definition is returned.

Flushing HTTP requests

The $httpBackend used in production, always responds to requests with responses asynchronously. If we preserved this behavior in unit testing, we'd have to create async unit tests, which are hard to write, follow and maintain. At the same time the testing mock, can't respond synchronously because that would change the execution of the code under test. For this reason the mock $httpBackend has a flush() method, which allows the test to explicitly flush pending requests and thus preserving the async api of the backend, while allowing the test to execute synchronously.

Unit testing with mock $httpBackend

The following code shows how to setup and use the mock backend in unit testing a controller. First we create the controller under test

  1. // The controller code
  2. function MyController($scope, $http) {
  3. var authToken;
  4.  
  5. $http.get('/auth.py').success(function(data, status, headers) {
  6. authToken = headers('A-Token');
  7. $scope.user = data;
  8. });
  9.  
  10. $scope.saveMessage = function(message) {
  11. var headers = { 'Authorization': authToken };
  12. $scope.status = 'Saving...';
  13.  
  14. $http.post('/add-msg.py', message, { headers: headers } ).success(function(response) {
  15. $scope.status = '';
  16. }).error(function() {
  17. $scope.status = 'ERROR!';
  18. });
  19. };
  20. }

Now we setup the mock backend and create the test specs.

  1. // testing controller
  2. describe('MyController', function() {
  3. var $httpBackend, $rootScope, createController;
  4.  
  5. beforeEach(inject(function($injector) {
  6. // Set up the mock http service responses
  7. $httpBackend = $injector.get('$httpBackend');
  8. // backend definition common for all tests
  9. $httpBackend.when('GET', '/auth.py').respond({userId: 'userX'}, {'A-Token': 'xxx'});
  10.  
  11. // Get hold of a scope (i.e. the root scope)
  12. $rootScope = $injector.get('$rootScope');
  13. // The $controller service is used to create instances of controllers
  14. var $controller = $injector.get('$controller');
  15.  
  16. createController = function() {
  17. return $controller('MyController', {'$scope' : $rootScope });
  18. };
  19. }));
  20.  
  21.  
  22. afterEach(function() {
  23. $httpBackend.verifyNoOutstandingExpectation();
  24. $httpBackend.verifyNoOutstandingRequest();
  25. });
  26.  
  27.  
  28. it('should fetch authentication token', function() {
  29. $httpBackend.expectGET('/auth.py');
  30. var controller = createController();
  31. $httpBackend.flush();
  32. });
  33.  
  34.  
  35. it('should send msg to server', function() {
  36. var controller = createController();
  37. $httpBackend.flush();
  38.  
  39. // now you don’t care about the authentication, but
  40. // the controller will still send the request and
  41. // $httpBackend will respond without you having to
  42. // specify the expectation and response for this request
  43.  
  44. $httpBackend.expectPOST('/add-msg.py', 'message content').respond(201, '');
  45. $rootScope.saveMessage('message content');
  46. expect($rootScope.status).toBe('Saving...');
  47. $httpBackend.flush();
  48. expect($rootScope.status).toBe('');
  49. });
  50.  
  51.  
  52. it('should send auth header', function() {
  53. var controller = createController();
  54. $httpBackend.flush();
  55.  
  56. $httpBackend.expectPOST('/add-msg.py', undefined, function(headers) {
  57. // check if the header was send, if it wasn't the expectation won't
  58. // match the request and the test will fail
  59. return headers['Authorization'] == 'xxx';
  60. }).respond(201, '');
  61.  
  62. $rootScope.saveMessage('whatever');
  63. $httpBackend.flush();
  64. });
  65. });

Methods

  • expect(method, url, data, headers)

Creates a new request expectation.

Parameters

ParamTypeDetailsmethodstring

HTTP method.

urlstringRegExp

HTTP url.

data (optional) stringRegExpfunction(string)Object

HTTP request body or function that receives data string and returns true if the data is as expected, or Object if request body is in JSON format.

headers (optional) Objectfunction(Object)

HTTP headers or function that receives http header object and returns true if the headers match the current expectation.

Returns

requestHandler

Returns an object with respond method that control how a matched request is handled.

  • respond – {function([status,] data[, headers])|function(function(method, url, data, headers)} – The respond method takes a set of static data to be returned or a function that can return an array containing response status (number), response data (string) and response headers (Object).
  • expectDELETE(url, headers)

Creates a new request expectation for DELETE requests. For more info see expect().

Parameters

ParamTypeDetailsurlstringRegExp

HTTP url.

headers (optional) Object

HTTP headers.

Returns

requestHandler

Returns an object with respond method that control how a matched request is handled.

  • expectGET(url, headers)

Creates a new request expectation for GET requests. For more info see expect().

Parameters

ParamTypeDetailsurlstringRegExp

HTTP url.

headers (optional) Object

HTTP headers.

Returns

requestHandler

Returns an object with respond method that control how a matched request is handled. See #expect for more info.

  • expectHEAD(url, headers)

Creates a new request expectation for HEAD requests. For more info see expect().

Parameters

ParamTypeDetailsurlstringRegExp

HTTP url.

headers (optional) Object

HTTP headers.

Returns

requestHandler

Returns an object with respond method that control how a matched request is handled.

  • expectJSONP(url)

Creates a new request expectation for JSONP requests. For more info see expect().

Parameters

ParamTypeDetailsurlstringRegExp

HTTP url.

Returns

requestHandler

Returns an object with respond method that control how a matched request is handled.

  • expectPATCH(url, data, headers)

Creates a new request expectation for PATCH requests. For more info see expect().

Parameters

ParamTypeDetailsurlstringRegExp

HTTP url.

data (optional) stringRegExpfunction(string)Object

HTTP request body or function that receives data string and returns true if the data is as expected, or Object if request body is in JSON format.

headers (optional) Object

HTTP headers.

Returns

requestHandler

Returns an object with respond method that control how a matched request is handled.

  • expectPOST(url, data, headers)

Creates a new request expectation for POST requests. For more info see expect().

Parameters

ParamTypeDetailsurlstringRegExp

HTTP url.

data (optional) stringRegExpfunction(string)Object

HTTP request body or function that receives data string and returns true if the data is as expected, or Object if request body is in JSON format.

headers (optional) Object

HTTP headers.

Returns

requestHandler

Returns an object with respond method that control how a matched request is handled.

  • expectPUT(url, data, headers)

Creates a new request expectation for PUT requests. For more info see expect().

Parameters

ParamTypeDetailsurlstringRegExp

HTTP url.

data (optional) stringRegExpfunction(string)Object

HTTP request body or function that receives data string and returns true if the data is as expected, or Object if request body is in JSON format.

headers (optional) Object

HTTP headers.

Returns

requestHandler

Returns an object with respond method that control how a matched request is handled.

  • flush(count)

Flushes all pending requests using the trained responses.

Parameters

ParamTypeDetailscount (optional) number

Number of responses to flush (in the order they arrived). If undefined, all pending requests will be flushed. If there are no pending requests when the flush method is called an exception is thrown (as this typically a sign of programming error).

  • resetExpectations()

Resets all request expectations, but preserves all backend definitions. Typically, you would call resetExpectations during a multiple-phase test when you want to reuse the same instance of $httpBackend mock.

  • verifyNoOutstandingExpectation()

Verifies that all of the requests defined via the expect api were made. If any of the requests were not made, verifyNoOutstandingExpectation throws an exception.

Typically, you would call this method following each test case that asserts requests using an "afterEach" clause.

  1. afterEach($httpBackend.verifyNoOutstandingExpectation);
  • verifyNoOutstandingRequest()

Verifies that there are no outstanding requests that need to be flushed.

Typically, you would call this method following each test case that asserts requests using an "afterEach" clause.

  1. afterEach($httpBackend.verifyNoOutstandingRequest);
  • when(method, url, data, headers)

Creates a new backend definition.

Parameters

ParamTypeDetailsmethodstring

HTTP method.

urlstringRegExp

HTTP url.

data (optional) stringRegExpfunction(string)

HTTP request body or function that receives data string and returns true if the data is as expected.

headers (optional) Objectfunction(Object)

HTTP headers or function that receives http header object and returns true if the headers match the current definition.

Returns

requestHandler

Returns an object with respond method that controls how a matched request is handled.

  • respond – {function([status,] data[, headers])|function(function(method, url, data, headers)} – The respond method takes a set of static data to be returned or a function that can return an array containing response status (number), response data (string) and response headers (Object).
  • whenDELETE(url, headers)

Creates a new backend definition for DELETE requests. For more info see when().

Parameters

ParamTypeDetailsurlstringRegExp

HTTP url.

headers (optional) Objectfunction(Object)

HTTP headers.

Returns

requestHandler

Returns an object with respond method that control how a matched request is handled.

  • whenGET(url, headers)

Creates a new backend definition for GET requests. For more info see when().

Parameters

ParamTypeDetailsurlstringRegExp

HTTP url.

headers (optional) Objectfunction(Object)

HTTP headers.

Returns

requestHandler

Returns an object with respond method that control how a matched request is handled.

  • whenHEAD(url, headers)

Creates a new backend definition for HEAD requests. For more info see when().

Parameters

ParamTypeDetailsurlstringRegExp

HTTP url.

headers (optional) Objectfunction(Object)

HTTP headers.

Returns

requestHandler

Returns an object with respond method that control how a matched request is handled.

  • whenJSONP(url)

Creates a new backend definition for JSONP requests. For more info see when().

Parameters

ParamTypeDetailsurlstringRegExp

HTTP url.

Returns

requestHandler

Returns an object with respond method that control how a matched request is handled.

  • whenPOST(url, data, headers)

Creates a new backend definition for POST requests. For more info see when().

Parameters

ParamTypeDetailsurlstringRegExp

HTTP url.

data (optional) stringRegExpfunction(string)

HTTP request body or function that receives data string and returns true if the data is as expected.

headers (optional) Objectfunction(Object)

HTTP headers.

Returns

requestHandler

Returns an object with respond method that control how a matched request is handled.

  • whenPUT(url, data, headers)

Creates a new backend definition for PUT requests. For more info see when().

Parameters

ParamTypeDetailsurlstringRegExp

HTTP url.

data (optional) stringRegExpfunction(string)

HTTP request body or function that receives data string and returns true if the data is as expected.

headers (optional) Objectfunction(Object)

HTTP headers.

Returns

requestHandler

Returns an object with respond method that control how a matched request is handled.