Search code examples
angularjsunit-testingjasminehttpbackend

Which URL to use when working with $httpBackend expectGET


When expecting a call to the API should I include the entire URL including all the parameters, or do I just need a partial match?

Should I be listening for a call to the exact URL :

http://address.of.api/stuff/123?include=thing,anotherthing.name;

Or do I just need this :

/stuff/123


Solution

  • $httpBackend is part of Angular's Mock environment designed to replace real backend by fake one, or rather by imitating how Angular's $http works without real backend.

    As much as I love Angular, I find $httpBackend over-engineered and unnecessarily complicated for what it does:

    • It is not recommended way to throw complicated code inside your tests. The more you do it, the more chance is that you create errors in that testing code instead of what you are actually supposed to test.

    • It promotes the bad practice of placing $http (or other low-level services in your abstraction hierarchy) freely around your code, as you can later use that $httpBackend to mock it away.

    Instead it works cleaner to isolate any reference to low level methods into dedicated methods of your own, whose single responsibility is to make http requests. These dedicated methods should be able to work with real backend, not a fake one!

    More details here on Angular testing