Introduction
Mocha is one of the most important frameworks of Javascript for Node development. It is generally used for asynchronous testing and is compatible with all of the major libraries of Node, including
- should.js
- express.js
- better-assert
We can install the mocha framework using the npm install command,
npm install -g mochaLet us look at an example,
arrow.js
var assert = require('assert');
describe('arr', function () {
describe('#indexOf()', function () {
it('should return -1 when the value is not present in the array', function () {
assert.equal([1, 2, 3].indexOf(4), -1);
});
});
});
In the above code, we run a test case using Mocha. If the value is not present in the array, we return -1.
Root Hooks
We are often required to execute hooks before or after every test in every file. These are generally called Root Hooks. We can easily define a Root Hook using the following syntax,
arrow.js
exports.mochaHooks = {
beforeEach(done) {
console.log("This is the Before Each hook");
done();
}
};We can choose from a variety of Hooks, namely.
- beforeAll()
- beforeEach()
- afterAll()
- afterEach()




