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:
Node.js assert.deepStrictEqual() Function
Next article icon

Node.js assert() Function

Last Updated : 19 Aug, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report

The assert() function in Node.js is used for testing and verifying assumptions in your code. It is part of the built-in assert module, which provides a set of assertion functions to perform various checks and validations.

Node assert Function

In assert() function, if the value is not truth, then a AssertionError is thrown with a message property set equal to the value of the message parameter. 

Syntax:

assert(value[, message])

Parameters: This function accepts the following parameters as mentioned above and described below:

  • value: This parameter holds the expression that needs to be evaluated. It is of any type.
  • message: This parameter holds the error message of string or error type. It is an optional parameter.

Return Value: This function returns assertion error of object type.

Installation of assert module (optional):

You can visit the link to Install assert module. You can install this package by using this command.

npm install assert

Note: Installation is an optional step as it is inbuilt Node.js module.

After installing the assert module, you can check your assert version in command prompt using the command.

npm version assert

After that, you can just create a folder and add a file for example, index.js as shown below.

Features:

  • Part of Node.js’s standard library, so no additional installation is required.
  • Allows for custom error messages and conditions.
  • Supports a wide range of assertion types for different testing needs.

Example 1: This example uses Node.js’s assert module to assert a falsy value (0), catches the resulting error, and logs it.

JavaScript
// Filename: index.js   // Requiring the module const assert = require('assert').strict;  // Function call try { 	assert(0) } catch(error) { 	console.log("Error:", error) } 

Steps to run the program:

  • The project structure will look like this:
  • Run index.js file using below command:
node index.js

Output:

Error: AssertionError [ERR_ASSERTION]: The expression evaluated to a falsy value: assert(0) at Object. (C:\Users\Lenovo\Downloads\index.js:6:5) at Module._compile (internal/modules/cjs/loader.js:1138:30) at Object.Module._extensions..js (internal/modules/cjs/loader.js:1158:10) at Module.load (internal/modules/cjs/loader.js:986:32) at Function.Module._load (internal/modules/cjs/loader.js:879:14) at Function.executeUserEntryPoint [as runMain] (internal/modules/run_main.js:71:12) at internal/main/run_main_module.js:17:47 { generatedMessage: true, code: ‘ERR_ASSERTION’, actual: 0, expected: true, operator: ‘==’ }

Example 2: This example uses Node.js’s assert module to assert a truthy value (1), and if no error occurs, it logs “No Error Occurred”; otherwise, it catches and logs the error.

JavaScript
// Filename - index.js  // Requiring the module const assert = require('assert').strict;  // Function call try { 	assert(1) 	console.log("No Error Occurred") } catch(error) { 	console.log("Error:", error) } 

Steps to run the program:

The project structure will look like this:

Run index.js file using below command:

node index.js

Output:

No Error Occurred

Summary

The assert() function in Node.js is a fundamental tool for verifying code correctness. It helps catch errors by testing conditions and ensuring that values meet expected criteria. Using assertions can improve code quality and facilitate debugging and testing processes.

Reference: https://nodejs.org/dist/latest-v12.x/docs/api/assert.html#assert_assert_value_message


Next Article
Node.js assert.deepStrictEqual() Function
author
gouravhammad
Improve
Article Tags :
  • Node.js
  • Web Technologies
  • Node.js-Methods
  • NodeJS-assert

Similar Reads

  • Node.js assert() Function
    The assert() function in Node.js is used for testing and verifying assumptions in your code. It is part of the built-in assert module, which provides a set of assertion functions to perform various checks and validations. Node assert FunctionIn assert() function, if the value is not truth, then a As
    3 min read
  • Node.js assert.deepStrictEqual() Function
    The assert module provides a set of assertion functions for verifying invariants. The assert.deepStrictEqual() function tests for deep equality between the actual and expected parameters. If the condition is true it will not produce an output else an assertion error is raised. Syntax: assert.deepStr
    2 min read
  • Node.js assert.doesNotThrow() Function
    The assert module provides a set of assertion functions for verifying invariants. The assert.doesNotThrow() function asserts that the function fn does not throw an error. Syntax: assert.doesNotThrow(fn[, error][, message]) Parameters: This function accepts the following parameters as mentioned above
    3 min read
  • Node.js assert.equal() Function
    The assert module provides a set of assertion functions for verifying invariants. The assert.equal() function tests for equality between the actual and the expected parameters. If the condition is true it will not produce an output else an assertion error is raised. Syntax: assert.equal(actual, expe
    2 min read
  • Node.js assert.fail() Function
    The assert module provides a set of assertion functions for verifying invariants. The assert.fail() function throws an AssertionError with the provided the error message or with a default error message. Syntax: assert.fail([message]) Parameters: This function accepts following parameters as mentione
    2 min read
  • Node.js assert.ifError() Function
    The assert module provides a set of assertion functions for verifying invariants. The assert.ifError() function throws value if value is not undefined or null. When testing the error argument in callbacks, this function is very useful. Syntax:  assert.ifError(value) value: This parameter holds the a
    2 min read
  • Node.js assert.match() Function
    The assert module provides a set of assertion functions for verifying invariants. The assert.match() function expects the string input to match the regular expression. If the condition is true it will not produce an output else an assertion error is raised. Syntax: assert.match(string, regexp[, mess
    2 min read
  • Node.js assert.notDeepEqual() Function
    The assert module provides a set of assertion functions for verifying invariants. The assert.notDeepEqual() function tests deep strict inequality between the actual and the expected parameters. If the condition is true it will not produce an output else an assertion error is raised.Syntax: assert.no
    2 min read
  • Node.js assert.notDeepStrictEqual() Function
    The assert module provides a set of assertion functions for verifying invariants. The assert.notDeepStrictEqual() function tests for deep strict inequality. If the condition is true it will not produce an output else an assertion error is raised. Syntax: assert.notDeepStrictEqual(actual, expected[,
    2 min read
  • Node.js assert.notEqual() Function
    The assert module provides a set of assertion functions for verifying invariants. The assert.notEqual() function tests strict inequality between the actual and the expected parameters. If the condition is true it will not produce an output else an assertion error is raised. Syntax: assert.notEqual(a
    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