Conducting unit tests on APIs

Tutorial 2 of 5

1. Introduction

In this tutorial, we will be discussing how to conduct unit tests on APIs (Application Programming Interfaces). Unit testing is a software testing method where individual units or components of the software are tested to ensure that they function correctly. In the case of APIs, these 'units' refer to the individual endpoints.

By the end of this tutorial, you will be able to:
- Understand the importance and use of unit testing in APIs
- Write unit tests for your API endpoints
- Use a testing framework for your unit tests

Prerequisites:
- Basic knowledge of APIs
- Familiarity with a programming language (in this tutorial, we will be using JavaScript)
- Node.js and npm installed on your computer
- Basic understanding of Express.js and Mocha (our chosen testing library)

2. Step-by-Step Guide

2.1 Setting up the Testing Environment

First, we need to set up our testing environment. We will use Mocha as our testing library and Chai as our assertion library. Install them using npm:

npm install mocha chai --save-dev

2.2 Writing the Tests

In Mocha, tests are grouped by describe blocks. Inside these blocks, we use it functions to define our tests.

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

describe('Example API', () => {
  it('should work', () => {
    expect(true).to.be.true;
  });
});

In this example, we're testing that true is indeed true. It's a simple test to get us started.

2.3 Testing API Endpoints

Now, let's test an actual API endpoint. We will use chai-http to help us make HTTP requests in our tests.

npm install chai-http --save-dev

Let's say we have an API endpoint, GET /users, which should return a list of users.

const chai = require('chai');
const chaiHttp = require('chai-http');
const app = require('../app'); // import your Express app
chai.use(chaiHttp);
const expect = chai.expect;

describe('GET /users', () => {
  it('should return all users', (done) => {
    chai.request(app)
      .get('/users')
      .end((err, res) => {
        expect(res).to.have.status(200);
        expect(res.body).to.be.an('array');
        done();
      });
  });
});

3. Code Examples

3.1 Testing POST Requests

Let's now test a POST /users endpoint, which should create a new user.

describe('POST /users', () => {
  it('should create a new user', (done) => {
    const newUser = {name: 'John Doe', email: 'john@example.com'};
    chai.request(app)
      .post('/users')
      .send(newUser)
      .end((err, res) => {
        expect(res).to.have.status(201);
        expect(res.body).to.be.an('object');
        expect(res.body.name).to.equal(newUser.name);
        expect(res.body.email).to.equal(newUser.email);
        done();
      });
  });
});

3.2 Testing Error Responses

It's also important to test how your API responds to errors. Here's how you can test a GET /users/:id endpoint when the user does not exist.

describe('GET /users/:id', () => {
  it('should return 404 for non-existent user', (done) => {
    const id = 'non-existent-id';
    chai.request(app)
      .get(`/users/${id}`)
      .end((err, res) => {
        expect(res).to.have.status(404);
        done();
      });
  });
});

4. Summary

We've covered how to set up a testing environment, write tests for API endpoints, and how to test different types of responses. The next step would be to explore more complex tests, such as those involving authentication or database operations.

Additional resources:
- Mocha documentation
- Chai documentation
- Express.js testing guide

5. Practice Exercises

  1. Write a test for a DELETE /users/:id endpoint, which should delete a user.
  2. Write a test for a PUT /users/:id endpoint, which should update a user's details.
  3. Write a test for a GET /users/:id/posts endpoint, which should return all posts from a specific user.

The solutions for these exercises are left as an exercise for the reader to promote further practice and understanding.