0
0
Node.jsframework~5 mins

Assert module for assertions in Node.js

Choose your learning style9 modes available
Introduction

The Assert module helps check if your code works as expected by testing values. It stops your program if something is wrong.

When you want to test if a function returns the right result.
When you want to check if two values are equal during development.
When you want to catch errors early by verifying conditions.
When writing simple tests without extra tools.
When debugging to confirm assumptions in your code.
Syntax
Node.js
import assert from 'assert';

assert.strictEqual(actual, expected, 'optional error message');
Use strictEqual to check if two values are exactly the same.
If the assertion fails, the program throws an error and stops.
Examples
This checks if 5 equals 5. It passes silently because they are equal.
Node.js
import assert from 'assert';

assert.strictEqual(5, 5);
This throws an error with the message 'Strings do not match' because the strings differ.
Node.js
import assert from 'assert';

assert.strictEqual('hello', 'world', 'Strings do not match');
assert.ok checks if the value is truthy. Here it passes because true is truthy.
Node.js
import assert from 'assert';

assert.ok(true, 'This should not fail');
Sample Program

This program defines a simple add function. It uses assert.strictEqual to check if adding 2 and 3 equals 5. If the check passes, it prints 'Test passed!'. If it fails, it stops with an error.

Node.js
import assert from 'assert';

function add(a, b) {
  return a + b;
}

const result = add(2, 3);
assert.strictEqual(result, 5, 'Addition result should be 5');
console.log('Test passed!');
OutputSuccess
Important Notes

Assertions help catch bugs early by verifying your code behaves as expected.

Use clear messages in assertions to understand failures quickly.

Assertions are mainly for development and testing, not for handling user errors.

Summary

The Assert module checks if values meet conditions and stops code if not.

Use it to test your code during development simply and quickly.

It helps find mistakes early before your program runs fully.