Ad

How To Use HttpBackend For The $http

- 1 answer

I'm having a hardtime to create a Test with the Controller that uses promise when doing initialization. here's my angularjs scirpt.

Javascript.js

   var appModule = angular.module('appModule', []);
appModule.controller('c0001Controller', function($http, $window) {

    var user = {};
    this.c0001Data = user;
    this.submitForm = function() {
            if(!angular.isUndefined(this.c0001Data.user_id) && !angular.isUndefined(this.c0001Data.password))
            {
                var promise = $http.post('C0001Login', user);

                promise.success(function(data, status, headers, config) {
                    if(data.message == 'error'){
                            alert('Invalid Username/Password');
                        } else {
                            $window.location.href =  data.url + "#/c0003";
                        }
                });
                promise.error(function(data, status, headers, config) {
                    alert("Invalid Username/Password");
                });
            }
            else {
                alert ("Invalid/ Username/password");
            }

    };

});
Ad

Answer

Using $httpBackend is more like setting up a fake call to intercept the original call of your $http service in your test cases.

Say you in your controller/service you have an $http get that gets from the request url 'api/employees'. In your test you would like to do something like this before the actual call to your function that calls $http:

$httpBackend.expectGET('api/employees').and.return(200, [ 
    { id: 1, name: 'sample' }, 
    { id: 2, name: 'sample 2' }
]);

(JasmineJS) In this way the original $http get request to your url 'api/employees' will not be called instead, the $httpBackend's setup/expected call will be called, and a http status code of 200 along with the array data will be returned.

This would work well on expecting a POST with data parameters. You should always know the request url, the data and other configs used in your original $http calls.

P.S. Always return appropriate HTTP status codes when using $httpBackend. Say, returning an HTTP status code 400 will trigger your catch block in the code you're testing.

Ad
source: stackoverflow.com
Ad