What is assert?
The assert npm package is a module that provides a set of assertion functions for verifying invariants. It is primarily used for writing tests to ensure that code behaves as expected. The module includes functions to test strict equality, deep equality, and various other conditions.
What are assert's main functionalities?
Strict Equality Assertion
This feature is used to test if two values are strictly equal using the === operator.
const assert = require('assert');
assert.strictEqual(1, 1, '1 is strictly equal to 1');
Deep Equality Assertion
This feature is used to test if two objects or arrays are equal by comparing their properties or elements.
const assert = require('assert');
assert.deepStrictEqual({ a: 1 }, { a: 1 }, 'Objects are deeply equal');
Assertion with a Predicate Function
This feature is used to test if a value passes a specified predicate function.
const assert = require('assert');
assert.ok(value => value > 10, 'Value is greater than 10');
Throws Assertion
This feature is used to test if a function throws an error as expected.
const assert = require('assert');
assert.throws(
() => { throw new Error('Wrong value'); },
Error,
'Function should throw an Error'
);
Other packages similar to assert
chai
Chai is a BDD/TDD assertion library for node and the browser that can be delightfully paired with any javascript testing framework. It offers more plugins and a more flexible API compared to assert.
expect
Expect is a minimalistic assertion library that provides a set of assertion functions and is often used with Jest. It offers a more fluent and readable syntax compared to assert.
should
Should.js is an expressive, readable, framework-agnostic assertion library. It extends the Object prototype with a single non-enumerable getter that allows for a more fluent and chainable API, providing a different style of coding compared to assert.