How to test JavaScript application with Mocha and Chai

JavaScript
Testing
Mocha
Chai
Published on: Dec 24, 2024
  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 iex -D mocha chai

    Install Mocha and Chai as development dependencies.

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

    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. {
    "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.1.2",
    "mocha": "^11.0.1"
    }
    }

    Add test script to package.json.

  6. Terminal window
    npm test

    Run the test.

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