Click for the code of this post in a Plnkr
Imagine you have an Angular service:
This is our main app config:
Now, you want to write a simple unit test that ensures both methods on your service actually make a GET
request.
This will fail. You will see the following:
This confused me. Why was $httpBackend trying to fetch the template on our main route?
The answer lies in the Angular docs:
Request expectations provide a way to make assertions about requests made by the application and to define responses for those requests. The test will fail if the expected requests are not made or they are made in the wrong order.
“Wrong order”. Angular’s $httpBackend service expected template.html
as the first $http request, yet the unit test expects the account_details.json
request to be the first.
So this means, we need to satisfy the GET
for template.html
before we run our tests.
Here’s the problem with the approach above. What if we have a resolve on our main app route as well?
Do we really want to have this in every test file when we need to test $http?
My solution was to create a helpers.js
file that lives in the testing folder. I create a global called utils
:
Now in each beforeEach
, I call utils.appInitResolve(httpBackend)
. Now if our resolve considerations change, we can update them in one file rather than crowd all the beforeEach blocks.