Angular mock uses $httpbackend service to test $http


Introduction to angular mock

The angular mock module provides module definition, loading, injection and other support for angular unit testing. Assist karma, jasmine and other JS testing tools to simulate the angular method and test the angular application. In addition, angular mock also extends NG’s multiple core services so that the tested code can be reviewed and controlled in a synchronous manner.


Reference in HTML:


You can also download or reference it in the following ways:

  • Bower

        bower install [email protected]


    10. Y and Z are the version numbers of angularjs you need.

Then enable the ngmock module in your angular application:

angular.module('app', ['ngMock']);

Module components


name describe
angular.mock Namespace for ‘angular mocks. JS’, which contains the test code.


name describe
$exceptionHandler Replay or record error information through $exceptionhandler simulation. see$exceptionHandlerProviderGet configuration information.
$log Simulation Implementation$logCollect the recorded log information in all arrays (one array for each record level). These arrays are used aslogsProperty can be obtained by the log method of each specific level. Example: for gradeerrorThe array can be obtained by $log.error.logs.
$interval Simulate the implementation of $interval service.
$httpBackend Used for$http serviceThe application provides a pseudo HTTP background for unit testing.
$timeout The service is just a simple decorator for$timeoutThe service adds “flush” and “verifynopendingtasks” methods.
$controller An additional bindings parameter was provided for $controller, which was used in the testbindToControllerCommand controller is very useful.

The above introduction information comes from the official API. If it is unclear in Chinese, please click the link to view the English description.

Test framework



npm install -g karma

to configure

Create config in the project directory you want to test

karma init karma.config.js

Using this command, question and answer settings will appear, including frame selection, including files / folders, test listening port, test browser, whether to use require.js, etc. Set according to the prompt.

$HTTP test example

$HTTP service example

This example provides two tests, a simple $HTTP service and a simple string matching test.

var app = angular.module('Application', []);

app.controller('MainCtrl', function($scope, $http) {
        $scope.users = data;
    $scope.text = 'Hello World!';

Save the file as JS / demo.js, which is required for testingIn orderImport the test project file and dependency file into config.js.

Setting the pseudo background with $httpbackend

For the above example, when testing, we do not need to actually send HTTP requests to obtain data. If you can only test the logic of the service, when sending a request, we can intercept the request and return a predefined data:

describe('MainCtrl', function() {
    //We will use this scope in the test
    var scope, $httpBackend;

    //Simulate our application module and inject our own dependencies

    //Simulate the controller and include $rootscope and $controller
    beforeEach(angular.mock.inject(function($rootScope, $controller, _$httpBackend_) {
        //Set up $httpbackend $HTTP request
        $httpBackend = _$httpBackend_;
        $httpBackend.when('GET', 'Users/users.json').respond([{
            id: 1,
            name: 'Bob'
        }, {
            id: 2,
            name: 'Jane'
        //Create an empty scope
        scope = $rootScope.$new();

        //Declare the controller and inject the created empty scope
        $controller('MainCtrl', {
            $scope: scope

    //The test starts here
    it('should have variable text = "Hello World!"', function() {
        expect(scope.text).toBe('Hello World!');
    it('should fetch list of users', function() {
        //Output results for easy viewing
        for(var i=0;i<scope.users.length;i++){

In the above example, $httpbackend.when and $httpbackend.expect can be used to set the requested pseudo data in advance. Finally, executing $httpbackend.flush after the request will immediately complete the HTTP request.

Save the test file in test / demo-test.js.

Next, find the set config.js file in the project directory and add the following reference to the files array:

files: [

In order to ensure the separation of test and project code, I suggest that the configuration file and test code be stored separately in the test directory, which can be deleted directly when the project is packaged.

Test run

After writing the test, use

karma start config.js

Let the test run. The default port of karma is 9876, which can be set in config.js. After running the command, the set browser will run automatically. Click the debug button to run the test code.

Open the console and you can see that the test has been successfully output.

$httpbackend common methods


Create a new backend definition.

when(method, url, [data], [headers]);


Create a new request expectation.

expect(method, url, [data], [headers]);

Both when and expect require four parametersmethod, url, data, headersThe last two parameters are optional.

  • Method means that HTTP methods should be capitalized (get, put…)< br/>

  • URL the requested URL can be regular or string;

  • Parameters carried during data request,

  • Headers the header set when requesting.

If these parameters are provided, the request will be correctly matched only when these parameters match. Both when and expect return an object with a response method. The response method has three parameters status, data and headers. You can forge the returned response data by setting these three parameters.


$httpBackend.whenAnd$httpBackend.expectThe differences are:$httpBackend.expectThe pseudo background can only be called once (it will be cleared after one call), and an error will be reported for the second call, and$httpBackend.resetExpectationsAll expectations can be removed without affecting when.

Shortcut method

Both when and expect have corresponding shortcut methods: whenget, whenpost, whenhead, whenjonp, whendelete, whenput; Expect is the same.

whenGET(url, [headers]);
whenHEAD(url, [headers]);
whenDELETE(url, [headers]);
whenPOST(url, [data], [headers]);
whenPUT(url, [data], [headers]);
expectGET(url, [headers]);
expectHEAD(url, [headers]);
expectDELETE(url, [headers]);
expectPOST(url, [data], [headers]);
expectPUT(url, [data], [headers]);
expectPATCH(url, [data], [headers]);

reference resources

Recommended Today

C # regular implementation of UBB parsing class code

The parsed code can pass XHTML   one   Strict verification;It includes title, link, font, alignment, picture, reference, list and other functions  Ubb.ReadMe.htm UBB code description title [H1] title I [/ H1] Title I [H2] Title II [/ H2] Title II [H1] Title III [/ H1] Title III [H4] Title IV [/ H4] Title IV […]