• Toby Sinclair

Testing a RESTful API using Supertest

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:

  1. http://www.marcusoft.net/2014/02/mnb-supertest.html

  2. http://willi.am/blog/2014/07/28/test-your-api-with-supertest/

  3. https://www.codementor.io/nodejs/tutorial/testing-express-apis-with-supertest

  4. http://www.scotchmedia.com/tutorials/express/authentication/2/02

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:

  1. Supertest – “High-level abstraction module for testing HTTP”

  2. Mocha – “Mocha is a simple, flexible, fun JavaScript test framework for node.js and the browser”

  3. 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:.gist table { margin-bottom: 0; }

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)

API: http://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..gist table { margin-bottom: 0; }

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..gist table { margin-bottom: 0; }

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.

  • LinkedIn
  • Twitter

©2020 by Toby Sinclair.