Skip to content
geeksforgeeks
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Tutorials
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
  • Practice
    • Build your AI Agent
    • GfG 160
    • Problem of the Day
    • Practice Coding Problems
    • GfG SDE Sheet
  • Contests
    • Accenture Hackathon (Ending Soon!)
    • GfG Weekly [Rated Contest]
    • Job-A-Thon Hiring Challenge
    • All Contests and Events
  • JS Tutorial
  • JS Exercise
  • JS Interview Questions
  • JS Array
  • JS String
  • JS Object
  • JS Operator
  • JS Date
  • JS Error
  • JS Projects
  • JS Set
  • JS Map
  • JS RegExp
  • JS Math
  • JS Number
  • JS Boolean
  • JS Examples
  • JS Free JS Course
  • JS A to Z Guide
  • JS Formatter
Open In App
Next Article:
How to write a function in JavaScript ?
Next article icon

Introduction to Mocha

Last Updated : 30 Mar, 2023
Comments
Improve
Suggest changes
Like Article
Like
Report

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:

  1. Install Nodejs onto your system as mocha makes use of it.
  2. 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.

  1. it() 
  2. describe() 
  3. beforeEach() 
  4. afterEach()
  5. before()
  6. after()

javascript




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




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 

javascript




// Using mongoose as a database
const mongoose = require('mongoose');
mongoose.Promise = global.Promise;
 
// The before() hook
before( (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 

javascript




// 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:

  1. Navigate into the directory where your test file is located and type the following command:
npm test
  1. 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.



Next Article
How to write a function in JavaScript ?
author
yathartharora
Improve
Article Tags :
  • JavaScript
  • Web Technologies
  • JavaScript-Misc

Similar Reads

  • CoffeeScript | Introduction
    CoffeeScript is a lightweight language that compiles JavaScript. It provides simple and easy-to-learn syntax avoiding the complex syntax of JavaScript. CoffeeScript is influenced by JavaScript, Ruby, YAML, Haskell, Perl, and Python and has influenced MoonScript, LiveScript, and JavaScript. In this t
    4 min read
  • What are Arguments in a Function ?
    Arguments in JavaScript functions are the input values passed to the function when it is called. Functions can accept zero or more arguments, which can be used within the function body to perform specific tasks or calculations. Uses of Arguments in FunctionsArguments allow functions to be customized
    2 min read
  • How to write a function in JavaScript ?
    JavaScript functions serve as reusable blocks of code that can be called from anywhere within your application. They eliminate the need to repeat the same code, promoting code reusability and modularity. By breaking down a large program into smaller, manageable functions, programmers can enhance cod
    4 min read
  • How to Learn Angular in 2024?
    ng new angular-component ng generate component Home ng generate service Home ng serve ng serve --open If you are familiar with these commands, or looking forward to working with these commands then you are in right direction towards the path of learning Angular. If you’re a passionate developer then
    9 min read
  • CoffeeScript Conditional Statements
    The CoffeeScript programming language is used to write a simpler syntax that compiles into JavaScript before getting executed. In any programming language, conditions play an important role in the execution of code in a particular sequence. In this article, we will see various conditional Statements
    5 min read
  • Top 7 Node.js Project Ideas For Beginners
    Node.js, a powerful JavaScript runtime built on Chrome's V8 engine, has become a cornerstone for developing scalable network applications. Its non-blocking, event-driven architecture makes it an ideal choice for server-side development. Here are 7 project ideas to help beginners learn the fundamenta
    6 min read
  • What is CoffeeScript Debugging ?
    While writing codes, It is a very common thing to get an error. The errors can be of many types like - logical errors, runtime errors, syntax errors, compilation errors, etc. Solving those errors is Debugging. Basically, Debugging is a part of the Software testing process which helps in evaluating a
    6 min read
  • Node Exercises, Practice Questions and Solutions
    Node Exercise: Explore interactive quizzes, track progress, and enhance coding skills with our engaging portal. Ideal for beginners and experienced developers, Level up your Node proficiency at your own pace. Start coding now! #content-iframe { width: 100%; height: 500px;} @media (max-width: 768px)
    4 min read
  • Next.js Exercises, Practice Questions and Solutions
    Next.js Online Practice Question: Explore Next.js Exercises, an interactive practice set to upscale your Next.js skills, track progress, and enhance coding skills with our engaging portal. Ideal for beginners and experienced developers, Level up Next.js proficiency at your own pace. Start coding now
    3 min read
  • How to convert CoffeeScript code in JavaScript ?
    CoffeeScript is a lightweight programming language that compiles into JavaScript. It provides simple and easy-to-learn syntax, avoiding the complex syntax of JavaScript. CoffeeScript is influenced by JavaScript, Ruby, YAML, Haskell, Perl, and Python and has influenced MoonScript, LiveScript, and Jav
    2 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences