Home ยป Node.js assert: A Comprehensive Tutorial

Node.js assert: A Comprehensive Tutorial

The assert module in Node.js is used for writing tests and performing assertions. An assertion is a way to check that something is as expected. If the condition being tested by the assert module fails, it throws an error.

This is helpful for unit testing, debugging, and validating the expected behavior of code.

In this tutorial, we will cover the most commonly used assert methods available in Node.js and provide practical examples demonstrating how to use them effectively.

1. Introduction to the assert Module

The assert module is a built-in Node.js module, so you don't need to install any external packages to use it. To start using it, simply require it in your Node.js code:

const assert = require('assert');

The assert module provides a number of assertion methods for testing conditions. These methods will throw an AssertionError if the condition fails.

2. Basic Example with assert.strictEqual()

The assert.strictEqual() method compares two values using the strict equality operator (===). If the values are not strictly equal, an error is thrown.

Example 1: Basic Assertion with assert.strictEqual()

const assert = require('assert');

const actualValue = 5;
const expectedValue = 5;

// Check if the actual value is equal to the expected value
assert.strictEqual(actualValue, expectedValue); // No error
console.log('Test passed!');  // This will run if the assertion does not fail

// Assertion will fail if values are not equal
assert.strictEqual(actualValue, 10);  // Throws AssertionError: 5 === 10

Explanation:

assert.strictEqual() checks if the actualValue is strictly equal to the expectedValue.

If the values are not equal (as in the second assertion), an AssertionError is thrown.

3. assert.deepStrictEqual() for Deep Comparison

assert.deepStrictEqual() is used to perform a deep comparison of objects and arrays. It checks if the structure and values inside two objects or arrays are equal.

Example 2: Using assert.deepStrictEqual()

const assert = require('assert');

const obj1 = { name: 'Alice', age: 25 };
const obj2 = { name: 'Alice', age: 25 };
const obj3 = { name: 'Bob', age: 30 };

// Perform deep comparison of objects
assert.deepStrictEqual(obj1, obj2); // No error (objects are deeply equal)
console.log('Test passed!');  // This will run

// Assertion will fail if objects are not deeply equal
assert.deepStrictEqual(obj1, obj3);  // Throws AssertionError

Explanation:

assert.deepStrictEqual() checks if two objects or arrays are deeply equal.
In the first assertion, obj1 and obj2 are deeply equal, so no error is thrown.
In the second assertion, obj1 and obj3 are not equal, so an error is thrown.

4. assert.notStrictEqual() to Check Inequality

The assert.notStrictEqual() method checks if two values are not strictly equal. If they are equal, an error is thrown.

Example 3: Using assert.notStrictEqual()

const assert = require('assert');

const value1 = 5;
const value2 = 10;

// Check if the values are not equal
assert.notStrictEqual(value1, value2);  // No error (values are not equal)
console.log('Test passed!');

// This will fail because the values are equal
assert.notStrictEqual(value1, 5);  // Throws AssertionError: 5 !== 5

Explanation:

assert.notStrictEqual() throws an error if the two values are equal.
The second assertion fails because both values are 5, which are strictly equal.

5. Using assert.ok() to Test Truthy Values

assert.ok() is used to assert that a value is truthy. If the value is falsy (e.g., false, 0, null, undefined, or ”), an error is thrown.

Example 4: Using assert.ok()

const assert = require('assert');

const value = true;
const falsyValue = 0;

// Assert that the value is truthy
assert.ok(value);  // No error (value is truthy)
console.log('Test passed!');

// This will fail because the value is falsy (0 is falsy)
assert.ok(falsyValue);  // Throws AssertionError: The expression evaluated to a falsy value

Explanation:

assert.ok() passes if the value is truthy.
The second assertion fails because 0 is a falsy value.

6. assert.throws() for Testing Thrown Errors

assert.throws() checks if a function throws an error when executed. If no error is thrown, or the error is not of the expected type, the assertion fails.

Example 5: Using assert.throws()

const assert = require('assert');

// A function that throws an error
function throwError() {
  throw new Error('An error occurred');
}

// Assert that the function throws an error
assert.throws(
  () => throwError(),
  Error // The expected error type
);

console.log('Test passed!');

// This will fail because the function does not throw an error
assert.throws(
  () => console.log('No error thrown'),
  Error // Expected an error, but none was thrown
);

Explanation:

assert.throws() checks if throwError() throws an error of type Error.
The second assertion fails because no error is thrown in the console.log() statement.

7. assert.doesNotThrow() to Ensure No Error is Thrown

assert.doesNotThrow() is used to verify that a given function does not throw an error. If an error is thrown, the assertion fails.

Example 6: Using assert.doesNotThrow()

const assert = require('assert');

// A function that does not throw an error
function noError() {
  return 'Everything is fine';
}

// Assert that the function does not throw an error
assert.doesNotThrow(() => noError());
console.log('Test passed!');

// This will fail because the function throws an error
function throwError() {
  throw new Error('An error occurred');
}

assert.doesNotThrow(() => throwError());  // Throws AssertionError

Explanation:

assert.doesNotThrow() passes if the function does not throw any errors.
The second assertion fails because throwError() throws an error.

8. Using assert.ifError() to Handle Error Objects

assert.ifError() checks if a value is truthy. If the value is truthy, the assertion fails. This is useful for checking error objects (where null or undefined is expected).

Example 7: Using assert.ifError()

const assert = require('assert');

// No error (null value), so the assertion passes
assert.ifError(null);
console.log('Test passed!');

// This will fail because an error object is passed
assert.ifError(new Error('An error occurred'));  // Throws AssertionError

Explanation:

assert.ifError() passes if the value is null or undefined.
The second assertion fails because an error object is passed, which is truthy.

9. Custom Error Messages

You can pass custom error messages to assertion methods as the last argument. These messages will be displayed when the assertion fails.

Example 8: Using Custom Error Messages

const assert = require('assert');

const actual = 10;
const expected = 20;

// This will fail and print the custom error message
assert.strictEqual(actual, expected, 'Values are not equal!');

Explanation:

If the assertion fails, the custom error message ‘Values are not equal!' is displayed.

10. Using assert.deepEqual() for Loose Equality

assert.deepEqual() performs a loose comparison between two objects or arrays (similar to ==). However, it's often recommended to use assert.deepStrictEqual() for strict deep comparison.

Example 9: Using assert.deepEqual()

const assert = require('assert');

const obj1 = { name: 'Alice', age: '30' };
const obj2 = { name: 'Alice', age: 30 };

// This will pass because deepEqual uses loose comparison
assert.deepEqual(obj1, obj2);

console.log('Test passed!');

Explanation:

assert.deepEqual() uses loose comparison, so '30' (string) and 30 (number) are considered equal.

Conclusion

The assert module in Node.js is a powerful tool for validating your code by writing assertions that ensure values are as expected. It can be used for testing, debugging, and ensuring code correctness.

Key Methods Covered:

assert.strictEqual(): Asserts strict equality (===).
assert.deepStrictEqual(): Asserts deep strict equality of objects or arrays.
assert.notStrictEqual(): Asserts inequality.
assert.ok(): Asserts that a value is truthy.
assert.throws(): Asserts that a function throws an error.
assert.doesNotThrow(): Asserts that a function does not throw an error.
assert.ifError(): Asserts that a value is falsy (typically used for error checking).

By mastering these methods, you can write effective tests and assertions for your Node.js applications, ensuring code correctness and robustness!

You may also like