JavaScript

Using Chai With Mocha.js for Better Assertions

When writing tests with Mocha.js, you need a way to check whether your code produces the expected result. For example, if a function should return 10, your…

D
DevByteTechnical Author
Published
15 min read6 views
Using Chai with Mocha for JavaScript testing

Writing code is only one part of software development. Ensuring that your code works correctly, handles unexpected situations, and continues to work after changes is equally important.

Imagine building a Node.js application with authentication, payment processing, database operations, and multiple API endpoints. Everything works during development, but a small code change accidentally breaks an existing feature. Without automated tests, discovering such problems can become time-consuming.

This is where Mocha and Chai become useful.

Mocha is a JavaScript testing framework that helps you organize and execute tests. Chai is an assertion library that allows you to verify whether your code produces the expected results.

Together, they help developers write readable, maintainable, and reliable automated tests for JavaScript and Node.js applications.

In this guide, you'll learn what Mocha and Chai are, how they work together, how to configure a testing environment, and how to write practical tests for real-world applications.

What Is Mocha?

Mocha is a JavaScript testing framework that runs tests in Node.js and supported browser environments.

It provides the structure required to organize test cases, execute them, and report their results.

Mocha supports synchronous tests, asynchronous tests, promises, and async/await.

Key Features of Mocha

  • Supports synchronous and asynchronous testing.

  • Organizes tests using describe() and it().

  • Provides setup and cleanup hooks.

  • Supports configurable test timeouts.

  • Offers different test reporters.

  • Works with assertion libraries such as Chai.

  • Supports testing JavaScript modules and Node.js applications.

For example, a simple Mocha test looks like this:

describe("Calculator", function () {
  it("should add two numbers", function () {
    // Test logic goes here
  });
});

Here, describe() groups related tests, while it() defines an individual test case.

Mocha provides the testing structure, but you need assertions to verify whether the actual result matches the expected result.

That's where Chai comes in.

What Is Chai?

Chai is an assertion library for JavaScript.

Assertions allow you to check whether a particular condition is true, whether two values match, whether an object contains a property, or whether a function throws an error.

For example:

import { expect } from "chai";

expect(2 + 3).to.equal(5);

This assertion verifies that adding two and three produces five.

If the assertion fails, Chai reports the failure, allowing the test runner to identify the problem.

Three Common Chai Assertion Styles

Chai supports three primary assertion styles.

1. Expect style

expect(10).to.equal(10);
expect("hello").to.be.a("string");

2. Should style

import chai from "chai";

chai.should();

(10).should.equal(10);
"hello".should.be.a("string");

The should style adds assertion properties to values and can have limitations with certain JavaScript values, including undefined.

3. Assert style

import { assert } from "chai";

assert.equal(10, 10);
assert.isString("hello");

All three styles can verify conditions. The expect style is a popular choice because its assertions read naturally.

Mocha vs Chai: What Is the Difference?

Although Mocha and Chai are frequently used together, they perform different jobs.

Feature

Mocha

Chai

Main purpose

Runs and organizes tests

Verifies expected results

Type

Testing framework

Assertion library

Defines test suites

Yes

No

Defines test cases

Yes

No

Checks equality

Through an assertion library

Yes

Supports readable assertions

Through integrations

Yes

Handles asynchronous tests

Yes

Assertions can check async results

Can be used independently

Yes

Yes

Consider this example:

import { expect } from "chai";

describe("Calculator", function () {
  it("should return the correct sum", function () {
    const result = 10 + 20;

    expect(result).to.equal(30);
  });
});

In this example:

  • Mocha defines the test suite and test case.

  • The JavaScript expression calculates the result.

  • Chai verifies that the result equals 30.

In simple terms, Mocha runs your tests, and Chai helps you check whether they pass.

Why Use Mocha With Chai?

You can test JavaScript applications without using these particular tools, but Mocha and Chai provide a flexible testing combination.

1. Readable Test Cases

Tests should explain what your code is expected to do.

Compare a simple condition with a descriptive assertion:

expect(user.age).to.equal(25);

This clearly communicates that the user's age should be 25.

2. Better Bug Detection

Automated tests can detect unexpected behavior before code reaches production.

For example, a test can verify that a registration function rejects invalid email addresses or that a pricing function calculates totals correctly.

3. Easier Refactoring

When you modify existing code, automated tests help verify that important behavior remains unchanged.

This is particularly useful in large Node.js applications with multiple modules and business rules.

4. Support for Asynchronous Operations

Node.js applications frequently use promises, database queries, and HTTP requests.

Mocha supports asynchronous tests, making it possible to test these operations without blocking the test runner.

5. Flexible Integration

Mocha and Chai can be integrated into applications using different module systems and can work alongside other testing tools.

For example, you can combine them with Sinon for mocking dependencies or Supertest for testing HTTP endpoints.

How to Install Mocha and Chai

Let's create a small Node.js project and configure Mocha and Chai.

Step 1: Create a Project

Create a directory for your project:

mkdir mocha-chai-demo
cd mocha-chai-demo

Initialize the project:

npm init -y

This creates a package.json file that stores project metadata and dependencies.

Step 2: Install Mocha and Chai

Install both packages as development dependencies:

npm install --save-dev mocha chai

For this tutorial, we'll use ES modules with import syntax.

Add the following configuration to your package.json:

{
  "type": "module",
  "scripts": {
    "test": "mocha"
  }
}

Important: If your existing package.json already contains dependencies, scripts, or other settings, add or update only the relevant fields instead of replacing the entire file.

The "type": "module" setting enables ES module syntax in .js files within the project.

Step 3: Create the Project Structure

Create the following files:

mocha-chai-demo/
├── src/
│   └── calculator.js
├── test/
│   └── calculator.test.js
├── package.json
└── package-lock.json

The src directory contains application code, while the test directory contains automated tests.

Keeping application code separate from test code makes the project easier to maintain.

Writing Your First Test With Mocha and Chai

Let's create a simple calculator module.

Step 1: Write the Application Code

Create src/calculator.js:

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

export function subtract(a, b) {
  return a - b;
}

export function multiply(a, b) {
  return a * b;
}

export function divide(a, b) {
  if (b === 0) {
    throw new Error("Cannot divide by zero");
  }

  return a / b;
}

This module provides four mathematical operations.

The division function also validates its input and throws an error when the divisor is zero.

Step 2: Write the Test Cases

Create test/calculator.test.js:

import { expect } from "chai";

import {
  add,
  subtract,
  multiply,
  divide
} from "../src/calculator.js";

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

  describe("subtract()", function () {
    it("should subtract two numbers", function () {
      expect(subtract(10, 4)).to.equal(6);
    });
  });

  describe("multiply()", function () {
    it("should multiply two numbers", function () {
      expect(multiply(3, 4)).to.equal(12);
    });
  });

  describe("divide()", function () {
    it("should divide two numbers", function () {
      expect(divide(10, 2)).to.equal(5);
    });

    it("should throw an error when dividing by zero", function () {
      expect(() => divide(10, 0))
        .to.throw("Cannot divide by zero");
    });
  });
});

Let's understand the important methods.

describe() groups related tests. In this example, all calculator operations belong to the Calculator test suite.

it() describes an individual behavior that should work correctly.

expect() creates an assertion.

.to.equal() verifies that the actual value equals the expected value.

.to.throw() verifies that a function throws an error matching the specified message.

Notice that the division error test passes a function to expect(). This allows Chai to execute the function and inspect whether it throws an error.

Step 3: Run the Tests

Execute:

npm test

Mocha discovers test files matching its default patterns and executes the tests.

Your output should indicate that five tests passed.

The exact formatting may vary depending on your Mocha configuration and reporter.

Understanding Common Chai Assertions

Chai provides numerous assertions for checking different kinds of values and behavior.

Let's explore some commonly used methods.

1. Equality Assertions

Use equality assertions when you want to verify expected values.

import { expect } from "chai";

expect(10).to.equal(10);
expect("Node.js").to.equal("Node.js");
expect(true).to.equal(true);

For objects and arrays, remember that equal() checks reference identity rather than recursively comparing their contents.

For deep comparisons, use deep.equal():

expect({ name: "Rahul" })
  .to.deep.equal({ name: "Rahul" });

expect([1, 2, 3])
  .to.deep.equal([1, 2, 3]);

2. Type Assertions

You can verify the type of a value:

expect("Hello").to.be.a("string");
expect(25).to.be.a("number");
expect(true).to.be.a("boolean");
expect([]).to.be.an("array");

These assertions are useful when validating function outputs or application data.

3. Truthiness Assertions

Use truthiness assertions to check whether a value is truthy or falsy.

expect(true).to.be.true;
expect(false).to.be.false;

expect("Node.js").to.be.ok;
expect(0).to.not.be.ok;

Remember that JavaScript treats values such as 0, false, null, undefined, and an empty string as falsy.

4. Object Property Assertions

You can verify that an object contains a particular property.

const user = {
  id: 1,
  name: "Rahul",
  role: "developer"
};

expect(user).to.have.property("name");
expect(user).to.have.property("role", "developer");

This is useful for checking objects returned by services and APIs.

5. Array Assertions

Chai can verify array contents and membership.

const languages = ["JavaScript", "Python", "TypeScript"];

expect(languages).to.include("Python");
expect(languages).to.have.lengthOf(3);

These assertions are useful when testing filtering, sorting, and data-processing functions.

6. Error Assertions

You can test whether a function throws an error:

function getUser() {
  throw new Error("User not found");
}

expect(getUser).to.throw("User not found");

If the function requires arguments, wrap the invocation in another function when passing it to the assertion.

This lets Chai capture the thrown error and verify its message or type.

Testing Asynchronous Functions With Mocha

Asynchronous operations are common in Node.js applications.

Your application might retrieve users from a database, call an external API, or perform an operation that returns a promise.

Mocha supports testing asynchronous code using callbacks, promises, and async/await.

Example: Testing a Promise

Create a function in src/userService.js:

export function getUser() {
  return Promise.resolve({
    id: 1,
    name: "Rahul"
  });
}

Now create a test in test/userService.test.js:

import { expect } from "chai";

import { getUser } from "../src/userService.js";

describe("User Service", function () {
  it("should return user details", async function () {
    const user = await getUser();

    expect(user).to.deep.equal({
      id: 1,
      name: "Rahul"
    });
  });
});

Mocha waits for the asynchronous test to finish because the test function returns a promise through async.

If an awaited operation rejects or an assertion fails, Mocha reports the test as failed.

Example: Testing a Rejected Promise

Create a function that rejects its promise:

export function getMissingUser() {
  return Promise.reject(new Error("User not found"));
}

You can test the rejection with Chai's promise assertions, but these require an additional plugin.

Alternatively, you can use native JavaScript:

it("should reject when the user is missing", async function () {
  try {
    await getMissingUser();
    throw new Error("Expected getMissingUser() to reject");
  } catch (error) {
    expect(error.message).to.equal("User not found");
  }
});

This example works, but there is a subtle issue: the catch block can also catch the manually thrown error if the function unexpectedly resolves. That makes the test less reliable.

A better approach is to use a rejection assertion library such as chai-as-promised, or explicitly capture the rejection:

it("should reject when the user is missing", async function () {
  let error;

  try {
    await getMissingUser();
  } catch (err) {
    error = err;
  }

  expect(error).to.be.instanceOf(Error);
  expect(error.message).to.equal("User not found");
});

This ensures that an unexpected successful resolution causes the test to fail.

Using Hooks in Mocha

Mocha provides hooks for executing setup and cleanup logic around test cases.

The four commonly used hooks are:

  • before()

  • after()

  • beforeEach()

  • afterEach()

For example:

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

  beforeEach(function () {
    user = {
      id: 1,
      name: "Rahul"
    };
  });

  it("should contain the correct user name", function () {
    expect(user.name).to.equal("Rahul");
  });

  it("should contain a user ID", function () {
    expect(user.id).to.equal(1);
  });
});

The beforeEach() hook runs before every test in the suite.

This helps you create fresh test data and reduce repeated setup code.

When Should You Use Each Hook?

Hook

Purpose

before()

Run setup once before tests in a suite

after()

Run cleanup once after tests in a suite

beforeEach()

Run setup before each test

afterEach()

Run cleanup after each test

These hooks are particularly useful when working with database fixtures, temporary files, test servers, or mocked dependencies.

Testing Node.js APIs With Mocha and Chai

In real projects, testing individual functions is only part of the job.

You may also need to test HTTP endpoints, including response status codes, response bodies, and validation errors.

For HTTP integration tests, developers often combine Mocha and Chai with Supertest.

Supertest sends HTTP requests to an application and makes it easier to verify the responses.

Install Supertest

npm install --save-dev supertest

Suppose your Express application has a health-check endpoint.

Create src/app.js:

import express from "express";

const app = express();

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

export default app;

Install Express if your project doesn't already have it:

npm install express

Now create test/app.test.js:

import { expect } from "chai";
import request from "supertest";

import app from "../src/app.js";

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

    expect(response.status).to.equal(200);

    expect(response.body).to.deep.equal({
      status: "ok"
    });
  });
});

Run the tests:

npm test

This test checks both the HTTP status code and the JSON response body.

Supertest can run requests against the Express application without requiring you to start a separate server manually.

For endpoints that depend on authentication, databases, or external services, configure the test environment carefully and isolate external dependencies where appropriate.

Testing Best Practices

Writing tests is useful, but poorly designed tests can become difficult to maintain.

Follow these practices to make your test suite more reliable.

1. Test Behavior, Not Just Implementation

Write tests around what your functions and endpoints should do.

For example, verify that a registration endpoint rejects an invalid email address instead of testing private implementation details that may change during refactoring.

2. Keep Tests Independent

One test should not rely on another test running first.

Create fresh data when necessary and clean up temporary resources after tests finish.

3. Test Edge Cases

Do not test only successful scenarios.

Consider invalid inputs, missing data, empty arrays, rejected promises, permission errors, and boundary conditions.

4. Use Descriptive Test Names

Prefer:

it("should reject an invalid email address", function () {
  // Test logic
});

over:

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

Descriptive names make failed tests easier to understand.

5. Avoid Real External Dependencies When Possible

Tests that depend on live payment services, external APIs, or production databases can become slow and unreliable.

Use controlled test environments and mock external dependencies where appropriate.

6. Run Tests Automatically

Integrate your test suite into a continuous integration workflow.

Running tests during pull requests and deployments can help detect regressions before code reaches production.

7. Maintain Meaningful Coverage

Code coverage indicates which parts of your code were executed during tests.

However, high coverage alone does not prove that your tests are effective. Focus on important application behavior, error handling, and business rules.

Common Problems When Using Mocha and Chai

Problem 1: describe is not defined

This usually occurs when test files are executed directly with Node.js rather than through Mocha.

Run:

npm test

Also check that Mocha is installed and your package script is configured correctly.

Problem 2: Import Errors

If you're using import statements, ensure your project is configured for ES modules.

For this tutorial, the relevant setting is:

{
  "type": "module"
}

Alternatively, you can configure your project to use CommonJS, but your imports and exports must match that module system.

Problem 3: Tests Finish Before Asynchronous Operations

If your test performs an asynchronous operation, make sure the test returns its promise or uses async/await.

For example:

it("should fetch user details", async function () {
  const user = await getUser();

  expect(user.name).to.equal("Rahul");
});

Without proper asynchronous handling, the test runner may finish before the operation completes.

Problem 4: Assertion Failures

When a test fails, compare the actual result with the expected result.

For example:

expect(2 + 2).to.equal(5);

This test fails because the actual result is 4, not 5.

The failure may indicate a problem with the application code or an incorrect expectation in the test.

Mocha and Chai vs Jest

Jest is another popular JavaScript testing framework.

Both approaches can be useful, depending on your project requirements.

Feature

Mocha + Chai

Jest

Test runner

Mocha

Jest

Assertions

Chai or another assertion library

Built-in assertions

Mocking

Commonly paired with Sinon

Built-in mocking utilities

Configuration

Flexible, often requires additional tools

Many features included

Node.js testing

Supported

Supported

React testing

Possible with additional libraries

Commonly used with React Testing Library

Best fit

Developers who want a flexible testing stack

Developers who prefer an integrated testing framework

Neither option is universally better.

Mocha and Chai provide flexibility and let you choose separate tools for assertions, mocking, and HTTP testing.

Jest provides a more integrated experience for many common testing tasks.

Choose based on your team's preferences, application requirements, and existing codebase.

Frequently Asked Questions

1. What is Mocha in JavaScript?

Mocha is a JavaScript testing framework used to organize and execute automated tests in Node.js and supported browser environments.

2. What is Chai used for?

Chai is an assertion library that verifies whether actual values and application behavior match expected results.

3. Can Mocha work without Chai?

Yes. Mocha can be used with Node.js's built-in assertion module or other assertion libraries. Chai is optional.

4. Can Chai work without Mocha?

Yes. Chai can be used with other testing frameworks or directly in JavaScript code, although assertions are most commonly used as part of a test suite.

5. What is the difference between expect() and assert() in Chai?

Both provide assertion functionality. The expect style uses chainable expressions, while the assert style provides function-based assertions.

For example:

expect(5).to.equal(5);
assert.equal(5, 5);

6. Can I test asynchronous Node.js functions with Mocha?

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

7. Do I need Sinon with Mocha and Chai?

No. Sinon is optional. It is useful when you need to create spies, stubs, and mocks to isolate dependencies during testing.

8. Is Mocha and Chai enough for API testing?

They can handle test execution and assertions, but an HTTP testing library such as Supertest is useful for testing Express endpoints.

9. Are Mocha and Chai still useful for Node.js developers?

They remain useful tools for developers who need a flexible testing setup. However, you should evaluate current package compatibility, project maintenance requirements, and alternatives before choosing a testing stack.

Conclusion

Mocha and Chai are useful tools for building reliable automated tests in JavaScript and Node.js applications.

Mocha organizes and executes test cases, while Chai provides readable assertions for verifying application behavior. Together, they can test simple functions, asynchronous operations, error handling, and HTTP endpoints when combined with suitable supporting tools.

If you're a Node.js developer, learning automated testing can help you catch bugs earlier, refactor code with greater confidence, and build more maintainable applications.

Start with a small calculator test, practice common assertions, explore asynchronous tests, and gradually introduce testing into a real backend project.

The goal of automated testing isn't simply to make every test pass. It's to gain confidence that your application behaves as expected, even as your code changes.

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↘