Assert values and structural equality in Node.js
Quick answer
An assertion checks an expected condition and throws on failure. Node’s node:assert/strict provides explicit equality, deep equality and exception checks for tests.
How it works
Import require("node:assert/strict") in a CommonJS file. strictEqual compares values using Object.is semantics, including NaN equality and distinct signed zeros. deepStrictEqual compares supported nested structures with type and prototype distinctions; it is not JSON text comparison. A successful assertion returns undefined; a failed one throws AssertionError. Use throws with a callable to test a synchronous exception. Keep each expected result independent of the implementation under test.
Local examples
Run in Node.js v22.16.0 as a CommonJS script. No interactive debugger attached; actual ByteMind editor support is unverified.
(async () => {const assert=require("node:assert/strict");assert.strictEqual(NaN,NaN);try{assert.strictEqual(0,-0);}catch(e){console.log(e.name);}})()Expected console output:
AssertionErrorNaN equals itself by Object.is, whereas the two signed zeros differ.
Run in Node.js v22.16.0 as a CommonJS script. No interactive debugger attached; actual ByteMind editor support is unverified.
(async () => {const assert=require("node:assert/strict");const a={rows:[{qty:2}]},b={rows:[{qty:2}]};assert.deepStrictEqual(a,b);console.log(a===b,"pass");})()Expected console output:
false passStructural equality does not require the same reference.
Common mistakes
Do not test a returned object by reference when the contract is structural equality. Do not catch and silently discard an assertion failure.
Practice
Write a strict equality check for a primitive and a deep equality check for a nested inventory record; deliberately change the expected value to see a failure.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Assert values and structural equality in Node.js — Knowledge Check
Apply the concept and reason about local example output.
Which comparison is suitable for independently created equivalent plain data objects?
What does a failing strict assertion normally do?
Which comparison does Node strictEqual use?
What is the exact console output in Assert values and structural equality in Node.js example 1?
(async () => {const assert=require("node:assert/strict");assert.strictEqual(NaN,NaN);try{assert.strictEqual(0,-0);}catch(e){console.log(e.name);}})()What is the exact console output in Assert values and structural equality in Node.js example 2?
(async () => {const assert=require("node:assert/strict");const a={rows:[{qty:2}]},b={rows:[{qty:2}]};assert.deepStrictEqual(a,b);console.log(a===b,"pass");})()