Rest API Testing with Mocha, Chai, SuperTest
Lets start by installing the three npm modules needed for API testing.
npm install mocha chai supertest --save-dev
Now you must be seeing Mocha, Chai and Supertest being added to your package.json.
Also update the package.json scripts to something like this,
"scripts": { "test": "mocha"}
Lets take a simple API that's free and simple to understand.
When you visit the website random.dog. ๐
There are two things here
- Static Text
- Random Image
Static Text remains the same every time you visit the website but that's not the case for the image. Its randomly changing because every time you visit the website, it gets it image source from its API that generates random image.
The website does a GET request to https://random.dog/woof .The response we get back is basically an image.
For this testing lets trigger a GET request to https://random.dog/woof.json. The response we get back is JSON format.
To verify this manually I am using POSTMAN. ๐ฎ
In the response, You could see on every request, random image is returned.
Now lets automate ๐ค this using Mocha, Chai and SuperTest.
Create a new file called test.js
under your project root directory. Write this code inside it.
Start by importing all the libraries that we just installed.
Then define a test suite with describe
. Multiple tests could be written with the keyword it
which basically means individual test. Both describe
and it
are provided by MOCHA.
Using SUPER TEST, we trigger a GET request and then store the response in a variable.
Now we verify the response code we got has a status code 200 โ
and we also verify that the URL in the response contains https://random.dog/ using expect
which is provided by CHAI. Here we are unable to verify the complete string because the remaining string is randomly generated.
We could add one more check to verify that the URL in response we get back contains either JPEG or GIF or PNG but I ll leave that for you to practice ๐ .
Since I have my tests in root directory ๐ and also specified main property in package.json has test.js. I did not need to specify mocha configs but if you have your tests inside folders, then update your package.json to something like this
"scripts": {"test": "mocha --recursive test/*.js"}
Now lets run the tests using npm test
.
And you have your first test running using the modern frameworks available in the market. ๐
In case , you want to get the source code. Feel free to download it.