Automating API Testing with CI/CD

Tutorial 4 of 5

Automating API Testing with CI/CD

1. Introduction

Goal

The main goal of this tutorial is to automate API testing within a CI/CD (Continuous Integration/Continuous Delivery) pipeline.

Learning Outcomes

By the end of this tutorial, you should be able to:

  • Write test scripts for API testing
  • Configure a CI/CD tool to automatically run tests
  • Understand how automation improves the software development process

Prerequisites

  • Basic knowledge of APIs
  • Familiarity with a programming language, preferably JavaScript
  • Basic understanding of CI/CD

2. Step-by-Step Guide

Understanding API Testing

API testing involves sending requests to the API and evaluating the response. It's important to test APIs to ensure they're performing as expected, returning the correct data, and handling errors properly.

CI/CD and API Testing

In a CI/CD pipeline, code changes are regularly merged and tested. By automating API testing, we can ensure our APIs are working correctly with every code change.

Configuring the CI/CD Tool

We'll use Jenkins as our CI/CD tool. After installing Jenkins, we'll create a new job, select "Pipeline", and define our pipeline. We'll specify that our pipeline should pull the latest code from our repository, then run our API tests.

Writing API Tests

We'll use the Mocha framework to write our API tests in JavaScript. Mocha provides functions to define test suites and test cases, and makes it easy to write asynchronous tests - perfect for API testing.

3. Code Examples

Example 1: Writing an API Test

Here's a simple test for a "GET" request:

// We use the 'chai' library to make assertions
const chai = require('chai');
const chaiHttp = require('chai-http');
chai.use(chaiHttp);
const expect = chai.expect;

// The URL of our API
const url = 'https://my-api.com';

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

Example 2: Configuring Jenkins

In Jenkins, we'll specify our pipeline script:

pipeline {
  agent any

  stages {
    stage('Pull latest code') {
      steps {
        git 'https://my-repo.com'
      }
    }

    stage('Run tests') {
      steps {
        sh 'npm test'
      }
    }
  }
}

4. Summary

We've learned how to write API tests and automate them with a CI/CD pipeline. This can greatly improve the reliability of our software and speed up the development process.

5. Practice Exercises

  1. Write a test for a "POST" request
  2. Write a test that checks the contents of the API response
  3. Configure Jenkins to send a notification if a test fails

Remember, practice is key to mastering these concepts. Happy coding!