Node.js assert Module

Java FileNode.js built-in modules


In Node.js, theassertmodule is a built-in utility library for writing unit tests. It provides a series of assertion functions to verify whether code behavior meets expectations. If an assertion fails,assertthe module will throw anAssertionErrorexception.

assertThe module is very suitable for use during development and testing, helping developers quickly discover problems in code.


How to use the assert module?

To useassertmodule, you first need to import it:

const assert = require('assert');

Basic assertion methods

1. assert.ok(value[, message])

assert.ok()is the most basic assertion method. It testsvaluewhether it is a truthy value. Ifvalueit is falsy, then throwsAssertionError。

Example

assert.ok(true); // passed
assert.ok(1); // passed
assert.ok(false); // throws AssertionError
assert.ok(0, 'value is falsy'); // throws AssertionError: value is falsy

2. assert.equal(actual, expected[, message])

assert.equal()Uses==operator to compareactualandexpectedwhether they are equal (loose equality).

Example

assert.equal(1, 1); // passed
assert.equal(1, '1'); // passed
assert.equal(1, 2); // throws AssertionError

3. assert.strictEqual(actual, expected[, message])

assert.strictEqual()Uses===operator to compareactualandexpectedwhether they are strictly equal.

Example

assert.strictEqual(1, 1); // passed
assert.strictEqual(1, '1'); // throws AssertionError

4. assert.deepEqual(actual, expected[, message])

assert.deepEqual()Used to compare whether the contents of two objects or arrays are equal (recursive comparison).

Example

assert.deepEqual({ a: 1 }, { a: 1 }); // passed
assert.deepEqual([1, 2], [1, 2]); // passed
assert.deepEqual({ a: 1 }, { a: '1' }); // passed (loose comparison)

5. assert.deepStrictEqual(actual, expected[, message])

assert.deepStrictEqual()Similar todeepEqual, but uses strict comparison (===)。

Example

assert.deepStrictEqual({ a: 1 }, { a: 1 }); // passed
assert.deepStrictEqual({ a: 1 }, { a: '1' }); // throws AssertionError

Other common assertion methods

1. assert.notEqual(actual, expected[, message])

Testsactualandexpectedwhether they are not equal (!=)。

Example

assert.notEqual(1, 2); // passed
assert.notEqual(1, '1'); // throws AssertionError

2. assert.notStrictEqual(actual, expected[, message])

Testsactualandexpectedwhether they are not strictly equal (!==)。

Example

assert.notStrictEqual(1, '1'); // passed
assert.notStrictEqual(1, 1); // throws AssertionError

3. assert.throws(block[, error][, message])

Testsblockwhether a function will throw an error.

Example

assert.throws(
  () => {
    throw new Error('Wrong value');
  },
  Error
); // passed

assert.throws(
  () => {
    throw new Error('Wrong value');
  },
  /Wrong/
); // passed (regular expression matches error message)

4. assert.doesNotThrow(block[, error][, message])

Testsblockwhether a function will not throw an error.

Example

assert.doesNotThrow(
  () => {
    const x = 1 + 1;
  },
  Error
); // passed

5. assert.fail([message])

Forcefully throws anAssertionError。

Example

assert.fail('Test failed'); // throws AssertionError: Test failed

Practical application example

Suppose we have a simple functionadd, used to calculate the sum of two numbers:

Example

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

We can useassertmodule to write tests for it:

Example

const assert = require('assert');

// Test normal case
assert.strictEqual(add(1, 2), 3, '1 + 2 should be 3');
assert.strictEqual(add(-1, 1), 0, '-1 + 1 should be 0');

// Test edge case
assert.strictEqual(add(0, 0), 0, '0 + 0 should be 0');
assert.strictEqual(add(1.5, 2.5), 4, '1.5 + 2.5 should be 4');

// Test error case
assert.throws(
  () => add('1', 2),
  TypeError,
  'Adding string to number should throw TypeError'
);

Notes

  1. Production environment:assertThe module is mainly used in development and testing environments. It is not recommended to use it in production, because assertion failures will cause the program to crash.

  2. Strict mode: Node.js also providesassert/strictmodule, which isassertstrict version of the module. All comparisons use strict equality (===)。

    const assert = require('assert/strict');
  3. Custom error messages: Provide clear error messages for each assertion, which helps quickly locate problems.

  4. Performance considerations: Althoughassertmodule is very convenient, it should be used with caution in performance-critical code, because assertion checks add extra overhead.


Summary

assertThe module is a simple but powerful testing tool in Node.js, especially suitable for unit testing and code verification during the development phase. By using various assertion methods appropriately, you can effectively ensure code correctness. Remember that after development is completed, you should replaceassertmodule for more comprehensive testing.

Java FileNode.js built-in modules

Other extensions