JavaScript

What Is Mocha? A Complete Beginner’s Guide to JavaScript Testing

Testing is an important part of JavaScript development. It helps you check whether your code works as expected. It can also help you find bugs before users…

D
DevByteTechnical Author
Published
14 min read2 views
Mocha JavaScript Testing Framework beginner guide

When building JavaScript applications, writing code is only one part of the development process. You also need to ensure that your code behaves as expected, handles errors correctly, and continues working when you make changes.

This is where automated testing becomes important.

Imagine you're developing a Node.js application with user authentication, payment processing, and database operations. A small change to one function could accidentally break another feature. Testing helps you identify these problems before they reach production.

Mocha is a JavaScript testing framework that helps developers organize, execute, and report automated tests. It supports testing in Node.js and browsers and makes asynchronous testing straightforward.

In this guide, you'll learn what Mocha is, how it works, how to install it, and how to write practical JavaScript tests using real code examples.

What Is Mocha in JavaScript?

Mocha is an open-source JavaScript testing framework used to run automated tests. It provides functions for organizing test suites, defining individual test cases, executing asynchronous operations, and reporting results.

Mocha works particularly well with Node.js applications, APIs, and JavaScript libraries.

For example, suppose you have a function that adds two numbers:

function add(a, b) {
  return a + b;
}

console.log(add(5, 3));

The function should return 8. Instead of checking its output manually every time, you can write an automated test that verifies the result.

Mocha runs that test and reports whether it passes or fails.

One important distinction is that Mocha is a test runner, not an assertion library. It organizes and executes tests, while assertion libraries such as Node.js's built-in assert module or Chai help you verify expected results.

You can learn more from the official Mocha documentation.

Why Is Mocha Used?

Developers use Mocha to automate testing and improve the reliability of their applications.

Here are some common reasons to use it.

1. Automated Testing

You can write tests once and execute them whenever you change your code.

This reduces repetitive manual testing and helps identify unexpected behavior.

2. Asynchronous Testing

Modern JavaScript applications frequently use promises, async/await, database queries, and API requests.

Mocha supports testing asynchronous functions, making it useful for Node.js applications.

3. Organized Test Suites

Mocha provides functions such as describe() and it() to organize tests into readable groups.

This makes large test suites easier to understand and maintain.

4. Flexible Assertions

You can use different assertion libraries with Mocha, including Node.js's built-in assert module and Chai.

This flexibility lets you choose an assertion style that suits your project.

5. Test Hooks

Mocha provides hooks such as before(), after(), beforeEach(), and afterEach().

These help you prepare test data, establish database connections, and clean up resources around your tests.

6. Detailed Test Reports

Mocha reports passing and failing tests and helps you identify which test cases need attention.

Its reporting options are useful when running tests locally or in continuous integration pipelines.

How Does Mocha Work?

Mocha follows a straightforward testing workflow.

  1. You write application code.

  2. You create test files describing expected behavior.

  3. Mocha discovers and loads the test files.

  4. Mocha executes the test cases.

  5. Assertions check whether the actual results match the expected results.

  6. Mocha reports which tests passed and which failed.

For example, consider a function that checks whether a user is eligible to register based on their age.

function canRegister(age) {
  return age >= 18;
}

You might expect the following behavior:

  • An age of 20 should return true.

  • An age of 18 should return true.

  • An age of 16 should return false.

You can create separate test cases for these conditions and let Mocha execute them automatically.

Mocha vs. Chai: What's the Difference?

Mocha and Chai are often used together, but they serve different purposes.

Feature

Mocha

Chai

Primary purpose

Runs and organizes tests

Provides assertion methods

Test suites

Provides describe()

Not its primary responsibility

Test cases

Provides it()

Not its primary responsibility

Assertions

Can use external or built-in assertion libraries

Provides expect, should, and assert interfaces

Asynchronous tests

Supports promises and async/await

Helps assert the results

Can be used together

Yes

Yes

For example, Mocha defines the test, while Chai verifies the expected result.

import { expect } from "chai";

describe("Addition", function () {
  it("should add two numbers", function () {
    expect(2 + 3).to.equal(5);
  });
});

Here, describe() and it() come from Mocha's test interface, while expect() and .to.equal() come from Chai.

You can also use Node.js's built-in assertion library instead of Chai.

How to Install Mocha in a Node.js Project

Let's create a simple testing setup from scratch.

Step 1: Check Node.js and npm

Make sure Node.js and npm are installed.

Run these commands in your terminal:

node -v
npm -v

If both commands display version numbers, you can continue.

Version note: Mocha 12 requires Node.js ^20.19.0 or >=22.12.0. If you're using an older Node.js version, check the compatibility requirements for the Mocha version you intend to install.

Step 2: Create a Project

Create a new directory and initialize an npm project.

mkdir mocha-demo
cd mocha-demo
npm init -y

This creates a package.json file to manage your project's dependencies and scripts.

Step 3: Install Mocha

Install Mocha as a development dependency:

npm install --save-dev mocha

Mocha is generally a development dependency because it is used to test your application rather than serve normal production requests.

Step 4: Configure ES Modules

For the examples in this guide, we'll use modern JavaScript import and export syntax.

Add "type": "module" to your package.json.

{
  "name": "mocha-demo",
  "version": "1.0.0",
  "type": "module",
  "scripts": {
    "test": "mocha"
  },
  "devDependencies": {
    "mocha": "^12.0.0"
  }
}

Your actual Mocha dependency version may differ depending on when you install it. Keep the version generated by npm rather than manually replacing it unnecessarily.

The "type": "module" setting allows Node.js to interpret regular .js files as ES modules.

Step 5: Create a Test File

Create a directory named test and add a file called math.test.js.

Your project structure should look like this:

mocha-demo/
├── node_modules/
├── test/
│   └── math.test.js
├── package.json
└── package-lock.json

Add the following code to test/math.test.js:

import assert from "node:assert/strict";

function add(a, b) {
  return a + b;
}

describe("Math Functions", function () {
  it("should add two numbers correctly", function () {
    assert.equal(add(2, 3), 5);
  });

  it("should return a negative result when appropriate", function () {
    assert.equal(add(-5, 2), -3);
  });
});

Here is what each part does:

  • describe() groups related test cases.

  • it() defines an individual test.

  • assert.equal() verifies that the actual result matches the expected value.

  • add() is the function being tested.

Step 6: Run the Tests

Execute the following command:

npm test

You should see output similar to this:

  Math Functions
    ✔ should add two numbers correctly
    ✔ should return a negative result when appropriate

  2 passing

The exact timing and formatting may differ.

Congratulations! You've created and executed your first Mocha tests.

Understanding describe() and it()

Two of the most frequently used functions in Mocha are describe() and it().

Understanding them is essential when writing organized test cases.

The describe() Function

The describe() function groups related tests into a test suite.

For example:

describe("User Authentication", function () {
  // Authentication-related tests
});

You can create separate suites for registration, login, password reset, and other application features.

You can also nest describe() blocks to organize tests into smaller groups.

The it() Function

The it() function defines a specific test case.

For example:

it("should reject an invalid password", function () {
  // Test implementation
});

A good test description explains the expected behavior rather than simply stating that the function should work.

For example, prefer:

it("should return false when the password is empty", function () {
  // Assertions
});

This makes test reports easier to understand.

How to Test JavaScript Functions With Mocha

Let's create a more practical example.

Suppose you're building an application that calculates the total price of products in a shopping cart.

Create a file named cart.js:

export function calculateTotal(prices) {
  return prices.reduce((total, price) => total + price, 0);
}

This function adds all the prices in an array.

Now create test/cart.test.js:

import assert from "node:assert/strict";
import { calculateTotal } from "../cart.js";

describe("calculateTotal()", function () {
  it("should calculate the total price", function () {
    const result = calculateTotal([100, 200, 300]);

    assert.equal(result, 600);
  });

  it("should return zero for an empty cart", function () {
    const result = calculateTotal([]);

    assert.equal(result, 0);
  });

  it("should handle a single product", function () {
    const result = calculateTotal([250]);

    assert.equal(result, 250);
  });
});

Run the tests:

npm test

These test cases verify the function's behavior under different conditions.

This is useful because testing only one normal input may not reveal problems with empty arrays, missing values, or unexpected inputs.

For a production shopping cart, you should also decide how the function should handle invalid prices, negative values, and non-numeric inputs, then write tests for those requirements.

How to Test Asynchronous Functions in Mocha

Asynchronous operations are common in Node.js applications.

Examples include:

  • Fetching data from an API.

  • Querying a database.

  • Reading files.

  • Sending emails.

  • Processing background tasks.

Mocha supports asynchronous tests through promises, async/await, and callback-based completion.

Example: Testing With async/await

Create a file named user-service.js:

export async function getUserName() {
  return new Promise((resolve) => {
    setTimeout(() => {
      resolve("Manjeet");
    }, 100);
  });
}

Now create test/user-service.test.js:

import assert from "node:assert/strict";
import { getUserName } from "../user-service.js";

describe("User Service", function () {
  it("should return the user's name", async function () {
    const result = await getUserName();

    assert.equal(result, "Manjeet");
  });
});

Run the tests:

npm test

Mocha waits for the promise returned by the asynchronous test to settle.

If the promise resolves and the assertion passes, the test succeeds. If the promise rejects or an assertion fails, Mocha reports a failure.

Important: Always return or await asynchronous work in a test. Otherwise, Mocha might finish the test before the operation completes.

What Are Mocha Hooks?

Hooks are functions that run at specific points during test execution.

They are especially useful when your tests require setup and cleanup.

Mocha provides four common hooks:

Hook

When It Runs

before()

Once before the tests in its suite

after()

Once after the tests in its suite

beforeEach()

Before each test in its suite

afterEach()

After each test in its suite

Example of Mocha Hooks

import assert from "node:assert/strict";

describe("User Tests", function () {
  let user;

  beforeEach(function () {
    user = {
      name: "Manjeet",
      role: "developer"
    };
  });

  afterEach(function () {
    user = null;
  });

  it("should contain the correct user name", function () {
    assert.equal(user.name, "Manjeet");
  });

  it("should contain the correct user role", function () {
    assert.equal(user.role, "developer");
  });
});

In this example, beforeEach() creates a fresh user object before each test, while afterEach() clears the reference after the test.

Hooks are useful when testing APIs, database models, authentication systems, and other features that require repeatable setup.

For database integration tests, you might use hooks to connect to a test database and remove test records after execution.

How to Configure Mocha

As your application grows, you may want to customize how Mocha discovers and executes tests.

Mocha supports configuration files, including .mocharc.json, .mocharc.yaml, and JavaScript configuration files.

For an ES module project, create .mocharc.json in your project root:

{
  "spec": "test/**/*.test.js",
  "timeout": 5000,
  "reporter": "spec"
}

Here's what these options mean:

  • spec: Tells Mocha which test files to execute.

  • timeout: Sets the default time limit for an individual test.

  • reporter: Selects the format used to display test results.

The test/**/*.test.js pattern includes matching test files in the test directory and its subdirectories.

The five-second timeout is an example, not a universal recommendation. Set timeouts according to your tests' expected behavior.

You can now run:

npx mocha

Mocha automatically loads the configuration file.

How to Test a Node.js API With Mocha

Mocha is also useful for testing Express.js APIs.

For HTTP endpoint tests, developers commonly combine Mocha with an assertion library and Supertest.

Consider a simple Express application.

Create app.js:

import express from "express";

const app = express();

app.get("/api/health", (req, res) => {
  res.status(200).json({
    status: "ok"
  });
});

export default app;

Install the dependencies:

npm install express
npm install --save-dev supertest

Create test/api.test.js:

import request from "supertest";
import assert from "node:assert/strict";
import app from "../app.js";

describe("GET /api/health", function () {
  it("should return a successful health response", async function () {
    const response = await request(app)
      .get("/api/health");

    assert.equal(response.status, 200);

    assert.deepEqual(response.body, {
      status: "ok"
    });
  });
});

Run the tests:

npm test

Supertest sends a request to the Express application and returns the response for assertions.

Notice that the application is exported without calling app.listen(). This allows Supertest to exercise the app without requiring a separate network port.

For a real application, you can test authentication, request validation, error responses, and other API behavior in a dedicated test environment.

Mocha Best Practices

Writing tests is useful, but writing maintainable tests is just as important.

Follow these practices when using Mocha in your projects.

1. Use Descriptive Test Names

Test descriptions should explain the expected behavior.

Instead of:

it("should work", function () {
  // Test implementation
});

Prefer:

it("should return an error when the email is invalid", function () {
  // Test implementation
});

Descriptive names make failing test reports easier to understand.

2. Test Normal and Edge Cases

Don't test only the expected input.

For example, if you are testing a registration function, consider:

  • Valid registration details.

  • Missing required fields.

  • Invalid email addresses.

  • Duplicate email addresses.

  • Passwords that fail validation.

Choose test cases based on the application's actual requirements.

3. Keep Tests Independent

One test should not depend on another test having executed successfully.

Use setup hooks and isolated test data where necessary.

This makes your tests more reliable and easier to run individually.

4. Test Asynchronous Operations Correctly

Use async/await or return the relevant promise.

Avoid starting asynchronous work without waiting for its completion.

5. Use a Separate Test Database

When testing database operations, use a dedicated test database or another isolated test environment.

Never run destructive cleanup operations against production data.

6. Avoid Testing Only Implementation Details

Focus on observable behavior and expected results rather than the internal structure of a function.

This allows you to refactor your application without unnecessarily breaking tests that depend on implementation details.

7. Run Tests Automatically

Include automated tests in your development and continuous integration workflows.

Running tests before merging changes can help detect regressions early.

Common Mocha Errors and How to Fix Them

Error 1: Mocha Is Not Recognized

If your terminal reports that Mocha is not found, ensure it is installed in your project.

npm install --save-dev mocha

Then run:

npx mocha

Alternatively, use your configured npm test script:

npm test

Error 2: Cannot Use import Statement Outside a Module

This often occurs when your JavaScript files use ES module syntax but Node.js is treating them as CommonJS.

For regular .js files, add the following to package.json:

{
  "type": "module"
}

Alternatively, configure your project to use CommonJS consistently.

Error 3: No Test Files Found

Check that your test files are inside the expected directory.

By default, Mocha searches for test files in the test directory.

You can also specify a test file directly:

npx mocha test/math.test.js

Error 4: Timeout Exceeded

A timeout failure can indicate that an asynchronous operation is taking too long or that your test never completes.

Check that promises are awaited, callbacks are completed correctly, and external dependencies are responding as expected.

Increase the timeout only when the test legitimately requires more time.

Error 5: Tests Pass Individually but Fail Together

This may happen when tests share mutable data, database records, environment variables, or other resources.

Use isolated test data and appropriate cleanup hooks to make tests independent.

Mocha vs. Jest: Which Should You Choose?

Mocha and Jest are both JavaScript testing tools, but they offer different development experiences.

Feature

Mocha

Jest

Main purpose

Flexible test framework

Testing framework with an integrated toolset

Assertions

Uses Node.js assert, Chai, or another library

Includes built-in expect assertions

Mocking

Commonly uses separate libraries

Includes built-in mock functions

Configuration

Flexible and extensible

Integrated configuration

Asynchronous testing

Supports promises and async/await

Supports promises and async/await

Best suited for

Projects needing a flexible testing setup

Projects that benefit from an integrated testing toolkit

Choose Mocha when you want flexibility in selecting assertion libraries, mocks, and other testing tools.

Choose Jest when you prefer an integrated testing experience with built-in assertions and mocking capabilities.

Neither is automatically the best choice for every project. Consider your existing stack, team preferences, and testing requirements.

Frequently Asked Questions

1. What is Mocha used for in JavaScript?

Mocha is used to run automated tests for JavaScript applications. It supports synchronous and asynchronous testing and can run tests in Node.js and browsers.

2. Is Mocha a testing framework or an assertion library?

Mocha is a testing framework. It organizes and executes tests, while assertion libraries such as Chai or Node.js's built-in assert module verify expected results.

3. Can Mocha be used with Node.js?

Yes. Mocha is commonly used to test Node.js functions, backend services, Express APIs, and asynchronous operations.

4. Is Mocha better than Jest?

Not in every situation. Mocha offers flexibility through its integration with other testing libraries, while Jest provides a more integrated testing toolkit. The right choice depends on your project's needs.

5. Can Mocha test asynchronous functions?

Yes. Mocha supports promises, async/await, and callback-based asynchronous tests.

6. Do I need Chai to use Mocha?

No. You can use Mocha with Node.js's built-in assert module or another assertion library. Chai is optional.

7. Can Mocha test Express.js APIs?

Yes. You can combine Mocha with Supertest to send HTTP requests to an Express application and verify response status codes, response bodies, and other observable behavior.

8. How do I run Mocha tests?

If Mocha is installed in your project, you can run:

npx mocha

If you have configured a test script in package.json, you can also run:

npm test

Conclusion

Mocha is a flexible JavaScript testing framework that helps developers organize, execute, and maintain automated tests.

It supports synchronous functions, asynchronous operations, test hooks, and API testing workflows. By combining Mocha with assertion libraries such as Chai or Node.js's built-in assert module, you can create reliable tests for your applications.

If you're developing with Node.js and Express.js, learning Mocha is a practical step toward building more maintainable backend applications.

Start small: install Mocha, test a simple function, explore asynchronous testing, and gradually introduce automated tests into your real projects.

For additional learning, visit the official Mocha Getting Started guide and practice by testing your own Node.js functions and API endpoints.

D
DevByteAuthor

Technical author and software engineer at DevByte. Writing deep-dive tutorials on distributed systems, modern full-stack web architectures, and cloud deployments.

Keep Exploring

Related Engineering Dispatches

More guides and architectural patterns you might find valuable.

Browse All Articles↘