8 different ways to use assert in Node.js [Practical Examples]

The purpose of the assert module in Node.js is to provide various ways of asserting functions. For instance, if the assertion. It is used to test the functionality of functions in Node.js.

If an application has an error, assert throws an assertion error. It is therefore used to verify invariants. The assert module can be used with unit tests modules like mocha, and chai.

Advertisement

Before understanding how to implement the assert module to verify invariants, it is important to understand what invariants are.

 

What Are Invariants and How Are They Used?

An invariant is a condition or expression that is alas true. Invariants are used in data or code locking. Invariant functions are used to test expressions. Consider the following code:

const x = 3;
const y = 3;
const isGreater= (x>y);
console.log(isGreater);

When you run the above function, it should print true on the console. It is an invariant function.

Consider a situation whereby an expression depends on that value. If the isGreater expression returned an unexpected value, the code that depends on it would also behave unusually. To prevent this, you have to introduce a method that guarantees that the expression will return true. This guarantee can be implemented using the assert method.

 

Different Assert Methods in Node.js

The assert module is an inbuilt Node.js module. You do not have to install it and can directly import it to your code.

const assert = require(‘assert’);

 

Method-1: Node.js assert(value[, message]) Method

This method is an alias of assert.ok() and is used to check if the value passed to it is truthy. Continuing from the above block of code, we can perform assertion as shown below:

Advertisement
const x = 3;
const y = 4;
assert(x>y);

If the expression is false, it will throw an exception and if it is true, the block of code will continue executing as expected.

 

Method-2: Node.js assert.deepStrictEqual(actual, expected[, message]) Method

The assert.deepStrictEqual() method tests for deep equality (===) between the actual and expected value. It is different from assert.deepEqual() which tests for abstract equality (==). Deep quality does not perform type conversion but the abstract comparison does. The assert.deepStrictEqual() method throws an error if it produces a false output. Since this method uses assert in strict mode, you will have to specify so in your require statement.

const assert = require('assert').strict;
try {
    assert.deepStrictEqual({ a: 3 }, { a: '3' });
} catch(err) {
    console.log(err)
}

When you run the above function, the assert.deepStrictEqual() performs a deep comparison between the two objects you have passed in. The two objects are not equal, and an error will be thrown. The catch block catches the error and displays it in the console.

The assert module has the assert.deepEqual() method that can be used for abstract equality comparisons. It evaluates child objects too.

Another assert() method that tests for equality is the assert.strictEqual(actual, expected[,message]) method that uses the Object.is() JavaScript method to test for equality.

For example, the expression assert.strictEqual(1,2) will throw an error as 1 and 2 are not strictly equal but assert.strictEqual(1, 1) does not throw an error.

 

Method-3: Node.js assert.notDeepStrictEqual(actual, expected,message]) Method 

The assert.notDeepStrictEqual() is used to test expressions for deep inequality and is the opposite of the assert.deepStrictEqualMethod(). It accepts the actual expression, the expected expression and an optional error message. This function does not throw an error.

try {
    assert.notDeepStrictEqual({ a: 3 }, { a: '3' });
} catch(err) {
    console.log(err)
}

 

Method-4: Node.js assert.match(string, regexp[, message]) Method

This method is used to match input to a regular expression. If it does not match, the method throws an error.

const assert = require('assert').strict;
assert.match('I will pass', /pass/);

No error will be thrown in the above function since the string passed in matches the regular expression. There is also the assert.doesNotMatch() method that is used to verify that the string passed in does not match the regular expression. The following expression would throw an error since the string and the expected regular expression match.

constassert = require('assert').strict;
// Throws an error
assert.doesNotmatch('I will pass', /pass/);

// Does not throw an error
assert.match('I will fail', /pass/);

 

Method-5: Node.js assert.fail([message]) Method

This method throws the provided error message or a default error message when called.  Below is an example of how you can use this method.

const assert = require('assert').strict;
assert.fail();
// throws the default error message
assert.fail('Custom error message');
// throws the custom error message

 

Method-6: Node.js assert.ifError(value)

If you want to test error callbacks, the assert.ifError() allows you to throw a value if  the value is not undefined or null. This method is useful when testing error arguments and callbacks as it provides the stack trace from the error passed in. The following expression does not throw an error since null is passed as the value.

const assert = require('assert').strict;
assert.ifError(null) // Does not throw an error
assert.ifError(new Error()) // Throws an error

Method-7: Node.js assert.rejects(asyncFn[, error][, message]) Method

This method awaits the promise passed in or the promise returned from the async function passed in and checks if the function is rejected.

If the async function throws an error or fails to return a promise, assert.rejects() returns a rejected promise with an error object.

(async () => {
  assert.strictEqual(3,4)
  await assert.rejects(
    async () => {
      throw new TypeError('Wrong value');
    },
    (err) => {
      assert.strictEqual(err.name, 'TypeError');
      assert.strictEqual(err.message, 'Wrong value');
      return true;
    }
  );
})();

If you want to check whether a promise returned by a function is not rejected, you can use the

assert.doesNotReject(asyncFn\[, error\][, message]) method. This method returns a rejected promise if the expression passed in fails to return a promise.

(async () => {
  await assert.doesNotReject(
    async () => {
      throw new TypeError('Wrong value');
    },
    SyntaxError
  );
})();

assert.doesNotReject() is not usually helpful as there is no benefit of catching a rejected promise and then rejecting it again. A good approach would be to add comments in the function that should not react and have expressive error messages.

 

Method-8: Node.js assert.throws(fn[, error][, message]) Method

assert.throws() expects the passed in function to throw an error. The function takes in the function expected to throw an error, an optional error object and the error message.

try {
    assert.throws(
        () => {
          throw new TypeError('Wrong value');
        },
    );
} catch(error) {
    console.log("Error:", error)
}

 

Next Steps

This article illustrated some of the methods from the assert module provided by Node.js. The assert module is used to ensure that an invariant condition returns true. These methods are especially useful when performing tests. The article only discussed some of the available assert methods. To learn more, visit the Node.js assert module  documentation page

 

Didn't find what you were looking for? Perform a quick search across GoLinuxCloud

If my articles on GoLinuxCloud has helped you, kindly consider buying me a coffee as a token of appreciation.

Buy GoLinuxCloud a Coffee

For any other feedbacks or questions you can either use the comments section or contact me form.

Thank You for your support!!

Leave a Comment

X