Scroll to top

Getting started with API Test Automation using JavaScript


DigitalOnUs - December 25, 2020 - 0 comments

What is API Testing?

API testing involves testing application programming interfaces (APIs) and therefore, focuses on testing the business logic or the service layer of the application without interacting with the user interface of the application. API testing is done as part of integration testing to ensure APIs are functional, reliable, performant and secure.

How to Validate an API Response

Let’s say you are testing this ‘users’ API -> https://jsonplaceholder.typicode.com/users.

You’ll see a response similar to this on a GET call:

{
 id:1,
 name:"Leanne Graham",
 username:"Bret",
 email:"Sincere@qpril.biz"
 ...
},

You can validate the following scenarios:

  • Ensure the value of the required properties are not empty such as username or email
  • Verify email is in the right format
  • Validate the name field does not exceed ‘x’ number of characters

Similarly, you can create and verify many such scenarios per your business requirements. 

Different Types of API Testing:

There are various kinds of API testing that you can perform, including:

  • Functionality Testing: Functionality testing allows you to test the business logic of the application. For example, if a user makes an API call to the signup route, the functional test would validate that a new user is created and the necessary response with the user details gets returned from the server.
  • Load Testing: Load testing allows you to ensure the APIs can handle the necessary load on the application. For example, if a thousand users are hitting the API at the same time, the load test would validate that the APIs are able to handle the load, and not break or take an unreasonable amount of time to return the response.
  • Security Testing: Security testing allows you to ensure the APIs are secure and follow the necessary security guidelines. For example, a security test would validate that a user is not able to access the application data without going through the proper authentication process first. Another common example is ensuring that users cannot access the personal data of another user.
  • Negative Testing: Negative testing allows you to ensure APIs are doing what they are specifically built to do, and are able to handle responding to invalid input appropriately. For example, a negative API test would ensure users are not able to enter an invalid email format, or register without entering an email, password, etc. 

Advantages of API Testing:

  • Early application access: In most cases within the software development life cycle, APIs are created first, followed by the creation and integration of the UI with the APIs. This provides early access to the application functionality, allowing us to begin testing the business logic sooner and providing a greater opportunity to identify issues earlier on.
  • Test speed and coverage: Often times, API testing can be performed a lot more quickly than browser testing. Specifically, when you start automating tests, API tests tend to run a lot faster than browser tests as you are skipping the interaction with the UI layer and jumping directly to the API layer. Due to the difference in test execution speed, building thorough API test coverage is usually preferred over building front-end tests since they can cover a lot more ground, more quickly.
  • Language independent: API testing is programming language independent since the data is exchanged via JSON or XML. Therefore, you can use pretty much any programming language for test automation that can handle JSON or XML data.
  • Easier to maintain: API tests are comparatively easier to maintain than front-end tests as business logic tends to be more stable than the UI, making API tests a lot less flaky and more reliable in comparison to front-end tests.

Now that we have covered the basics of API testing, let’s take a look at how we can do API Automation Testing using JavaScript. 

Dependencies

You will need to install Node.js in your machine before installing any of the dependencies below. The dependencies below will allow us to write API tests using JavaScript.

  • SuperTest: SuperTest is built on top of SuperAgent, which is a HTTP request library. SuperTest adds an abstraction on top of SuperAgent to easily test API requests.
  • Mocha: Mocha is a popular JavaScript test framework that runs on Node.js.
  • Chai: Chai is an assertion library for browser and node.js that can be paired with any JavaScript framework.

Note: These libraries/frameworks can be replaced with an equivalent library/framework. However, for the purpose of this post we will be using the ones mentioned above. 

Setup Your Project:

Before installing dependencies, initialize a new NPM project –

mkdir api-test-js && cd api-test-js
npm init -y

Install Necessary Dependencies:

npm install supertest mocha chai --save-dev

This should install SuperTest, Mocha and Chai in your project. 

Setup Your Tests:

Create a new test.js file in your root folder to begin writing your API tests. For this tutorial, we will be using https://jsonplaceholder.typicode.com/ website to test the APIs. JSONPlaceholder provides fake REST APIs for testing and prototyping and works perfectly for our example here.

Now, let’s start with importing SuperTest in our test file and passing in the JSONplaceholder url for application testing –

const request = require('supertest')('https://jsonplaceholder.typicode.com');

Writing API Tests:

GET Method:

We will begin with writing test for GET method which will allow us to fetch data from the server.

  • Create a new describe block to group our tests and name it ‘Users API’ as we will be working with the User’s API
  • Within the describe block, we’ll create an it block to give a name to our test. Inside the it block we will begin to write our test

This is how a basic test would look –

describe('Users API', () => {
it(''GET /users', () => {
// Make a GET request to the users route 
return request.get('/users').expect(200);
});
});

We are making a GET request using request.get and passing the resource in the parameter (/users) and making sure that we get a 200 OK response back from the server.
Note: we are using return as we get a promise back when we make a request using SuperTest and we can return the promise to fulfill it. This avoids adding a ‘done’ callback in the test. 

Chai Assertion:

We can now expand our test to assert for more than just a 200 OK response by using Chai assertions. Let’s take a look at how we can do this.

const assert = require('chai').assert;

First, we’ll import the Chai library. Here, I am using the assert interface from the Chai library.

it('GET /users', () =>{
  // Make a GET request to the users route 
  return request
  .get('/users')
  .expect(200)
  .then((res) => {
   // assert data bieng return to not be empty
   assert.isNotEmpty(res.body);
 });
});

For the assertion, I am verifying that the response body should not be empty i.e. we should always receive the users’ data back when making a call to the /users API. 

Run Test:

To run tests, head over to the package.json  file and update the test script to use the mocha command –

"scripts":{
   "test":"mocha"
 },

Now, you can run test by doing npm test in your root folder.

There you go, we just wrote and successfully ran our first API test using SuperTest, Mocha and Chai. 

POST Method:

Let’s also take a look at how we can send data to the server to create a new user. To create a new resource, we usually use the POST method which allows us to send payload data to the server.

it('POST /users', () => {
   const data = {
       name:'Test user',
       email:'test_user@digitalonus.com',
    };
   return request
    .post ('/users')
    .send(data) // send payload data
    .then((res) => {
      assert.hasAnyKeys(res.body, 'id');
      assert.equal(res.body.name, data.name);
      assert.equal(res.body.email, data.email);

      });
});

In the example above,

  • we created a data object to store test name and test email and passed that to the request using the .send
  • In our assertions we are verifying whether the newly created user has the same name and email that we passed in the request.
  • Also, we are checking whether a new ID is created for the user.

Conclusion:

So that was a short introduction on the basics of API testing and getting started with API test automation using JavaScript.  All of this code will be available on GitHub for you to access along with some other tests for PUT and DELETE route – https://github.com/djohal/api-tests-js-example. I would highly recommend to try these out on your own and create some more API tests to get familiar with these libraries and framework.

Related posts