0
0
NodejsHow-ToBeginner · 3 min read

How to Use Assert Module in Node.js for Simple Testing

In Node.js, you use the assert module to check if values meet expectations by throwing errors when they don't. Import it with import assert from 'assert' and use functions like assert.strictEqual() to compare values and catch bugs early.
📐

Syntax

The assert module provides functions to test conditions. The most common is assert.strictEqual(actual, expected[, message]), which throws an error if actual is not strictly equal to expected. You import it using ES modules syntax.

  • actual: The value you want to test.
  • expected: The value you expect actual to be.
  • message: Optional error message if the assertion fails.
javascript
import assert from 'assert';

assert.strictEqual(actual, expected, 'Optional failure message');
💻

Example

This example shows how to use assert.strictEqual() to check if two values are equal. If they are not, Node.js throws an error and stops the program.

javascript
import assert from 'assert';

const sum = (a, b) => a + b;

// This will pass silently
assert.strictEqual(sum(2, 3), 5, 'Sum should be 5');

// This will throw an AssertionError
assert.strictEqual(sum(2, 2), 5, 'Sum should be 5');
Output
AssertionError [ERR_ASSERTION]: Sum should be 5 at file:///path/to/file.js:8:1
⚠️

Common Pitfalls

Common mistakes include:

  • Using assert.equal() instead of assert.strictEqual(), which does loose comparison and can hide bugs.
  • Not importing assert correctly in ES modules.
  • Expecting assertions to return values; they throw errors instead.
javascript
import assert from 'assert';

// Wrong: uses loose equality, can pass unexpectedly
assert.equal(1, '1'); // passes

// Right: uses strict equality, catches type differences
assert.strictEqual(1, '1'); // throws AssertionError
Output
AssertionError [ERR_ASSERTION]: Expected values to be strictly equal: 1 !== '1' at file:///path/to/file.js:7:1
📊

Quick Reference

FunctionPurposeThrows Error When
assert.strictEqual(actual, expected)Checks if actual === expectedValues are not strictly equal
assert.notStrictEqual(actual, expected)Checks if actual !== expectedValues are strictly equal
assert.ok(value)Checks if value is truthyValue is falsy
assert.throws(fn)Checks if function throws an errorFunction does not throw
assert.doesNotThrow(fn)Checks if function does not throwFunction throws an error

Key Takeaways

Import the assert module using ES module syntax: import assert from 'assert'.
Use assert.strictEqual() for strict equality checks to avoid hidden bugs.
Assertions throw errors when conditions fail, stopping execution.
Avoid assert.equal() as it uses loose equality and can cause false positives.
Use assert functions to write simple tests and catch bugs early in Node.js.