In this post, we'll take a look at what tools/technologies do we need for writing API tests using JavaScript and then we'll also write our first API test. So let's get started...
First off, we'll need to get the following dependencies installed to set up our base framework -
- Node JS and NPMĀ (to install the packages below)
- Mocha JSĀ (for test framework)
- Chai JSĀ (for assertions)
- SuperTestĀ (for making API calls)
- BabelĀ (to use ES6+ in our tests)
Note: the above libraries/frameworks are optional to use, you can replace any one or all of them to meet your desired goals.
Setup Your Project
You can watch the installation video below to see how to install all these packages and get your project setup:
Write an API Test
Once you have your project setup, we will begin to write our API test in theĀ users.jsĀ file (created as part of the installation video above).
import supertest from 'supertest';
const request = supertest('https://gorest.co.in/public-api/');
import { expect } from 'chai';
// watch the installation video to create your token
const TOKEN = {your_token_here}
describe('Users', () => {
it('GET /users', (done) => {
// make a GET call to the users api
request.get(`users?access-token=${TOKEN}`).end((err, res) => {
// assertion to ensure data is not empty
expect(res.body.data).to.not.be.empty;
// done callback to handle async calls
done();
});
});
});
Run Your Test
Now, its time to run your test, you can do that by running theĀ
mocha
command or doingĀ npm test
Ā which will also run the sameĀ mocha
command if you followed the installation video.There you go, we just created our first API test and it ran successfully š.
You can also clone theĀ GitHub repoĀ to access this code
I hope this post helped you out, let me know in the comments below!
Happy testing! š
- Subscribe to myĀ YouTubeĀ channel
- Support my work -Ā https://www.buymeacoffee.com/automationbro
- FollowĀ @automationbroĀ on Twitter