Hook Function
Mocha provides multiple hooks in its Behaviour Driven Development style interface. There are four types of hooks in Mocha,
- before()
- after()
- beforeEach()
- afterEach()
Hooks are used to set pre and post conditions for a test.
var assert = require('assert');
describe('hooks_demo', function() {
before(function() {
console.log("Before Hook");
});
after(function() {
console.log("After Hook");
});
beforeEach(function() {
console.log("Before Each Hook");
});
afterEach(function() {
console.log("After Each Hook");
});
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);
});
it('should return 0 when the value is present in the array', function () {
assert.equal([1, 2, 3].indexOf(1), 0);
});
});
});

You can also try this code with Online Javascript Compiler
Run Code

In the above code, we are executing two tests, and we added all the hooks to demonstrate the functionality of each hook.
We can even invoke multiple hooks of the same type in the code. The hooks can be differentiated based on the description or the function name. For instance,
beforeEach(function() {
// beforeEach hook
});
beforeEach(function otherBeforeEach() {
// beforeEach names otherBeforeEach
});
beforeEach('this is the third hook', function() {
// beforeEach with the description as this is the third hook
});

You can also try this code with Online Javascript Compiler
Run Code
In the above code snippet, we created three beforeEach hooks and differentiated them based on the function name and the description.
FAQs
-
What is Mocha?
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.
-
What are Hook functions used for?
Hooks are most commonly used to set preconditions and postconditions for a test. They are also used to clean up after the tests are executed.
-
How many types of hooks are there?
There are four types of hooks in Mocha, namely
before()
after()
beforeEach()
afterEach()
-
Can we implement multiple beforeEach() hooks in a describe() block?
Yes, we can implement multiple hooks of the same type in a describe() block. We can distinguish them on the basis of the description or the function name.
-
Are hook synchronous or Asynchronous?
All the hooks in Mocha can be both synchronous and asynchronous. They behave a lot like regular test cases in any programming language.
Key Takeaways
This Blog covered all the necessary points about the Arrow and Hook functions in Mocha. We further discussed the basics of Mocha. Finally, we mentioned the ways of implementation for hook function.
Don’t stop here; check out Coding Ninjas for more unique courses and guided paths. Also, try Coding Ninjas Studio for more exciting articles, interview experiences, and fantastic Data Structures and Algorithms problems.