Writing Unit Tests for REST APIs

Tutorial 2 of 5

Writing Unit Tests for REST APIs

1. Introduction

1.1 Goal

This tutorial aims to guide you through the process of writing unit tests for REST APIs. Unit tests help ensure that individual components of a software system work as expected. They are crucial for maintaining code integrity, especially in large projects.

1.2 Learning Outcomes

By the end of this tutorial, you will be able to:
- Understand the importance of unit tests for REST APIs
- Write basic unit tests for a REST API
- Understand how to isolate and test individual components
- Develop a habit of writing more reliable, robust code

1.3 Prerequisites

For this tutorial, you should have a basic understanding of:
- Programming with JavaScript
- REST APIs
- Node.js and Express.js

2. Step-by-Step Guide

2.1 The Importance of Unit Tests

Unit tests are designed to test individual parts of your code to ensure that they function correctly. For REST APIs, these tests are particularly crucial as they help ensure the API behaves as expected, returning the correct data when it is queried, and handling errors properly.

2.2 Setting up Your Testing Environment

We'll be using Mocha and Chai for our tests. Mocha is a popular JavaScript testing framework, and Chai is an assertion library that works well with Mocha. You can install these with npm:

npm install --save-dev mocha chai

2.3 Writing a Basic Unit Test

A basic unit test using Mocha and Chai might look like this:

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

describe('Basic Mocha String Test', function () {
 it('should return number of charachters in a string', function () {
    expect('Hello').to.have.lengthOf(5);
 });
});

Here, we're testing that the string "Hello" has a length of 5.

3. Code Examples

3.1 Testing a GET request

Let's assume we have a GET endpoint at /api/users that returns a list of users. Here's how we could test it:

const expect = require('chai').expect;
const request = require('supertest');
const app = require('../app');

describe('GET /api/users', function() {
  it('should return a list of users', function(done) {
    request(app)
      .get('/api/users')
      .end(function(err, res) {
        expect(res.statusCode).to.equal(200);
        expect(res.body).to.be.an('array');
        done();
      });
  });
});

This test sends a GET request to our /api/users endpoint and checks that the response has a status code of 200 and is an array.

3.2 Testing a POST request

Now, let's test a POST request that creates a new user:

const expect = require('chai').expect;
const request = require('supertest');
const app = require('../app');

describe('POST /api/users', function() {
  it('should create a new user and return it', function(done) {
    const newUser = {
      name: 'John Doe',
      email: 'john@doe.com'
    };

    request(app)
      .post('/api/users')
      .send(newUser)
      .end(function(err, res) {
        expect(res.statusCode).to.equal(201);
        expect(res.body.name).to.equal(newUser.name);
        expect(res.body.email).to.equal(newUser.email);
        done();
      });
  });
});

4. Summary

In this tutorial, we've learned the importance of unit testing and how to write basic tests for REST API endpoints using Mocha and Chai. We've covered how to test GET and POST requests, and how to ensure our tests are isolated and reliable.

5. Practice Exercises

Now that you've learned the basics, it's time to practice!

  1. Write a test for a DELETE endpoint that removes a user from the list.
  2. Write a test for a PUT endpoint that updates a user's details.
  3. Write a test for a GET endpoint that returns a specific user based on ID.

Remember to follow the same pattern we've used in our examples: make a request to the endpoint and then check that the response is as expected. Good luck!