Mocha

Mocha is a JavaScript test framework running on Node.js, commonly used for testing applications (both frontend and backend). It provides a structure for writing unit tests and integration tests, making sure your code behaves as expected.

Mocha doesn’t come with an assertion library by default, but it works well with popular ones like Chai, Should.js, or Node.js’s built-in assert.


🔹 Key Features

  • Supports BDD (Behavior Driven Development) and TDD (Test Driven Development) styles.
  • Runs tests asynchronously (great for async code).
  • Works in Node.js and the browser.
  • Allows setup/teardown hooks (before, after, beforeEach, afterEach).

🔹 Example with Mocha + Chai

Let’s say we have a simple function add(a, b):

// math.js
function add(a, b) {
  return a + b;
}
module.exports = add;

Now we write a test using Mocha and Chai:

// test/math.test.js
const { expect } = require("chai");
const add = require("../math");

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

  it("should return a number", function () {
    expect(add(2, 3)).to.be.a("number");
  });

});

🔹 Running the Test

  1. Install Mocha and Chai: npm install --save-dev mocha chai
  2. Add a test script in package.json: "scripts": { "test": "mocha" }
  3. Run the tests: npm test

✅ Output:

  Math functions
    ✓ should add two numbers correctly
    ✓ should return a number

Leave a Reply