Monday, December 9, 2024
HomeJavaScriptWorking with the Node.js assert Library

Working with the Node.js assert Library


Sep 7, 2022

Node.js’ assert.equal(a, b) operate will throw an error if a != b.
assert.equal(a, b) is equal assert(a, b).
Asserts are mostly used for testing, however will also be used as a extra concise various to an if assertion in your code.

const assert = require('assert');

const a = 1;
const b = 2;
assert.equal(a, b); 
assert(a, b); 
assert.equal(a, a); 
assert(a, a); 

strictEqual()

Whereas equal(a,b) throws an error if a != b, strictEqual(a, b) throws an error if a !== b.
This is extra on the distinction between !== and != in JavaScript

const assert = require('assert');

const a = 1;
const b = '1';

assert.equal(a, b); 
assert.strictEqual(a, b); 

deepEqual() && deepStrictEqual()

These features do a deep comparability of objects to ensure they’ve the identical keys and values.
Solely use these features with POJOs, this won’t work with MongoDB ObjectIds.

const assert = require('assert');

const obj = { a: 1, b: 2, c: 3};
const pojo = { a: '1', b: '2', c: '3'};
const entry = { a: 1, b: 2, c: 3 };

assert.deepEqual(obj, pojo); 
assert.deepStrictEqual(obj, entry); 
assert.deepStrictEqual(obj, pojo); 

throws()

Use this operate if you wish to assert that the operate you might be testing ought to throw an error with a selected message.
The primary parameter is a operate and the second parameter is a daily expression that you really want the error message to match.

const assert = require('assert');

operate run() {
  assert.throws(() => { take a look at(); }, /TypeError: Incorrect Worth/);
}

operate take a look at() {
  throw new TypeError('Incorrect Worth');
}

run();

rejects()

This features equally to throws(), however is used with guarantees.
Use this with async features.

const assert = require('assert');

async operate run() {
 await assert.rejects(async () => { await take a look at(); }, /TypeError: Incorrect Worth/);
}

async operate take a look at() {
  throw new TypeError('Incorrect Worth')
}

run();

Extra Node Tutorials

RELATED ARTICLES

LEAVE A REPLY

Please enter your comment!
Please enter your name here

Most Popular

Recent Comments