Hey, hello everyone. Welcome back. In this video, we will be seeing Mocha Hooks.
In general, there are 4 types of hooks Mocha provides us.
The first one is the before()
hook.
The before()
hook will execute the code clock before the test executes from it()
function.
The second one is the after()
hook.
The after()
hook will execute the code block after all the tests executes.
The third one is the beforeEach()
hook.
This beforeEach()
hook will run the code block before every test execution.
The fourth one is the afterEach()
hook.
The afterEach()
hook will be running the code block after every text execution.
Important Note about Hooks
Please keep in mind all the 4 different hooks which we have seen earlier should be present within the describe()
block. If these hooks are not present inside the describe()
block, none of the hooks will be executed during the test execution.
Let's now see how these Mocha hooks can be used.
In order to save some time, I have already written some code, and I'm going to paste it over here.
These are the 4 different types of hooks which we have seen a couple documents back.
If you'll see here, all the hooks are similar to what we have seen and describe()
and it()
functions. It accepts two parameters. One is the description, and the other one is the callback function
.
So, if you see here, the first hook is before()
, so before()
has the description and the callback function
.
Likewise, you will be able to see for other hooks as well.
In order to check whether these hooks are getting executed in a sequence, I'll be writing new a test case, using an it()
function.
describe('Mocha Hooks', function(){
before('Execute Before All Tests', function(){
console.log('Execute Before All Tests');
});
beforeEach('Execute Before Each Test', function(){
console.log('Execute Before Each Test');
});
after('Execute After All Tests', function(){
console.log('Execute After All Tests');
});
afterEach('Execute After Each Test', function(){
console.log('Execute Before Each Test');
});
it('Mocha Hooks Test', function(){
console.log('Mocha - This is a Test for Mocha Hooks');
})
})
So, I have written a test case called Mocha Hooks Test, and I have written a console log to print a message saying that this is a test for Mocha Hooks.
To execute the test, I'm launching my terminal, and using the old command:
npm test
When I hit Enter, Mocha's able to execute all the hooks that are available as part of the test case.
And you will be able to see that each and every hook that we have given as part of this particular Mocha test suite has got executed successfully.
Thank you so much for watching this video.