1

The Angularjs tutorial shows something using the $http service and then testing that using the $httpBackend mock. What it doesn't explain is why you mock $httpBackend and not just mock the $http service itself? Can anyone shed light of this?

1 Answer 1

2

You don't mock $httpBackend. You use it to mock the actual HTTP requests that $http makes. I suppose you probably could just mock $http itself, but $httpBacked provides a lot of functionality for asserting certain requests are made (The expect methods) and for just dummying in a response (The when methods). In short, $httpBacked makes testing code that uses $http much much easier.

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

3 Comments

I guess it just doesn't explain it well in the docs. Usually (from what I gather) you service A and in testing you provide a mock A which gets injected instead. However here with have service H and the mock library provides a mock Hbackend to inject. Does the real $http use a real $httpBackend usually, but instead gets the mock $httpBackend, or is $httpBackend just a mock $http in which case how does angular know that is the case?
The way I understand it, $http does use an $httpBackend service, and then when using the ngMock module for tests, angular provides a different implementation of $httpBackend that allows you to test functionality making HTTP requests.
Also, one of the biggest advantages of using $httpBackend over $http is the fact that you don't need to wait for a-sync call to a server, it works synchronously, check this reading: docs.angularjs.org/api/ngMock.$httpBackend

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.