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.

3
  • 1
    Define the decorator in a specific module, and don't load that module in your test. Commented Oct 25, 2015 at 12:14
  • That was easy ;) Just copy your comment and I'll accept it as answer. Tx! Commented Oct 25, 2015 at 15:11
  • show an example of this. I am still getting an error Commented Mar 16, 2016 at 21:37

1 Answer 1

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

Sign up to request clarification or add additional context in comments.

2 Comments

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?
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: stackoverflow.com/questions/18512434/…

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.