CodeWithMMAK
API AutomationIntermediate

API Automation with Axios, Mocha, and Chai: The Ultimate Step-by-Step Guide

A comprehensive, from-scratch guide to building a professional API automation framework using Axios, Mocha, and Chai. Master CRUD operations, data generation, and reporting.

CodeWithMMAK
June 21, 2022
15 min

Introduction

🎯 Quick Answer

API Automation with Axios, Mocha, and Chai is a powerful stack for testing RESTful services in JavaScript. Axios handles the HTTP requests (GET, POST, PUT, PATCH, DELETE), Mocha provides the test execution structure, and Chai offers expressive assertions. To build this from scratch, you initialize a Node.js project, install the dependencies, and write asynchronous tests that validate response status codes, headers, and body data.

We will be using Axios for API automation, Mocha as a test automation framework and Chai for assertion. As JavaScript is popular these days so we will be using JavaScript for writing our tests. At the end of this tutorial, you will be having knowledge of setting up the framework from scratch.

📖 Key Definitions

Axios

A promise-based HTTP client for Node.js and the browser. It is isomorphic, meaning it can run in both environments with the same codebase.

Mocha

A feature-rich JavaScript test framework running on Node.js, making asynchronous testing simple and fun.

Chai

A BDD/TDD assertion library for Node.js and the browser that can be paired with any JavaScript testing framework.

FakerJS

A library for generating massive amounts of realistic fake data for testing purposes.

Mochawesome

A custom reporter for use with the Mocha testing framework that generates beautiful HTML/JSON reports.

Prerequisites

Before we begin, ensure you have the following installed:

  1. Install Node.JS
  2. Install Visual Studio Code (or any text editor of your choice)

🚀 Step-by-Step Implementation

1

Initialize the Project

Open your terminal and run:

Code Snippet
mkdir api-testing-axios-mocha-chai-javascript
cd api-testing-axios-mocha-chai-javascript
npm init -y
2

Install Dependencies

Install the core testing libraries and utilities:

Code Snippet
npm install --save axios mocha chai mochawesome rimraf @faker-js/faker properties-reader
3

Configure .gitignore

Create a .gitignore file to exclude node_modules/, test-results/, and other temporary files from version control.

4

Create Test Directory

Organize your tests by creating a dedicated folder:

Code Snippet
mkdir api-tests
5

Write Your First Test

Create get_request.js in the api-tests folder and use axios.get to validate a public API like reqres.in.

6

Execute and Report

Run your tests using npx mocha and generate an HTML report with the --reporter mochawesome flag.

Core CRUD Operations with Axios

1. GET Request

Code Snippet
const axios = require("axios");
const { expect } = require("chai");

describe("GET API Request Tests", async () => {
    it("should be able get user list", async () => {
        const res = await axios.get('https://reqres.in/api/users?page=2');
        expect(res.data.page).equal(2);
        expect(res.data.per_page).equal(6);
    });
});

2. POST Request with FakerJS

Code Snippet
const axios = require("axios");
const { expect } = require("chai");
const { faker } = require("@faker-js/faker");

describe("POST API Request Tests", async () => {
    it("should be able post a user", async () => {
        const randomName = faker.person.fullName();
        const randomJobTitle = faker.person.jobTitle();
        const res = await axios.post('https://reqres.in/api/users', {
            name: randomName,
            job: randomJobTitle
        });
        expect(res.data.name).equal(randomName);
        expect(res.data.job).equal(randomJobTitle);
    });
});

Advanced Techniques

Reading from Property Files

Usually, properties files are used to store environment information. Create config/env.properties:

Code Snippet
baseUrl=https://reqres.in/api

Then read it in your test:

Code Snippet
const PropertiesReader = require('properties-reader');
const properties = PropertiesReader('config/env.properties');
const baseUrl = properties.get("baseUrl");

Writing Data to JSON

Sometimes you need to persist data (like a token or ID) for subsequent tests:

Code Snippet
const fs = require("fs");
const data = { id: res.data.id };
fs.writeFileSync("./response-data/data.json", JSON.stringify(data));

Common Errors & Best Practices

⚠️ Common Errors & Pitfalls

  • Unhandled Promise Rejections

    Not using async/await correctly, which leads to tests finishing before the API response is received.

  • Timeout Failures

    Default Mocha timeout is 2000ms. Slow APIs will cause tests to fail. Use --timeout=30000 in your run command.

  • Missing Schema Validation

    Only checking the status code but ignoring the fact that the API might have returned an empty or malformed body.

Best Practices

  • Use it.only or describe.only to run specific tests during development.
  • Implement Axios Interceptors for global logging and authentication header management.
  • Keep your test data separate from your test logic using JSON files or FakerJS.
  • Always clean up your test results directory before a new run using rimraf.

Frequently Asked Questions

How do I handle SSL certificate issues?

In Node.js, you can set process.env.NODE_TLS_REJECT_UNAUTHORIZED = '0'; for local testing, though this is not recommended for production.

Can I run tests in parallel?

Yes, Mocha supports parallel execution using the --parallel flag, but ensure your tests are independent and don't share state.

How do I integrate this with Jenkins?

Since it's a standard Node.js project, you can run npm install and npm test as shell commands in your Jenkins pipeline.

Conclusion

Building an API automation framework from scratch gives you full control over your testing strategy. By combining Axios, Mocha, and Chai, you create a professional-grade toolset that is both powerful and easy to maintain.

📝 Summary & Key Takeaways

This guide provides a comprehensive roadmap for building an API automation framework using Axios, Mocha, and Chai. It covers project initialization, dependency management, and the implementation of all major CRUD operations. Advanced topics like property file reading, JSON data persistence, and HTML reporting with Mochawesome are also explored. By following these structured steps and best practices, teams can ensure high-quality, reliable, and automated validation of their web services.

Share it with your network and help others learn too!

Follow me on social media for more developer tips, tricks, and tutorials. Let's connect and build something great together!