node:assert module provides a set of assertion functions for verifying invariants in your code. It’s primarily used for testing but can also be used for runtime validation.
Installation
Strict vs Legacy Mode
Strict mode (recommended) uses strict equality (===) and is more predictable:
==) and may have surprising results:
Basic Assertions
assert(value[, message])
Alias forassert.ok(). Tests if value is truthy.
assert.ok(value[, message])
Tests if value is truthy.assert.fail([message])
Throws an AssertionError immediately.Equality Assertions
assert.equal(actual, expected[, message])
Tests shallow, coercive equality with== (legacy) or === (strict).
assert.notEqual(actual, expected[, message])
Tests shallow, coercive inequality.assert.strictEqual(actual, expected[, message])
Tests strict equality using===.
assert.notStrictEqual(actual, expected[, message])
Tests strict inequality using!==.
Deep Equality Assertions
assert.deepEqual(actual, expected[, message])
Tests deep equality between objects, arrays, and primitives.assert.notDeepEqual(actual, expected[, message])
Tests deep inequality.assert.deepStrictEqual(actual, expected[, message])
Tests deep strict equality (recommended for objects).assert.notDeepStrictEqual(actual, expected[, message])
Tests deep strict inequality.Error Assertions
assert.throws(fn[, error][, message])
Expects the function to throw an error.assert.doesNotThrow(fn[, error][, message])
Expects the function not to throw an error.assert.rejects(asyncFn[, error][, message])
Expects a promise or async function to reject.assert.doesNotReject(asyncFn[, error][, message])
Expects a promise or async function not to reject.Pattern Matching
assert.match(string, regexp[, message])
Tests if string matches the regular expression.assert.doesNotMatch(string, regexp[, message])
Tests if string does not match the regular expression.Custom Assertions
assert.ifError(value)
Throws value if it’s notnull or undefined. Useful for testing error-first callbacks.
Error Messages
All assertion methods accept an optional message parameter:Common Testing Patterns
Testing Object Properties
Testing Arrays
Testing Async Functions
Testing Error Conditions
Validation Functions
AssertionError Class
All assertion failures throw anAssertionError:
Best Practices
- Use strict mode - More predictable and catches more bugs
- Use descriptive messages - Make failures easier to debug
- Use deepStrictEqual for objects - More reliable than deepEqual
- Test both success and failure cases - Ensure error handling works
- Use async assertions for promises - Properly handle async errors
Related Modules
- util - Utility functions
- Test runners: Mocha, Jest, Vitest, Node.js built-in test runner