Node.js

How to Build a Complete Node.js Testing Setup With Mocha, Chai, and Sinon

Testing becomes increasingly important as a Node.js application grows. At the beginning, you may manually check whether a function works. But as your…

D
DevByteTechnical Author
Published
17 min read4 views
Node.js testing with Mocha, Chai and Sinon

Imagine you're building a Node.js API for user registration. Everything works perfectly on your machine. You can create users, validate emails, and save data to MongoDB.

But after adding a new feature, your login API suddenly stops working. You fix it, deploy the application, and discover that another API has broken.

Sound familiar?

This is one of the biggest challenges in backend development: how do you make sure your existing code continues to work when you introduce new changes?

The answer is automated testing.

Instead of manually checking every API after every code change, you can write tests that automatically verify your application's behavior. In Node.js, three popular tools can help you build a reliable testing setup:

  • Mocha: Runs your tests and organizes test suites.

  • Chai: Provides assertions to verify whether your code behaves as expected.

  • Sinon: Creates stubs, spies, and mocks to isolate code and track function calls.

In this guide, we'll build a practical Node.js testing setup from scratch, write unit tests for a service, test asynchronous functions, isolate database dependencies, and learn how to run tests automatically.

By the end, you'll understand how to use Mocha, Chai, and Sinon together in a real-world Node.js project.

1. What Is Automated Testing in Node.js?

Automated testing means writing code that checks whether other code works correctly.

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

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

module.exports = add;

You could manually call this function and check its output. However, you can also write a test that automatically verifies the result:

const add = require("./add");
const assert = require("node:assert/strict");

if (add(2, 3) !== 5) {
  throw new Error("Expected 2 + 3 to equal 5");
}

assert.equal(add(2, 3), 5);

The second approach is easier to maintain when your project contains hundreds of functions.

Whenever someone changes the implementation, the test can run again and identify unexpected behavior.

Why Do Node.js Applications Need Testing?

Testing is especially important in backend applications because a single change can affect multiple parts of a system.

Common examples include:

  • A registration API accidentally accepting invalid email addresses.

  • A payment service charging a customer twice.

  • A database query returning incorrect results.

  • A password-reset function generating an invalid token.

  • A refactor breaking an API that previously worked.

Automated tests help detect these problems before they reach production.

However, testing doesn't guarantee that an application is completely bug-free. It provides confidence that the specific behaviors covered by your tests work as intended.

2. Understanding Mocha, Chai, and Sinon

Before installing the packages, let's understand what each tool does.

What Is Mocha?

Mocha is a JavaScript testing framework that runs tests in Node.js.

It provides functions such as:

  • describe() to group related tests.

  • it() to define individual test cases.

  • beforeEach() to execute setup code before every test.

  • afterEach() to execute cleanup code after every test.

For example:

describe("User Service", function () {
  it("should create a user", function () {
    // Test implementation
  });
});

Mocha organizes and executes the test. However, it doesn't provide every assertion or mocking utility you might need.

That's where Chai and Sinon come in.

What Is Chai?

Chai is an assertion library.

Assertions allow you to verify the expected behavior of your code.

For example:

const { expect } = require("chai");

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

If the result isn't 5, the assertion fails and reports an error.

Chai offers several assertion styles, including:

  • expect

  • should

  • assert

In this tutorial, we'll use the expect style because it reads naturally.

What Is Sinon?

Sinon helps you test code that depends on other functions or external systems.

It provides three particularly useful features:

Spies: Track whether a function was called and what arguments it received.

Stubs: Replace a function with controlled behavior.

Mocks: Set expectations about how an object should be used.

For example, suppose a service sends an email after registering a user. You don't want every unit test to send a real email.

You can use a Sinon stub to replace the email function and control its behavior during the test.

How Do These Tools Work Together?

Think of the tools as three parts of one testing system:

Tool

Main responsibility

Example

Mocha

Runs and organizes tests

Execute all user service tests

Chai

Verifies expected results

Confirm that a user has an email

Sinon

Controls and observes dependencies

Replace an email sender with a stub

Together, these tools allow you to write focused tests without depending on real databases, external APIs, or email services.

3. Create a Node.js Project

Let's create a small project that we'll use throughout this tutorial.

Open your terminal and execute:

mkdir node-testing-demo
cd node-testing-demo
npm init -y

This creates a project directory and generates a package.json file.

Next, install the testing packages:

npm install --save-dev mocha chai sinon

We'll use ES modules in this tutorial. Add "type": "module" to your package.json and configure a test script.

Your package.json can look like this:

{
  "name": "node-testing-demo",
  "version": "1.0.0",
  "type": "module",
  "scripts": {
    "test": "mocha"
  },
  "devDependencies": {
    "chai": "^5.0.0",
    "mocha": "^11.0.0",
    "sinon": "^20.0.0"
  }
}

The version numbers above illustrate the configuration format. Your installed versions may differ, so keep the versions generated by your package manager rather than replacing them with these example numbers.

You can verify that the packages are installed by running:

npm list mocha chai sinon

Now let's create a basic project structure.

node-testing-demo/
├── src/
│   ├── services/
│   │   └── userService.js
│   └── repositories/
│       └── userRepository.js
├── test/
│   └── userService.test.js
├── package.json
└── package-lock.json

We'll place application code inside src/ and tests inside test/.

Keeping these directories separate makes it easier to maintain a growing project.

4. Write Your First Test With Mocha and Chai

Before testing a complete service, let's understand the basic testing workflow.

Create a file named src/calculator.js:

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

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

Now create test/calculator.test.js:

import { expect } from "chai";
import { describe, it } from "mocha";

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

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

  describe("subtract()", function () {
    it("should subtract one number from another", function () {
      expect(subtract(10, 4)).to.equal(6);
    });
  });
});

Run the tests:

npm test

Mocha discovers the test file and executes both test cases.

If the functions return the expected values, both tests pass.

Understanding the Test Structure

Let's break down the important parts.

describe()

Groups related test cases.

describe("Calculator", function () {
  // Calculator tests
});

it()

Defines one behavior you want to verify.

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

expect()

Starts a Chai assertion.

expect(add(2, 3)).to.equal(5);

The assertion verifies that the function returns 5.

A good test describes expected behavior rather than merely repeating the implementation.

For example, should return the total price including tax is more informative than should call calculatePrice.

5. Build a Real-World User Service

Now let's create a service that resembles code you might use in an Express.js application.

Suppose we have a user service that:

  1. Validates incoming user data.

  2. Checks whether the email already exists.

  3. Creates a new user.

  4. Returns the created user.

We'll keep the database interaction in a separate repository so we can test the service without connecting to MongoDB or MySQL.

Create src/repositories/userRepository.js:

export const userRepository = {
  async findByEmail(email) {
    // Database query would go here.
    throw new Error("Not implemented");
  },

  async create(userData) {
    // Database insert would go here.
    throw new Error("Not implemented");
  },
};

This is an intentionally incomplete repository. We'll replace its methods with Sinon stubs during testing, so the test suite won't need a real database.

Next, create src/services/userService.js:

import { userRepository } from "../repositories/userRepository.js";

export async function createUser(userData) {
  if (!userData.name || !userData.email) {
    throw new Error("Name and email are required");
  }

  const existingUser = await userRepository.findByEmail(
    userData.email
  );

  if (existingUser) {
    throw new Error("Email already exists");
  }

  return userRepository.create({
    name: userData.name,
    email: userData.email,
  });
}

This service contains business logic, while the repository is responsible for database operations.

Notice that we haven't added Express.js routes or a database connection. That's intentional: we want to test the service independently.

6. Test the Service Using Mocha, Chai, and Sinon

Create test/userService.test.js:

import { expect } from "chai";
import sinon from "sinon";
import { afterEach, describe, it } from "mocha";

import { createUser } from "../src/services/userService.js";
import { userRepository } from "../src/repositories/userRepository.js";

describe("User Service", function () {
  afterEach(function () {
    sinon.restore();
  });

  it("should create a user successfully", async function () {
    const userData = {
      name: "Rahul",
      email: "rahul@example.com",
    };

    const createdUser = {
      id: "user-123",
      ...userData,
    };

    sinon.stub(userRepository, "findByEmail").resolves(null);

    const createStub = sinon
      .stub(userRepository, "create")
      .resolves(createdUser);

    const result = await createUser(userData);

    expect(result).to.deep.equal(createdUser);

    expect(createStub.calledOnce).to.equal(true);

    expect(createStub.firstCall.args[0]).to.deep.equal(userData);
  });
});

Run the test:

npm test

The test verifies that the service creates a user successfully without connecting to a real database.

What Is Happening Here?

Let's examine the important lines.

1. Stub the database lookup

sinon.stub(userRepository, "findByEmail").resolves(null);

This replaces the repository's findByEmail() method with a stub that resolves to null.

Our service interprets this result as meaning that the email doesn't already exist.

2. Stub the create operation

const createStub = sinon
  .stub(userRepository, "create")
  .resolves(createdUser);

Instead of inserting a document or database row, the stub returns a predefined user object.

3. Call the actual service

const result = await createUser(userData);

The service's real business logic runs, but its database dependencies are controlled by the test.

4. Verify the result

expect(result).to.deep.equal(createdUser);

Chai's deep.equal() compares the contents of the objects rather than checking whether they are the exact same object reference.

5. Verify the dependency call

expect(createStub.calledOnce).to.equal(true);

This confirms that the repository's create() method was called exactly once.

Finally, sinon.restore() restores the original methods after each test. This prevents stubs from leaking into other test cases.

7. Test Validation Errors

Testing successful behavior is important, but it's only half of the job.

You should also verify that your application rejects invalid input.

Add these tests inside the existing User Service test suite:

it("should reject a user without a name", async function () {
  const userData = {
    email: "rahul@example.com",
  };

  try {
    await createUser(userData);
    expect.fail("Expected createUser() to throw an error");
  } catch (error) {
    expect(error.message).to.equal("Name and email are required");
  }
});

This test confirms that a user without a name is rejected.

We can also test duplicate emails:

it("should reject an existing email", async function () {
  const userData = {
    name: "Rahul",
    email: "rahul@example.com",
  };

  sinon
    .stub(userRepository, "findByEmail")
    .resolves({ id: "existing-user" });

  try {
    await createUser(userData);
    expect.fail("Expected createUser() to throw an error");
  } catch (error) {
    expect(error.message).to.equal("Email already exists");
  }
});

The repository stub simulates an existing user. No actual database record is needed.

A Cleaner Way to Test Rejected Promises

Chai can be used with async functions, but its core assertion API doesn't automatically provide a promise-rejection matcher.

For simple tests, you can write a small helper:

async function getError(promise) {
  try {
    await promise;
  } catch (error) {
    return error;
  }

  throw new Error("Expected promise to reject");
}

Then use it in your test:

it("should reject an existing email", async function () {
  sinon
    .stub(userRepository, "findByEmail")
    .resolves({ id: "existing-user" });

  const error = await getError(
    createUser({
      name: "Rahul",
      email: "rahul@example.com",
    })
  );

  expect(error.message).to.equal("Email already exists");
});

This pattern makes asynchronous error assertions easier to read. You could also use a dedicated promise assertion library if your project needs more advanced rejection assertions.

8. Understand Sinon Spies, Stubs, and Mocks

Sinon offers multiple ways to observe or control functions. Although they are related, they solve different problems.

Sinon Spies

A spy tracks how a function is used without replacing its behavior.

For example:

import sinon from "sinon";
import { expect } from "chai";

function sendNotification(message) {
  return `Sent: ${message}`;
}

const spy = sinon.spy(sendNotification);

const result = spy("Welcome!");

expect(result).to.equal("Sent: Welcome!");
expect(spy.calledOnce).to.equal(true);
expect(spy.firstCall.args[0]).to.equal("Welcome!");

The spy records the function call while allowing the original function to execute.

Use spies when you want to inspect function calls without changing the behavior being tested.

Sinon Stubs

A stub replaces a function with controlled behavior.

const paymentStub = sinon.stub();

paymentStub.resolves({
  status: "success",
  transactionId: "txn-123",
});

Now you can test how your application behaves when a payment provider reports success without sending a real payment request.

You can also simulate failures:

paymentStub.rejects(new Error("Payment provider unavailable"));

This is particularly useful for testing error-handling logic.

Sinon Mocks

Mocks combine test doubles with predefined expectations.

const notifier = {
  send(message) {
    return true;
  },
};

const mock = sinon.mock(notifier);

mock.expects("send")
  .once()
  .withArgs("User created");

notifier.send("User created");

mock.verify();

The mock verifies that the expected method was called the expected number of times with the expected arguments.

Mocks can be useful when the interaction itself is part of the contract, but using them excessively can make tests brittle.

Practical recommendation: Use stubs when you need to control external dependencies, spies when you need to observe calls, and mocks when you specifically want to verify interaction expectations.

9. Test Asynchronous Code and API Dependencies

Node.js applications commonly depend on asynchronous operations such as database queries, HTTP requests, and file operations.

Mocha supports asynchronous tests through promises and async/await.

Consider this example:

export async function getUserProfile(userId, userRepository) {
  if (!userId) {
    throw new Error("User ID is required");
  }

  const user = await userRepository.findById(userId);

  if (!user) {
    throw new Error("User not found");
  }

  return user;
}

A test can simulate a successful database lookup:

import { expect } from "chai";
import sinon from "sinon";

import { getUserProfile } from "../src/services/getUserProfile.js";

describe("getUserProfile()", function () {
  afterEach(function () {
    sinon.restore();
  });

  it("should return the requested user", async function () {
    const user = {
      id: "user-123",
      name: "Rahul",
    };

    const repository = {
      findById: async () => null,
    };

    sinon.stub(repository, "findById").resolves(user);

    const result = await getUserProfile("user-123", repository);

    expect(result).to.deep.equal(user);
  });
});

Because the test awaits getUserProfile(), Mocha waits for the promise to settle before reporting the result.

If the promise rejects unexpectedly, Mocha marks the test as failed.

This is better than starting asynchronous work without returning or awaiting it, which can cause tests to finish before the operation completes.

10. Test Express.js Routes Separately

Service tests are useful, but they don't prove that your Express.js routes behave correctly.

For route-level tests, you can use an HTTP testing library such as Supertest.

Install it:

npm install --save-dev supertest

For example, create src/app.js:

import express from "express";
import { createUser } from "./services/userService.js";

const app = express();

app.use(express.json());

app.post("/users", async (req, res) => {
  try {
    const user = await createUser(req.body);

    res.status(201).json({
      success: true,
      data: user,
    });
  } catch (error) {
    if (
      error.message === "Name and email are required" ||
      error.message === "Email already exists"
    ) {
      return res.status(400).json({
        success: false,
        message: error.message,
      });
    }

    return res.status(500).json({
      success: false,
      message: "Internal server error",
    });
  }
});

export default app;

This example assumes Express is installed:

npm install express

Now create a route test:

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

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

describe("POST /users", function () {
  it("should reject a request without required fields", async function () {
    const response = await request(app)
      .post("/users")
      .send({
        email: "rahul@example.com",
      });

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

    expect(response.body.success).to.equal(false);

    expect(response.body.message).to.equal(
      "Name and email are required"
    );
  });
});

This test checks the HTTP status and response body without opening a network port.

However, the route imports the service directly, so this test still uses the service's real repository dependency. For a complete isolated route test, introduce dependency injection or stub the service at the appropriate module boundary. Alternatively, use an integration test with a dedicated test database.

The important distinction is that unit tests verify individual components, while integration tests verify that components work together.

11. Organize Your Testing Setup for a Growing Project

Once you start writing tests for multiple services, organization becomes important.

A practical structure might look like this:

src/
├── controllers/
│   └── userController.js
├── services/
│   └── userService.js
├── repositories/
│   └── userRepository.js
├── routes/
│   └── userRoutes.js
└── app.js

test/
├── unit/
│   ├── userService.test.js
│   └── authService.test.js
├── integration/
│   └── userRoutes.test.js
└── helpers/
    └── testUtils.js

This structure separates tests by purpose.

Unit tests focus on a single function, service, or component with its dependencies controlled.

Integration tests check whether multiple components work together, such as an API route and a test database.

You don't need to create every directory on day one. Start with a simple structure and add separation when your project grows.

Configure Test Scripts

You can update your package.json scripts to support different test types:

{
  "scripts": {
    "test": "mocha",
    "test:unit": "mocha \"test/unit/**/*.test.js\"",
    "test:integration": "mocha \"test/integration/**/*.test.js\""
  }
}

These commands assume your tests use the shown directory structure.

Run all tests:

npm test

Run only unit tests:

npm run test:unit

Run only integration tests:

npm run test:integration

This separation becomes useful when integration tests require a database or take longer to execute.

12. Common Testing Mistakes to Avoid

Even a well-configured testing framework can produce unreliable tests if you use it incorrectly.

Mistake 1: Testing Only Successful Scenarios

A function may work correctly with valid input but fail when required fields are missing or an external service is unavailable.

Test both successful and failure scenarios.

Mistake 2: Sharing State Between Tests

If one test leaves a stub, modified environment variable, or database record behind, another test may behave differently depending on execution order.

Use hooks such as afterEach() to restore Sinon stubs and clean up test data.

Mistake 3: Using Production Services During Unit Tests

Unit tests generally shouldn't send real emails, charge payment methods, or make requests to production APIs.

Use controlled stubs for these dependencies. Reserve real integrations for appropriately isolated integration or end-to-end tests.

Mistake 4: Writing Tests That Depend on Implementation Details

A test that verifies every internal function call can fail whenever you refactor code, even if the externally observable behavior remains correct.

Focus primarily on meaningful outputs, side effects, and business rules.

Mistake 5: Forgetting to Await Asynchronous Operations

This pattern is unreliable:

it("should fetch a user", function () {
  getUserProfile("user-123");
});

The test doesn't return or await the promise, so Mocha may finish before the operation completes.

Use async/await:

it("should fetch a user", async function () {
  const result = await getUserProfile("user-123");

  expect(result.id).to.equal("user-123");
});

Mistake 6: Treating Code Coverage as Proof of Quality

Code coverage tells you which portions of your code were executed during testing. It doesn't prove that your tests check the right outcomes.

A test suite can achieve high coverage while missing important business rules.

Prioritize meaningful assertions over chasing a particular coverage percentage.

13. Run Tests Automatically in Your Development Workflow

Writing tests is only useful if you run them consistently.

A simple workflow for a Node.js project might be:

  1. Implement a feature.

  2. Write unit tests for its business logic.

  3. Add integration tests for important interactions.

  4. Run the test suite locally.

  5. Push the changes to GitHub.

  6. Run the tests automatically in your CI pipeline.

  7. Merge the changes only when required checks pass.

For example, a basic GitHub Actions workflow could look like this:

Create .github/workflows/test.yml:

name: Node.js Tests

on:
  push:
  pull_request:

jobs:
  test:
    runs-on: ubuntu-latest

    steps:
      - name: Checkout repository
        uses: actions/checkout@v4

      - name: Set up Node.js
        uses: actions/setup-node@v4
        with:
          node-version: 22
          cache: npm

      - name: Install dependencies
        run: npm ci

      - name: Run tests
        run: npm test

This workflow runs your tests when changes are pushed or a pull request is opened.

For a production project, use a Node.js version that matches your supported runtime, and pin or update GitHub Actions versions according to your organization's security and maintenance practices.

If your integration tests require MongoDB, MySQL, Redis, or other external services, configure suitable test instances in the CI environment.

14. When Should You Use Mocha, Chai, and Sinon?

These tools work well together, but they aren't the only available testing stack for Node.js.

Consider this setup when:

  • You want a flexible testing framework.

  • You prefer choosing your assertion and mocking libraries separately.

  • Your project uses Mocha and you want a mature ecosystem of testing utilities.

  • You need to test business logic independently from databases and external APIs.

  • You want explicit control over how tests are organized and executed.

Other frameworks, including Jest and Vitest, provide different combinations of test execution, assertions, mocking, and related utilities.

There isn't one universally best testing framework. The right choice depends on your project, team preferences, runtime requirements, and existing tooling.

For a new project, compare the maintenance requirements, ecosystem, and compatibility of the tools before committing to a testing stack.

Conclusion

Building a reliable Node.js testing setup doesn't have to be complicated.

Mocha gives you a framework for organizing and executing tests. Chai helps you verify expected results, while Sinon lets you control and observe dependencies such as database repositories and external services.

Together, they make it easier to test business logic, validate error handling, and catch regressions before they reach production.

Start with a few important service tests, add coverage for failure scenarios, and introduce integration tests when you need to verify how components work together.

The most valuable test suite isn't the one with the most tests—it's the one that consistently catches meaningful problems before your users experience them.

If you're building Node.js applications professionally, learning automated testing is an important step toward writing backend code that is easier to maintain, refactor, and deploy with confidence.

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↘