Installation of the module:
- Install Nodejs onto your system as mocha makes use of it.
- Run the following command to install the module:
npm install mocha
Hooks in Mocha: There are namely six hooks used in the testing by this framework to set up or load up preconditions used in the testing.
Example: Create a test directory in your project. Inside the test directory create two files named helper.js and create_test.js respectively.
Project Directory: The project directory should look something like this:
Now inside the package.json file change the “test” field to “mocha” since the testing framework is mocha.
The helper.js file contains the before() function which is to be executed before all the test cases.
The create_test.js file contains all the test cases that we are going to check using the framework. It contains a describe() function which includes all the test cases defined by it() function.
Steps to run the code:
- Navigate into the directory where your test file is located and type the following command:
- The console will display the message that you passed as the first argument in each it() method. If the Test fails then the error will be reported.
Need for Mocha Once the code is deployed on the server side, it is very difficult and costly to make any changes. User satisfaction is very important and therefore the code should go through vigorous testing before it is production-ready.