Testing a RESTful API using Supertest

Standard

This post explains how to test a RESTful API using Supertest.

There are many great blog posts that explain how to test NodeJS Express API’s using Supertest. For example:

This post explains how Supertest can be used to test any RESTful API even those that don’t run through express.

Setup

You will need a couple of node packages to get going including:

  • Supertest – “High-level abstraction module for testing HTTP”
  • Mocha – “Mocha is a simple, flexible, fun JavaScript test framework for node.js and the browser”
  • chai – “Chai is a BDD / TDD assertion library for node and the browser that can be delightfully paired with any javascript testing framework.”

Once installed your package.json should look something like this:

Testing API

To try out Supertest i tested http://postcodes.io/ – Postcode & Geolocation API for the UK

Searching for a single Post Code (GET Method)

APIhttp://api.postcodes.io/postcodes/SW1A1AA

In this method the user can query the Post Code data for a single post code. If valid, the API returns further detail.

In the tests below you can see a basic example that calls the API with a given Post Code and then performs assertions on the response. You can see in all three cases i’m checking the Status Code of the response and also inspecting the JSON response to ensure the correct data has been returned.

Searching for multiple Post Codes (POST Method)

To search for multiple Post Codes we need to POST an array of Post Codes to the API. To do this we pass in a JSON object to the service, in this example three post codes.

You can see we are again checking the status code of the response. In addition as multiple post codes are returned we iterate through the response to ensure the results match our search.

Summary

Supertest is really easy to use. You can very quickly write a series of tests for your API. Posting data and inspecting responses is very easy.

At this point i haven’t tried with a secure API that requires authentication but the documentation suggests that this shouldn’t be a problem.

Advertisements

2 thoughts on “Testing a RESTful API using Supertest

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s