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
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.
3 Comments
MrPurpleStreak
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?
dnc253
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.Daan
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