(AngularJS) Testing headers with whenGET / expectGET

Jotting this down here in case anyone else stumbles on the same issue(s) in AngularJS.

Suppose you’re mocking out $httpBackend in a unit test and want to test headers, like so:

// Assume $httpBackend and $http have been properly injected above
it("should not send a token if none is set", function() {
 $httpBackend.whenGET("/api-call", function(headers) {
   expect(headers.Authorization).toBeUndefined();
 }).respond(200, {hello: "world"});
 $http.get("/api-call");
 $httpBackend.flush();
});

This won’t work. If a function is passed to whenGET, it expects a true/false return value to signal whether the headers were correct. Instead, try this:

// Assume $httpBackend and $http have been properly injected above
it("should not send a token if none is set", function() {
 $httpBackend.whenGET("/api-call", function(headers) {
   return !headers.Authorization;
 }).respond(200, {hello: "world"});
 $http.get("/api-call");
 $httpBackend.flush();
});

Now, however, when the header test fails, you’ll get the following error:

Error: Unexpected request: GET /api-call

This is a bit misleading, since it implies the $http call somehow never hit $httpbackend. However, the issue isn’t that the GET request was unexpected; it’s that the the GET request with that particular header was incorrect. If you swap whenGET with expectGET, you’ll get a much more sensible failure message:

Error: Expected GET /api-call with different headers

In both cases, returning the correct header should make this failure go away.

Comments