Trusted answers to developer questions

How to Test an API in Node.JS

Get Started With Data Science

Learn the fundamentals of Data Science with this free course. Future-proof your career by adding Data Science skills to your toolkit — or prepare to land a job in AI, Machine Learning, or Data Analysis.

APIs are sets of functions that allow communication with or utilization of other services.

There are many ways to test an API. In Node.js, a useful testing tool is Mocha, a library for testing.

To install Mocha globally, use the following command.

npm i --global mocha

Installing dependencies for API testing

There are multiple ways to test APIs. A common test for APIs is the POST request test, which tests communication from a program with the API server.

SuperTest might be a useful way to implement this library as it simplifies HTTP POST requests for testing purposes.

To create a development dependency on SuperTest, run the following script.

npm install supertest --save-dev

expect is another library that is used to assert the expected behavior of the JavaScript code.

To create a development dependency on expect, run the following script.

npm install expect --save-dev

 After adding the required dependencies test script should be included in the package.json file scripts section.

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

To run the test, use the following script.

npm test

Coding example

Now, the test program needs to be written. The test should be stored in a directory called “test” which is inside the root folder. For this example, we will assume that our API handles Educative Answers.

Click the "Run" button to execute the program.

const request = require('supertest');
const {expect} = require('expect');

const app = require('../app');

describe('Testing POSTS/answers endpoint', () => {
  it('respond with valid HTTP status code and description and message', async () => { // add `async` keyword here
    const response = await request(app)
      .post('/answers')
      .send({ title: 'How to write a answer', body: 'Access the Educative answer tutorial' });

    expect(response.status).toBe(200);
    expect(response.body.status).toBe('success');
    expect(response.body.message).toBe('Answer Saved Successfully.');
  });
});
Coding example

Here, describe() and it() describe what is being tested and what is expected from the test as a response. In their second argument, a lambda function is defined. In general, it() functions are inside describe() functions, but the actual tests are taking place in the it() function.

The POST request is made by the SuperTest library on line 8. The responses are compared to expected responses between lines 12 and 14. These responses may be different for other APIs and largely depend on how the API is designed to respond.

RELATED TAGS

api
javascript
node.js
mocha
testing
Copyright ©2024 Educative, Inc. All rights reserved
Did you find this helpful?