How to write unit tests for Ajax requests using Mocha

Unit testing is an essential practice in software development to ensure the reliability and stability of our code. When testing Ajax requests, we can rely on Mocha, a popular JavaScript testing framework, which provides a user-friendly and flexible environment for testing code.

Prerequisites

Before proceeding, ensure that you have the following prerequisites installed:

  • Npm or yarn

  • Node.js

  • Axios (or alternate Ajax library)

Step 1: Setting up the environment

Before we start writing our tests, we need to install Mocha and Chai, which are essential dependencies for our testing environment. Open your terminal or command prompt and navigate to your project’s root directory. Then, run the following commands:

//Using npm
npm install --save-dev mocha
npm install --save-dev chai
//OR
//Using yarn
yarn add --dev mocha
yarn add --dev chai

The commands above will install Mocha and Chai as dev dependencies in our project, allowing us to use them for testing.

Note: Chai is an assertion library that offers various styles and methods for making assertions in our tests.

After installation, let’s create a new folder for our tests, typically named test. Inside this folder, let’s create a new JavaScript file, for example, ajax.test.js.

Step 2: Importing dependencies

After setting up the environment, import the required dependencies in your test file, axios for making Ajax requests and the assert module for assertions.

// Import the necessary modules
const axios = require('axios');
const assert = require('assert');

Step 3: Writing a test case

Now, let’s start writing a simple test case to ensure our Ajax request is functioning correctly. In this example, we will use a free JSONPlaceholder API to send requests using Ajax. You will be required to replace it with the request that you want to test.

// Describe the test suite
describe('Ajax Request', () => {
// Describe the specific test case
it('should return a list of users', async () => {
// Make the Ajax request
const response = await axios.get('https://jsonplaceholder.typicode.com/users');
// Assert the response status code
assert.strictEqual(response.status, 200);
// Assert the response contains data
assert.strictEqual(Array.isArray(response.data), true);
assert.strictEqual(response.data.length > 0, true);
});
});

In the code above, we define a test suite using the describe function provided by Mocha. Inside the suite, we define a specific test case using the it function. Within the test case, we make the Ajax request using Axios and await the response. Finally, we use the assert module to check if the response status code is 200 and if the response contains an array of data.

Step 4: Additional test cases

To write more comprehensive tests, we can expand our test suite with additional test cases. We should consider scenarios such as testing for error responses, testing specific data returned by the Ajax request, or testing different API endpoints. Below is an example of a test case that verifies the presence of a specific property in the response data:

it('should contain a specific property in the response', async () => {
const response = await axios.get('https://jsonplaceholder.typicode.com/users/1');
const responseData = response.data;
// Assert the presence of a specific property
assert.strictEqual(responseData.hasOwnProperty('name'), true);
});

Ajax requests are asynchronous, and Mocha provides ways to handle this in our tests. We can either use the done callback or leverage the async/await syntax, as shown in the example. By using await with promises, we can ensure that our assertions are executed after the request is complete.

Step 5: Running the test

To execute the test, we can navigate to the root of our project in the terminal and run the command mocha from npm package followed by the path to our test file.

$ npx mocha test/ajax.test.js

If everything is set up correctly, we should see Mocha running our test case. If the test passes, we will see a success message. Otherwise, Mocha will display an error message indicating the failed assertion.

If test files are placed in folder named test, then you can also run tests by just npx mocha.

Following are the example test cases, that are testing JSONPlaceholder API.

{
  "name": "mocha-test",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1"
  },
  "keywords": [],
  "author": "",
  "license": "ISC",
  "devDependencies": {
    "axios": "^1.4.0",
    "chai": "^4.3.7",
    "mocha": "^10.2.0"
  }
}

Conclusion

Writing unit tests for Ajax requests using Mocha allows us to verify the behavior and correctness of our code. By incorporating unit tests into our development workflow, we can detect and fix issues early, leading to a more robust and maintainable code.

Free Resources

Copyright ©2026 Educative, Inc. All rights reserved