E2E mock $httpBackend doesn’t actually passThrough for me

I stumbled on the same problem but instead of implementing a rich API or replacing the original angular-mocks simply added in the following helper:

angular.module('httpReal', ['ng'])
    .config(['$provide', function($provide) {
        $provide.decorator('$httpBackend', function() {
            return angular.injector(['ng']).get('$httpBackend');
        });
    }])
    .service('httpReal', ['$rootScope', function($rootScope) {
        this.submit = function() {
            $rootScope.$digest();
        };
    }]);

It patches two issues that prevent an HTTP request from getting passed through:

  1. Restores original $httpBackend;

  2. Provides a method to fulfill the requests, as otherwise they would be in AngularJS’ queue waiting for a digest loop.

describe('my service', function() {
    var myService, httpReal;

    beforeEach(module('myModule', 'httpReal'));

    beforeEach(inject(function( _myService_, _httpReal_ ) {
        myService = _myService_;
        httpReal = _httpReal_;
    }));

    it('should return valid data', function(done) {
        myService.remoteCall().then(
            function(data) {
                expect(data).toBeDefined();
                done();
            }, function(error) {
                expect(false).toBeTruthy();
                done();
            });

        httpReal.submit();
    });
});

Leave a Comment