Introduction to Mocha

30 Sep, 2020
Mocha is a testing framework for Javascript running on Node.js. The frameworks make it easier to test asynchronous Javascript concepts in the browser. Mocha is widely used for testing Javascript codes before deploying them onto the server.
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
Install Nodejs onto your system as mocha makes use of it.
Run the following command to install the module:npm install mocha
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.
it() describe() beforeEach() afterEach()before()after()
it() 
describe() 
beforeEach() 
afterEach()
before()
after()
describe("hooks", function() {   before(function() {   // Runs before all tests in this block  });     after(function() {  // Runs after all tests in this block });    beforeEach(function() {  // Runs before each test in this block });    afterEach(function() {  // Runs after each test in this block });    // Test cases});
Mocha Structure:
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:
Project directory
Now inside the package.json file change the “test” field to “mocha” since the testing framework is mocha.
Javascript {  "name": "Introduction to Mocha",  "version": "1.0.0",  "description": "Learn to code",  "main": "index.js",  "scripts": {    "test": "mocha"  },  "author": "Yatharth Arora",  "license": "ISC",  "dependencies": {    "mocha": "^8.1.3",  }}
The helper.js file contains the before() function which is to be executed before all the test cases.
Filename: helper.js
// Using moongoose as a databaseconst mongoose = require('mongoose'); mongoose.Promise = global.Promise;  // The before() hookbefore( (done) => {    mongoose.connect("mongodb://localhost/mongotube",     { useUnifiedTopology: true, useNewUrlParser: true});      mongoose.connection    .once('open', () => {        // console.log('Connected...')        done();    })    .on('error', (error) => {        console.log("Your error", error);    });});
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.
Filename: create_test.js
// Student is the database where we will // add details and test if details are added  const Student = require('../App/student');const assert = require('assert');  describe("Create Records", () => {           // First test case    it("create a user in db", () => {          // assert(true);        const geek = new Student({name: "geek"});                  // Save the object in database        geek.save()        .then( () => {          // The geek.isNew returns false if          // object is stored in database          // The !geek.isNew becomes true and          // the test passes.          assert(!geek.isNew)        })        .catch( () => {           console.log("error");        })    });});
Steps to run the code:
Navigate into the directory where your test file is located and type the following command:npm testThe 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.
Navigate into the directory where your test file is located and type the following command:npm test
npm test
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.
Output:
Output file
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.
JavaScript-Misc
JavaScript
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Difference between var, let and const keywords in JavaScript
Remove elements from a JavaScript Array
Difference Between PUT and PATCH Request
Roadmap to Learn JavaScript For Beginners
JavaScript | Promises
Installation of Node.js on Linux
Top 10 Projects For Beginners To Practice HTML and CSS Skills
Difference between var, let and const keywords in JavaScript
How to insert spaces/tabs in text using HTML/CSS?
How to fetch data from an API in ReactJS ?