Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use nodejs Assert

Tags:

node.js

How to use the Assert in nodejs http://nodejs.org/api/assert.html

Tried

Assert.assert(1===1);

It throws following error

ReferenceError: Assert is not defined

How to use "assert". I am new to javascript and nodejs. The nodejs documentation explictly mentions some of the sections as a class Example:- http://nodejs.org/api/all.html#all_class_buffer_1. But Assert is not mentioned as a class. Then what is "Assert"?

like image 748
Talespin_Kit Avatar asked Sep 26 '14 13:09

Talespin_Kit


People also ask

Why assert use in node JS?

Definition and Usage The assert module provides a way of testing expressions. If the expression evaluates to 0, or false, an assertion failure is being caused, and the program is terminated. This module was built to be used internally by Node.

How do I import assert in node JS?

For Node 10 and above, it's better to use strict assert which can be imported as named import and renamed for convenience as assert : import { strict as assert } from 'assert'; assert. ok(true); assert(true);

Is assert equal deprecated?

In test codes, assert module's assert. equal are heavily used. It is legacy API and deprecated since Node. js v9.


2 Answers

Although assert is already included in nodejs installation. You still need to require it.

var assert = require('assert')

And then use as follows:

assert.equal(1,1);
like image 31
rishiag Avatar answered Nov 08 '22 14:11

rishiag


This module is used for writing unit tests for your applications, you can access it with require('assert').

var assert = require('assert');

assert.throws(
  function() {
    throw new Error("Wrong value");
  },
  function(err) {
    if ( (err instanceof Error) && /value/.test(err) ) {
      return true;
    }
  },
  "unexpected error"
);
like image 158
Rahul_Dabhi Avatar answered Nov 08 '22 12:11

Rahul_Dabhi