Posted by & filed under AngularJS.

$httpBackend is usually the right tool when you want to unit test angular $http requests made by a service or a controller. You can setup $httpBackend to verify or respond with some testing data without sending a request to a real server.

You can verify the data and the headers sent to the server, but unfortunately not all properties of the config parameter object passed to $http.get() are verifiable.
An effective way to assert that a call as been made with the cache feature is to use jasmine spies.

Let’s look at this very simple service :

Here, getDataFromServer() calls the server with the cache feature. Since $http.get() is only a shortcut for the default $http() method, the config instance passed in parameter is modified later and could fool your jasmine spy into thinking it has been called with more configurations than just the cache option.

This code snippet copied from AngularJS source code demonstrates how the short methods are created.

The extend call reuses the config passed in parameters, making your spy expectation difficult.

Now to avoid the above code to be called, you need to fake the call using andCallFake().

Here’s how to do this :

Easy enough. Using the same trick, you could probably verify other config properties and even write your own jasmine matchers. The last line @q.defer().promise ensures that a promise is also returned from your fake call, as with the real call.

Tweet about this on TwitterShare on Google+Share on LinkedInEmail this to someone

Leave a Reply

  • (will not be published)