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:
npm init
Next article icon

jest - npm

Last Updated : 17 Oct, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report

Jest is a JavaScript-based testing framework that is prominently used to ensure the correctness of the Javascript codebase. It is widely based on production-oriented projects where we need testing things to be done so that no code or snippets get pushed by mistake.

Majorly used with React applications but is versatile enough to handle Javascript projects. Created by Facebook, Jest makes the testing simple by providing features like Zero config setup, snapshot testing, and powerful mocking capabilities. Jest can also be put in the CI/CD pipelines in the GitHub Actions or any other things to make the environment more and more automated to compete with the manual checking error. As it is built on the Node.js platform, Jest is available via the npm package manager.

These are the following topics that we are going to discuss:

Table of Content

  • Features of Jest
  • Performing Basic Test
  • Asynchronous Testing
  • Conclusion

Features of Jest

Some of the cool and notable features are as follows:

  • Zero Configuration: Jest is easy to set up with no need for entertaining or exclusive configurations.
  • Snapshots: Jest works by capturing our components output and in the future comparing the future outputs test runs with the current one to maintain consistency throughout the development.
  • Mocking: Jest allows us to mock the functions and modules, making it more simple to isolate components during testing.
  • Asynchronous Testing: Jest supports the asynchronous code with async/await, Promises, or callback functions to avoid the NullExceptionError.
  • Parallel Testing: Jest uses the power of Parallel running to optimize performance.
  • Code Coverage: Jest provides powerful code coverage reports generations to help us by ensuring that our tests cover all the important parts of our codebase simultaneously.

Performing Basic Test

Steps to run the test:

  • First install Jest by running:
npm install --save-dev jest
  • Add the following line to your existing package.json to enable running the test with the jest framework:
"scripts": {
"test": "jest"
}
  • Let us write a basic and simple test to check if a function returns the correct output or not.
  • Write this code in your files.
JavaScript
// sum.js function sum(a, b) {     return a + b; } module.exports = sum; 
JavaScript
// sum.test.js const sum = require('./sum');  test('adds 1 + 2 to equal 3', () => {     expect(sum(1, 2)).toBe(3); }); 
  • Run the tests using the following command:
npm test

Output:

Test-Passed
Test Passed

Asynchronous Testing

Testing the asynchronous code with Jest is straightforward. Here lets explore this with an example of promise:

  • First install the jest as the dev dependencies.
npm install --save-dev jest
  • and then write the following line as the test script in the package.json file
"scripts": {
"test": "jest"
}

Example: This example shows the jest test on the asynchronous function.

JavaScript
// asyncFunction.js const fetchData = () => {     return new Promise((resolve) => {         setTimeout(() => {             resolve('data');         }, 1000);     }); };  module.exports = fetchData; 
JavaScript
// asyncFunction.test.js const fetchData = require('./asyncFunction');  test('fetches data correctly', async () => {     const data = await fetchData();     expect(data).toBe('data'); }); 


asyncFunction.js

  • The fetchData function returns a promise that resolves with the string 'data' after a 1-second delay usin setTimeOut.

asyncFunction.test.js

  • The test imports the fetchData and uses the Jest framework's test function to check if the fetch is working correctly or not by returning the data. The async keyword allows us to await the promise, ensuring the test waits for the fetchdata results before using except to comapre it with 'data'.
Async-Function-example
Async Function testing example

Conclusion

Jest is a powerful and a easy-to-use tetsing framework used for the javascript based applications and also for the react based applications specifically. It requires zero configurations setup, extensive feature set including mocking, snapshot testing, and also parallel execution, making it an excellent choice for the developers community more productive. Jest helps individual to make sure that their code behaves a s expected while providing fast feedbacks.


Next Article
npm init
author
gautam_rana
Improve
Article Tags :
  • Web Technologies
  • Node.js
  • Node-npm

Similar Reads

  • NodeJS NPM
    NPM (Node Package Manager) is a package manager for NodeJS modules. It helps developers manage project dependencies, scripts, and third-party libraries. By installing NodeJS on your system, NPM is automatically installed, and ready to use. It is primarily used to manage packages or modules—these are
    7 min read
  • npm init
    NPM (Node Package Manager) is the default package manager for Node and is written entirely in JavaScript. Developed by Isaac Z. Schlueter, it was initially released on January 12, 2010. NPM manages all the packages and modules for Node and consists of command line client npm. NPM gets installed into
    3 min read
  • NPM Bootstrap
    NPM (Node Package Manager) is the default package manager for the NodeJS JavaScript runtime environment. It allows developers to easily manage project dependencies, share and reuse code, and automate various development tasks. npm is also used for installing, publishing, and managing third-party pac
    2 min read
  • NPM latest-version
    In Node.js development, staying up-to-date with the latest versions of npm packages is essential for ensuring security, stability, and access to new features. The npm latest version command provides a convenient way to check for the most recent version of a package available on the npm registry. In
    3 min read
  • What is NPM?
    NPM-Node Package Manager is the tool used by most developers within the JavaScript ecosystem. It manages packages and dependencies on behalf of an application in Node.js. It provides a lightweight way of installing, upgrading, configuring, and removing third-party libraries or modules that might be
    9 min read
  • npm run dev
    When working with Node.js and JavaScript projects, especially those involving frontend frameworks like React, Vue, or Next.js, you often encounter the command npm run dev. This command is pivotal for developers as it initiates the development server, enabling live reloading, hot module replacement,
    3 min read
  • depcheck NPM
    In modern JavaScript development, managing dependencies is important for maintaining efficient and clean codebases. The Depcheck is a popular npm package that helps us identify unused dependencies in Node.js projects. This article will guide us through the features of the Depcheck its usage and prac
    2 min read
  • npm edit command
    The command that can simplify the editing process of the project's files is npm edit. This command is useful for opening a file editor directly from the command line which allows users to make changes to the project’s files effortlessly. This article will provide a comprehensive overview of the npm
    3 min read
  • Next.js ESLint
    ESLint is a widely-used tool for identifying and fixing problems in JavaScript code. In Next.js projects, integrating ESLint helps ensure code quality and consistency by enforcing coding standards and catching errors early in the development process. In this article, we'll explore how to set up ESLi
    3 min read
  • npm install command
    The npm install command is one of the most commonly used commands in Node.js development. It allows developers to install dependencies from the package.json file as well as additional packages from the npm registry. This command simplifies the process of setting up a project managing dependencies an
    5 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