Working with Assert Module
1. Using assert() for Truthy Checks
Note: Always import
assert/strict — uses === instead of ==.2. Using assert.ok for Boolean Checks
| API | Equivalent |
|---|---|
assert.ok(x, msg) | Same as assert(x, msg) |
3. Using assert.strictEqual (===)
| Check | Behavior |
|---|---|
strictEqual(a,b) | Throws if a !== b |
| NaN handling | NaN === NaN in strict mode (Object.is) |
4. Using assert.notStrictEqual (!==)
| API | Throws When |
|---|---|
notStrictEqual(a,b) | a === b |
5. Using assert.deepStrictEqual
Example
assert.deepStrictEqual({ a: [1, 2] }, { a: [1, 2] }); // OK
assert.deepStrictEqual(new Map([["a",1]]), new Map([["a",1]]));
| Compares | Detail |
|---|---|
| Own enumerable props | Recursively |
| Prototypes | Must match |
| Symbols | Compared |
6. Using assert.notDeepStrictEqual
| API | Throws When |
|---|---|
notDeepStrictEqual(a,b) | Deep equal |
7. Using assert.throws (error testing)
Example
assert.throws(() => JSON.parse("nope"), {
name: "SyntaxError",
message: /Unexpected token/
});
8. Using assert.rejects
9. Using assert.doesNotThrow
| API | Use |
|---|---|
doesNotThrow(fn) | Asserts no synchronous throw |
doesNotReject(promise) | Async variant |
10. Using assert.ifError
| API | Behavior |
|---|---|
assert.ifError(err) | Throws if err is truthy |
| Use case | Node-style callbacks |
11. Using assert.match
| API | Use |
|---|---|
assert.match(str, /pattern/) | Throws if no match |
assert.doesNotMatch | Reverse |