CodeWithMMAK
API AutomationIntermediate

API Automation with Axios, Mocha, and Chai: A Professional Guide

Learn how to build a robust API automation framework using Axios for HTTP requests, Mocha as the test runner, and Chai for assertions. Master modern JavaScript testing techniques.

CodeWithMMAK
December 13, 2022
12 min

Introduction

🎯 Quick Answer

API Automation with Axios involves using the Axios library to send HTTP requests (GET, POST, PUT, DELETE) to an API and then validating the responses using a test runner like Mocha and an assertion library like Chai. This combination is highly popular in the JavaScript ecosystem due to its promise-based nature, ease of use, and extensive community support. It allows for clean, asynchronous test code that is easy to maintain and integrate into CI/CD pipelines.

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.

📖 Key Definitions

Axios

A promise-based HTTP client for the browser and Node.js. It handles request and response transformations automatically and supports interceptors.

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 (names, addresses, emails, etc.).

Why Axios for API Testing?

Axios is a promise-based HTTP client for the browser and node.js. It is easy to use and provides a clean API for making requests. Key benefits include:

  • Automatic JSON Transformation: No need to manually parse JSON responses.
  • Interceptors: Intercept requests or responses before they are handled by then or catch.
  • Concurrency: Easily handle multiple concurrent requests using axios.all.
  • Wide Support: Works seamlessly in both the browser and Node.js environments.

🚀 Step-by-Step Implementation

1

Initialize the Project

Create a new directory and run npm init -y to create your package.json file.

2

Install Dependencies

Install the core libraries:

Code Snippet
npm install axios mocha chai @faker-js/faker --save-dev
3

Create Your First Test File

Create a test folder and a file named user.test.js.

4

Write a GET Test

Use axios.get to fetch data and expect from Chai to validate the status and payload.

5

Write a POST Test with Faker

Use faker to generate dynamic user data and axios.post to create a new resource.

6

Run the Tests

Add a test script to your package.json: "test": "mocha" and run npm test.

Example: Advanced API Test

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

describe('User API Automation', () => {
    const baseUrl = 'https://reqres.in/api';

    it('should fetch user details successfully', async () => {
        const response = await axios.get(`${baseUrl}/users/2`);
        expect(response.status).to.equal(200);
        expect(response.data.data.first_name).to.equal('Janet');
    });

    it('should create a new user with dynamic data', async () => {
        const userData = {
            name: faker.person.fullName(),
            job: faker.person.jobTitle()
        };
        const response = await axios.post(`${baseUrl}/users`, userData);
        expect(response.status).to.equal(201);
        expect(response.data.name).to.equal(userData.name);
    });
});

Common Errors & Best Practices

⚠️ Common Errors & Pitfalls

  • Forgetting 'await'

    Since Axios is promise-based, forgetting await will cause the test to pass before the request completes, leading to false positives.

  • Hardcoding Base URLs

    Scattering the base URL across multiple files makes it difficult to switch between Dev, QA, and Production environments.

  • Ignoring Error Responses

    Not testing negative scenarios (400, 401, 404, 500) to ensure the API handles errors gracefully.

Best Practices

  • Use Axios Interceptors to attach Auth tokens or log request/response details globally.
  • Implement the "Page Object Model" equivalent for APIs by creating "Service" classes for each endpoint.
  • Use environment variables (process.env) to manage sensitive data and environment-specific URLs.
  • Always validate the response schema, not just the status code, to catch breaking changes in the data structure.

Frequently Asked Questions

Can I use Axios with Jest?

Yes, Axios works perfectly with Jest. The syntax is very similar to Mocha/Chai.

How do I handle authentication?

You can pass headers in the Axios config object: axios.get(url, { headers: { Authorization: 'Bearer token' } }).

How do I upload files with Axios?

Use the FormData API to append your file and send it via a POST request with the appropriate Content-Type header.

Conclusion

Building an API automation framework with Axios, Mocha, and Chai provides a powerful, flexible, and developer-friendly solution. By following structured patterns and leveraging libraries like FakerJS, you can create a comprehensive test suite that ensures your APIs remain reliable and performant.

📝 Summary & Key Takeaways

API automation with Axios, Mocha, and Chai is a robust approach for testing modern web services. Axios provides a clean, promise-based HTTP client, while Mocha and Chai handle test execution and assertions. Key techniques include using FakerJS for dynamic test data, implementing interceptors for global configurations, and ensuring thorough validation of both positive and negative scenarios. This framework is highly scalable and easily integrates into automated CI/CD pipelines for continuous quality assurance.

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!