Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to substitute $httpBackend with alternate mock server?

I have Angular (1.2.x) unit tests where I'm utilizing ngMock. My project has a fixture system that relies on sinon.fakeServer. For my unit tests, I'd prefer to use this as opposed to the $httpBackend .

ngMockE2E tests Angular provides a passthrough method, however there isn't a clear equivalent for unit tests. The rationale seems to be that unit tests should never be passing-through (to a server) but in my situation I'm just trying to pass through to a non-Angular-dependent-mock.

My strategy right now is to create a shim that matches .whenGet and .whenPost requests and routes them to my fake server.

However, what would be better is simply "turning off" the $httpBackend. Is there a way to do this?

like image 875
vpiTriumph Avatar asked Oct 18 '22 10:10

vpiTriumph


2 Answers

You may want to try

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();
        };
    }]);

This way you can restore httpBackend. For more details please refer: E2E mock $httpBackend doesn't actually passThrough for me

like image 83
Lalit Kale Avatar answered Nov 01 '22 15:11

Lalit Kale


This solution might work.

So the proposition is to use ngMockE2E’s $httpBackend. Actually if your test cause XHR request, it is not a 'Unit Test'.

like image 29
Igor Tsvetkoff Avatar answered Nov 01 '22 15:11

Igor Tsvetkoff