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
  • NodeJS Tutorial
  • NodeJS Exercises
  • NodeJS Assert
  • NodeJS Buffer
  • NodeJS Console
  • NodeJS Crypto
  • NodeJS DNS
  • NodeJS File System
  • NodeJS Globals
  • NodeJS HTTP
  • NodeJS HTTP2
  • NodeJS OS
  • NodeJS Path
  • NodeJS Process
  • NodeJS Query String
  • NodeJS Stream
  • NodeJS String Decoder
  • NodeJS Timers
  • NodeJS URL
  • NodeJS Interview Questions
  • NodeJS Questions
  • Web Technology
Open In App
Next Article:
How to run a node.js application permanently ?
Next article icon

Unit Testing of Node.js Application

Last Updated : 29 Jul, 2020
Comments
Improve
Suggest changes
Like Article
Like
Report

Node.js is a widely used javascript library based on Chrome’s V8 JavaScript engine for developing server-side applications in web development.

Unit Testing is a software testing method where individual units/components are tested in isolation. A unit can be described as the smallest testable part of code in an application. Unit testing is generally carried out by developers during the development phase of an application.

In Node.js there are many frameworks available for running unit tests. Some of them are:

  • Mocha
  • Jest
  • Jasmine
  • AVA

Unit testing for a node application using these frameworks:

  1. Mocha: Mocha is an old and widely used testing framework for node applications. It supports asynchronous operations like callbacks, promises, and async/await. It is a highly extensible and customizable framework that supports different assertions and mocking libraries.

    To install it, open command prompt and type the following command:

      # Installs globally  npm install mocha -g    # installs in the current directory  npm install mocha --save-dev  

    How to use Mocha?
    In order to use this framework in your application:

    1. Open the root folder of your project and create a new folder called test in it.
    2. Inside the test folder, create a new file called test.js which will contain all the code related to testing.
    3. open package.json and add the following line in the scripts block.
      "scripts": {  "test": "mocha --recursive --exit"  }

    Example:




    // Requiring module
    const assert = require('assert');
      
    // We can group similar tests inside a describe block
    describe("Simple Calculations", () => {
      before(() => {
        console.log( "This part executes once before all tests" );
      });
      
      after(() => {
        console.log( "This part executes once after all tests" );
      });
          
      // We can add nested blocks for different tests
      describe( "Test1", () => {
        beforeEach(() => {
          console.log( "executes before every test" );
        });
          
        it("Is returning 5 when adding 2 + 3", () => {
          assert.equal(2 + 3, 5);
        });
      
        it("Is returning 6 when multiplying 2 * 3", () => {
          assert.equal(2*3, 6);
        });
      });
      
      describe("Test2", () => {
        beforeEach(() => {
          console.log( "executes before every test" );
        });
          
        it("Is returning 4 when adding 2 + 3", () => {
          assert.equal(2 + 3, 4);
        });
      
        it("Is returning 8 when multiplying 2 * 4", () => {
          assert.equal(2*4, 8);
        });
      });
    });
     
     

    Copy the above code and paste it in the test.js file that we have created before. To run these tests, open the command prompt in the root directory of the project and type the following command:

    npm run test

    Output:

    What is Chai?
    Chai is an assertion library that is often used alongside Mocha. It can be used as a TTD (Test Driven Development) / BDD (Behavior Driven Development) assertion library for Node.js that can be paired up with any testing framework based on JavaScript. Similar to assert.equal() statement in the above code, we can use Chai to write tests like English sentences.

    To install it, open the command prompt in the root directory of the project and type the following command:

    npm install chai

    Example:




    const expect = require('chai').expect;
      
    describe("Testing with chai", () => {
        it("Is returning 4 when adding 2 + 2", () => {
          expect(2 + 2).to.equal(4);
        });
      
        it("Is returning boolean value as true", () => {
          expect(5 == 5).to.be.true;
        });
          
        it("Are both the sentences matching", () => {
          expect("This is working").to.equal('This is working');
        });
     });
     
     

    Output:

  2. Jest: Jest is also a popular testing framework that is known for its simplicity. It is developed and maintained regularly by Facebook. One of the key features of jest is it is well documented, and it supports parallel test running i.e. each test will run in their own processes to maximize performance. It also includes several features like test watching, coverage, and snapshots.

    You can install it using the following command:

    npm install --save-dev jest

    Note: By default, Jest expects to find all the test files in a folder called “__tests__” in your root folder.

    Example:




    describe("Testing with Jest", () => {
      test("Addition", () => {
        const sum = 2 + 3;
        const expectedResult = 5;
        expect(sum).toEqual(expectedResult);
      });
        
      // Jest also allows a test to run multiple
      // times using different values
      test.each([[1, 1, 2], [-1, 1, 0], [3, 2, 6]])(
      'Does %i + %i equals %i', (a, b, expectedResult) => {
        expect(a + b).toBe(expectedResult);
      });
    });
     
     

    Output:

  3. Jasmine: Jasmine is also a powerful testing framework and has been around since 2010. It is a Behaviour Driven Development(BDD) framework for testing JavaScript code. It is known for its compatibility and flexibility with other testing frameworks like Sinon and Chai. Here test files must have a specific suffix (*spec.js).

    You can install it using the following command:

    npm install jasmine-node

    Example:




    describe("Test", function() {
      it("Addition", function() {
        var sum = 2 + 3;
        expect(sum).toEqual(5);
      });
    });
     
     
  4. AVA: AVA is a relatively new minimalistic framework that allows you to run your JavaScript tests concurrently. Like the Jest framework, it also supports snapshots and parallel processing which makes it relatively fast compared to other frameworks. The key features include having no implicit globals and built-in support for asynchronous functions.

    You can install it using the following command:

    npm init ava

    Example:




    import test from 'ava';
      
    test('Addition', t => {
      t.is(2 + 3, 5);
    });
     
     


Next Article
How to run a node.js application permanently ?
author
dark_coder88
Improve
Article Tags :
  • JavaScript
  • Node.js
  • Web Technologies
  • Node.js-Misc

Similar Reads

  • Explain the working of Node.js
    Welcome to the world of Node.js, an open-source runtime environment that has transformed the landscape of backend development. Traditionally, JavaScript was confined for frontend development, powering user interactions on the browser. However, with the advent of Node.js, JavaScript has broken free f
    4 min read
  • Types of API functions in Node.js
    Node.js, known for its asynchronous and event-driven architecture, is a popular choice for building scalable server-side applications. One of its primary uses is to create and manage APIs (Application Programming Interfaces). APIs allow different software systems to communicate and share data with e
    6 min read
  • How to run a node.js application permanently ?
    NodeJS is a runtime environment on a V8 engine for executing JavaScript code with some additional functionality that allows the development of fast and scalable web applications but we can't run the Node.js application locally after closing the terminal or Application, to run the nodeJS application
    2 min read
  • Deploying Node.js Applications
    Deploying a NodeJS application can be a smooth process with the right tools and strategies. This article will guide you through the basics of deploying NodeJS applications. To show how to deploy a NodeJS app, we are first going to create a sample application for a better understanding of the process
    5 min read
  • How to build Video Streaming Application using Node.js ?
    In this article, we are going to create a Video Streaming Application. A video streaming application is used to stream or play video, like a simple video player. Functionality: Play video Approach: We are going to use express for this project, and create a server file app.js then we will create an H
    4 min read
  • Node First Application
    NodeJS is widely used for building scalable and high-performance applications, particularly for server-side development. It is commonly employed for web servers, APIs, real-time applications, and microservices. Perfect for handling concurrent requests due to its non-blocking I/O model.Used in buildi
    4 min read
  • Optimize Your NestJS Applications
    NestJS is a popular framework for building scalable and maintainable server-side applications with Node.js. NestJS offers many out-of-the-box features to enhance performance. In this article, we will cover several key techniques, tools, and best practices to ensure your NestJS application runs effic
    4 min read
  • How do you debug Node applications?
    Debugging is a crucial aspect of software development, including NodeJS applications. NodeJS offers several built-in debugging options and tools to help developers identify and fix issues efficiently. Let's explore some common techniques and tools for debugging NodeJS applications. Using console.log
    3 min read
  • Design First Application Using Express
    In NodeJS, the task of designing a server was very difficult, but after the introduction of ExpressJS, which is a lightweight web application framework for NodeJS used to build the back-end of web applications relatively fast and easily. PrerequisitesTo get started with an ExpressJS application, Nod
    5 min read
  • How to Deploy Node.js Express Application on Render ?
    Deploying a Node.js Express application on Render is straightforward and involves a few key steps to set up your project, configure deployment settings, and manage your application on the Render platform. Render provides an easy-to-use platform for deploying applications, offering features like auto
    4 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