#1 Data Analytics Program in India
₹2,499₹1,499Enroll Now
3 min read
Question 15 of 62easy

How to use the Assert module in Node.js?

Writing assertions for testing and validation.

What You'll Learn

  • Assert methods
  • Strict vs legacy mode
  • Common patterns

Assert Methods

code.jsJavaScript
const assert = require('assert/strict');

// Equality
assert.equal(1, 1);              // OK
assert.strictEqual(1, '1');      // Throws (strict)
assert.deepStrictEqual(
  { a: 1 },
  { a: 1 }
);                               // OK

// Truthiness
assert.ok(true);                 // OK
assert.ok(1);                    // OK
assert.ok('');                   // Throws

// Inequality
assert.notEqual(1, 2);           // OK
assert.notStrictEqual(1, '1');   // OK

// Throws
assert.throws(() => {
  throw new Error('fail');
}, Error);

assert.throws(
  () => { throw new Error('fail'); },
  { message: 'fail' }
);

// Does not throw
assert.doesNotThrow(() => {
  return 42;
});

// Rejects (for promises)
await assert.rejects(
  async () => { throw new Error('async fail'); },
  Error
);

Practical Example

code.jsJavaScript
function divide(a, b) {
  assert.ok(typeof a === 'number', 'a must be a number');
  assert.ok(typeof b === 'number', 'b must be a number');
  assert.notStrictEqual(b, 0, 'Cannot divide by zero');
  return a / b;
}

divide(10, 2);  // OK
divide(10, 0);  // Throws AssertionError

Custom Messages

code.jsJavaScript
assert.ok(false, 'This will be the error message');
// AssertionError: This will be the error message