How to test JavaScript application with Mocha and Chai

Technologies used

  • Node - 23.5.0
  • Chai - 5.2.0
  • Mocha - 11.2.2
  1. Terminal window
    npm init -y

    Initialize a new Node.js project in current directory.

  2. index.js
    function getHelloMessage() {
    return 'Hello, world!';
    }
    module.exports = {
    getHelloMessage
    }

    Create getHelloMessage() function that will be tested.

  3. Terminal window
    npm i -D mocha@11.2.2 chai@5.2.0

    Install Mocha and Chai as development dependencies.

  4. index.test.js
    const { getHelloMessage } = require('./index');
    const assert = require('assert');
    describe('getHelloMessage', () => {
    it('should return "Hello, world!"', () => {
    const actualResult = getHelloMessage();
    assert.equal('Hello, world!', actualResult);
    });
    });

    Create a test file index.test.js to test getHelloMessage() function.

    1. The expect function is used to create assertions in the test cases.
    2. Define a test suite for the getHelloMessage() function. The describe() function is used to group related test cases together, making the test output more organized and readable.
    3. Define a test case for the getHelloMessage() function. The it() function is used to define a single test case. The first argument is a description of the test case, and the second argument is a function that contains the test logic.
  5. package.json
    {
    "name": "how-to-test-js-app-with-mocha-and-chai",
    "version": "1.0.0",
    "description": "",
    "main": "index.js",
    "scripts": {
    "test": "mocha index.test.js"
    },
    "keywords": [],
    "author": "",
    "license": "ISC",
    "devDependencies": {
    "chai": "^5.2.0",
    "mocha": "^11.2.2"
    }
    }

    Add test script to package.json.

  6. Terminal window
    npm test

    Run the test.

    Terminal output
    getHelloMessage
    ✔ should return "Hello, world!"
    1 passing (3ms)