assert.rejects() function in Node.js

Node.jsJavascriptWeb DevelopmentFront End Technology

The assert module provides a bunch of different functionalities that are used for function assertion. The assert.rejects function will wait for the passed async function 'asyncfn' promise. If asyncfn is a function, it will immediately call this function and will wait for its returned promise to complete. It will then check that promise to get rejected.

Syntax

assert.rejects(asyncfn, [error], [message])

Parameters

The above parameters are described as below −

  • value – This is an async function which will throw errors synchronously.

  • error – This parameter can hold Class, Regular Expression, Validation function or an object where each property will be tested. (Optional Parameter)

  • message – This is an optional parameter. This is a user defined message printed when the function is executed.

Installing the Assert Module

npm install assert

The assert module is an inbuilt Node.js module, so you can skip this step as well. You can check the assert version using the following command to get the latest assert module.

npm version assert

Importing the module in your function

const assert = require("assert").strict;

Example

Create a file with the name – assertRejects.js and copy the below code snippet. After creating the file use the below command to run this code.

node assertRejects.js

assertRejects.js

/// Importing the module
const assert = require('assert').strict;

(async () => {
   assert.strictEqual(21,20)
   await assert.rejects(
   async () => {
      throw new TypeError('Value passed is Incorrect !');
   },
   (err) => {
      assert.strictEqual(err.name, 'TypeError');
      assert.strictEqual(err.message, 'Incorrect value');
      return true;
   }
   ).then(() => {
      console.log("This is a reject demp")
   });
})();

Output

C:\home\node>> node assertRejects.js
(node:259525) UnhandledPromiseRejectionWarning: AssertionError
[ERR_ASSERTION]: Input A expected to strictly equal input B:
+ expected - actual
- 21
+ 20
   at /home/node/test/assert.js:5:9
   at Object. (/home/node/test/assert.js:18:3)
   at Module._compile (internal/modules/cjs/loader.js:778:30)
   at Object.Module._extensions..js (internal/modules/cjs/loader.js:789:10)
   at Module.load (internal/modules/cjs/loader.js:653:32)
   at tryModuleLoad (internal/modules/cjs/loader.js:593:12)
   at Function.Module._load (internal/modules/cjs/loader.js:585:3)
   at Function.Module.runMain (internal/modules/cjs/loader.js:831:12)
   at startup (internal/bootstrap/node.js:283:19)
   at bootstrapNodeJSCore (internal/bootstrap/node.js:623:3)
(node:259525) UnhandledPromiseRejectionWarning: Unhandled promise rejection.
This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). (rejection id: 1)
(node:259525) [DEP0018] DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections that are not handled will terminate the Node.js process with a non-zero exit code.

Example

Let's take a look at one more example.

// Importing the module
const assert = require('assert').strict;

(async () => {
   assert.strictEqual(21,21)
   await assert.rejects(
      async () => {
         throw new TypeError('Value passed is Incorrect !');
      },
      (err) => {
         assert.strictEqual(err.name, 'TypeError');
         assert.strictEqual(err.message, 'Value passed is Incorrect !');
         return true;
      }
      ).then(() => {
         console.log("This is a reject demo success")
   });
})();

Output

C:\home\node>> node assertRejects.js
This is a reject demo success
raja
Published on 20-May-2021 11:41:11
Advertisements