Search code examples
angularjsjasminedecoratorangular-httpangular-http-interceptors

"$httpBackend.when is not a function" error when mocking AngularJS $httpBackend in Jasmine tests and using a decorator


I'm using a decorator for Angular service $httpBackend to change the urls of all http calls:

app.config(function($provide) {
   $provide.decorator('$httpBackend', function($delegate) {
      return function(method, url, post, callback, headers, timeout, withCredentials, responseType) {
          url = changeUrl(url);
          $delegate(method, url, post, callback, headers, timeout, withCredentials, responseType);
      };
   })
});

In some Jasmine tests I need to mock the $httpBackend service:

describe('...', function() {
    beforeEach(module('...'));
    beforeEach(inject(function($injector) {
        $httpBackend = $injector.get('$httpBackend');
        $httpBackend.when('GET', '...').respond(function(method, url) {
            return ...
        });
    }));
}

Now I'm getting error "$httpBackend.when is not a function" when executing these tests.

Any idea how to fix this? I'd prefer a solution without having test specific code in my app config.


Solution

  • You can simply define the decorator in a specific module, and don't load that module in your test.

    Instead of decorating httpBackend, you could also use an http interceptor. Loading it in your tests would cause the same problem (but you could still use the same technique to avoid loading it in the tests if you want to).