How to Test an AngularJS $http Service

Written by

In this post I will show you how to write a basic AngularJS service that makes an HTTP GET request to Vimeo using the $http service. As specified in the title, a TDD approach will be taken. Simplicity is key within this article so it’s definitely not for advanced Angular developers.

AngularJS

I will use Yeoman as usual to setup the project. Please refer to my previous post on Automating AngularJS With Yeoman, Grunt & Bower to help get started with these tools, be sure to follow through the instructions ensuring Karma is configured for e2e and unit testing.

Plan of action

Let’s pause for a moment and clarify exactly what we are aiming to achieve with this service from a high level perspective. We are going to make a request to the video service Vimeo for videos that the user newtriks likes. Vimeo offers a simple api request called likes and offers a variety of response formats. For this example the service class will request and expect a response in the JSON format. On receiving a response the service will handle either the success or error data from the vimeo api.

Service class logic

Now we know what we are aiming to achieve on a higher level, let’s now dive a little deeper and grasp the functionality of the service class. The service class will be expected to:

  1. Make a HTTP GET request to http://vimeo.com/api/v2/newtriks/likes.json.
  2. Handle a HTTP GET success response.
  3. Handle a HTTP GET error response.
  4. Notify the application with the response type and corresponding data.

This is a service expecting to interact with the Vimeo api for video likes but we would not want to restrict it to that one and only request. Therefore, the service needs to maintain flexability on the requests it can make. This could be accomplished by:

  1. Passing in specific parameters to the service class when making the request e.g. the request name passed in from a controller.
  2. An alternative approach would be to define specific api methods in the service class itself e.g. getLikes().

I favour option two as it keeps the scope of knowledge about the vimeo api restricted to the service class which means any changes to the vimeo api in the future will impact less of our application as a whole.

Create the project

mkdir http-service-example && cd $_
yo angular

Create the first e2e test

Create a service

yo angular:service vimeo

Start Karma

To start Karma which will also auto run the tests when we update the files use:

karma start

You should now see that two tests have been executed successfully:

Executed 2 of 2 SUCCESS (0.284 secs / 0.015 secs)

Create a failing test

Comments