Skip to main content

Mocha

  • Version 10+ required Node.js version 14+
  • describe(): Defines a test suite.
  • it(): Defines a test case.
  • assert: Built-in assertion library.
  • chai: Popular assertion library (optional).

Getting Started

  1. Add package to projects

    npm i --save-dev mocha
  2. Making test

    test/mocha.test.js
    import assert from "assert";

    describe("Array", () => {
    describe("#indexOf()", () => {
    it("should return -1 when the value is not present", () => {
    assert.equal([1, 2, 3].indexOf(4), -1);
    });
    });
    });
  3. Add Script

    package.json
    {
    "scripts": {
    "test": "mocha"
    }
    }

Basic concepts

decribe("test suite", () => {
// 'done' to be called to complete the test, and it is OPTIONAL
it("test case infor", (done) => {
// do some stuff ...
done();
});
});

Assertions

USING: assert.<func>(...args)

FunctionUsing
equal(actual, expected)Checks for strict equality.
deepEqual(actual, expected)Checks for deep equality.
notEqual(actual, expected)Checks for inequality.
strictEqual(actual, expected)Checks for strict inequality.
isOk(value)Checks if value is truthy.
isNull(value)Checks if value is null.
isUndefined(value)Checks if value is undefined.
throws(function, expectedError)Checks if function throws expected error.

Hooks

describe("hooks", () => {
before(() => {
// runs once before the first test in this block
});

after(() => {
// runs once after the last test in this block
});

beforeEach(() => {
// runs before each test in this block
});

afterEach(() => {
// runs after each test in this block
});

// test cases
});
// Describing hook - apply for all hooks

beforeEach(function namedFun() {
// beforeEach:namedFun
});

beforeEach("some description", () => {
// beforeEach:some description
});

Folder structure

project-name/
├── package.json
├── src/
│ ├── index.js
│ └── utils.js
├── test/
│ ├── math/
│ │ └── math.test.js
│ ├── utils/
│ │ └── utils.test.js
│ └── index.test.js
└── .gitignore

References