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.
You will need a couple of node packages to get going including:
- Supertest – “High-level abstraction module for testing HTTP”
Once installed your package.json should look something like this:
To try out Supertest i tested http://postcodes.io/ – Postcode & Geolocation API for the UK
Searching for a single Post Code (GET Method)
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.
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.