assert.ok() 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.ok tests whether the values are true or not. It will throw an assertion error if the value is not true.

Syntax

assert.ok(value, [message])

Parameters

The above parameters are described as below −

  • value – This parameter takes the value as input which will be checked by the assert ok() function.

  • 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 – assertOK.js and copy the below code snippet. After creating the file use the below command to run this code.

node assertOk.js

assertOK.js

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

try {
   //Checking the type of value
   assert.ok(typeof 21 === 'number');
   console.log("NO ERROR!")
} catch(error) {
   console.log("Error: ", error)
}

Output

C:\home\node>> node assertOk.js
NO ERROR!

Example

Let's take a look at one more example.

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

try {
   //Checking the type of value
   assert.ok(typeof 21 === 'string');
   console.log("NO ERROR!")
} catch(error) {
   console.log("Error: ", error)
}

Output

C:\home\node>> node assertOk.js
Error: { AssertionError [ERR_ASSERTION]: The expression evaluated to a falsy
value:
   assert.ok(typeof 21 === 'string')
      at Object. (/home/node/test/assert.js:6:9)
      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)
   generatedMessage: true,
   name: 'AssertionError [ERR_ASSERTION]',
   code: 'ERR_ASSERTION',
   actual: false,
   expected: true,
   operator: '==' }
raja
Published on 20-May-2021 11:38:41
Advertisements