2

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.

cnmuc
  • 6,025
  • 2
  • 24
  • 29

1 Answers1

3

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).

JB Nizet
  • 678,734
  • 91
  • 1,224
  • 1,255
  • I have this same problem- what do you mean define the decorator in a specific module and don't load that module in your test? Can you show a simple example of how that would look? – user3897392 Feb 05 '16 at 18:35
  • I found a userful link to another stack overflow that helped me understand how to have two separate modules and load them into one combined module: http://stackoverflow.com/questions/18512434/multiple-module-in-angularjs – user3897392 Feb 05 '16 at 20:52