Assert module in nodeJS
Introduction
- The assert module provides a set of assertion functions for verifying invariants
- We will learn the most used assertion functions
Common assertion functions
- assert.deepEqual()
- assert.equal()
- assert.notDeepEqual()
- assert.notEqual()
assert.deepEqual()
Tests for deep equality between the actual and expected parameters
Comparison details
- Primitive values are compared with the Abstract Equality Comparison ( == ) with the exception of NaN.
- It is treated as being identical in case both sides are NaN.
- Type tags of objects should be the same.
- Only enumerable own properties are considered.
- Error names and messages are always compared, even if these are not enumerable properties
- Object wrappers are compared both as objects and unwrapped values.
- Object properties are compared unordered.
- Map keys and Set items are compared unordered.
- Recursion stops when both sides differ or both sides encounter a circular reference
- Implementation does not test the [[Prototype]] of objects.
- Symbol properties are not compared
- WeakMap and WeakSet comparison does not rely on their values
const assert = require('assert') console.log(assert.deepEqual({ a: 1 }, { a: 1 })); // OK console.log(assert.deepEqual({ a: 1 }, { a: 2 })); // ERR_ASSERTION
assert.equal()
Tests shallow, coercive equality between the actual and expected parameters using the Abstract Equality Comparison ( == )
const assert = require('assert') assert.equal(1, 1); // OK assert.equal(1, 2); // ERR_ASSERTION
assert.notDeepEqual()
Tests for any deep inequality. Opposite of assert.deepEqual().
const assert = require('assert') assert.notDeepEqual({ a: 1 }, { a: 1 }); // ERR_ASSERTION assert.notDeepEqual({ a: 1 }, { a: 2 }); // OK
assert.notEqual()
Tests shallow, coercive inequality with the Abstract Equality Comparison (!= ).
const assert = require('assert') assert.notEqual(1, 1); // ERR_ASSERTION assert.notEqual(1, 2); // OK