DEV Community

Cover image for Writing your first API Test using JavaScript
Dilpreet Johal
Dilpreet Johal

Posted on • Edited on • Originally published at sdetunicorns.com

Writing your first API Test using JavaScript

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...

βš™οΈ Dependencies:

First off, we'll need to get the following dependencies installed to set up our base framework -

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 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();
    });
  });
});

Enter fullscreen mode Exit fullscreen mode

πŸƒβ€β™‚οΈ 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.

Alt Text

There you go, we just created our first API test and it ran successfully πŸ™Œ.

Time to celebrate -
Celebration Gif


Check out this video to see a detailed explanation on how to write your first API test:

You can also clone the GitHub repo to access this code


To learn more about API testing, check out my free tutorial series here -

https://www.youtube.com/watch?v=ZSVw3TyZur4&list=PL6AdzyjjD5HDR2kNRU2dA1C8ydXRAaaBV&ab_channel=AutomationBro


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/dilpreetjohal
Follow sdetunicorns on Twitter


Enjoyed this read? Discover more insightful articles on software testing and development on my blog. 🌐

Top comments (0)