What is Assertion in Node.js
Assert is a module in Nodejs which provides a set of assertion methods which helps in the verifying of invariants. The implementation is called assertion in Node.js.
It can also be used with Strict Mode for the verifying of invariants
How to include in application?
const assert = require('assert');
If any error occurs assert.AssertionError is the returned class object which contains following information:
- message <string> If provided, the error message is set to this value.
- actual <any> The actual property on the error instance.
- expected <any> The expected property on the error instance.
- operator <string> The operator property on the error instance.
- stackStartFn <Function> If provided, the generated stack trace omits frames before this function.
Methods of Assert module for Equality Comparison in Legacy Mode:
assert.deepEqual()
assert.equal()
assert.notDeepEqual()
assert.notEqual()
Methods of Assert module for Equality Comparison in Strict Mode:
assert.strictEqual();
assert.deepStrictEqual();
assert.notDeepStrictEqual();
assert.notStrictEqual();
Example to use:
const assert = require('assert');
// Create a dummy AssertionError to compare with the original error
const { message } = new assert.AssertionError({
actual: 1,
expected: 2,
operator: 'strictEqual'
});
// use assets to verify error output:
try {
assert.strictEqual(1, 2);
} catch (err) {
assert(err instanceof assert.AssertionError);
assert.strictEqual(err.message, message);
assert.strictEqual(err.name, 'AssertionError');
assert.strictEqual(err.actual, 1);
assert.strictEqual(err.expected, 2);
assert.strictEqual(err.code, 'ERR_ASSERTION');
assert.strictEqual(err.operator, 'strictEqual');
assert.strictEqual(err.generatedMessage, true);
}
Enable Strict mode:
const assert = require('assert').strict;
When we enable the strict mode then ,Legacy mode methods will behave as of strict methods:
- assert.deepEqual() will beahave same as assert.deepStrictEqual();
- assert.equal() will beahave same as assert.strictEqual();
- assert.notDeepEqual() will beahave same as assert.notDeepStrictEqual();
- assert.notEqual() will beahave same as assert.notStrictEqual();