Asserts are not just for testing

Assert is a general-purpose validator and should not be used in the context of testing alone.

An assert in Javascript simply checks for truthy values and produces an error otherwise. We use it quite a bit in automated testing when checking for correctness of output for pre-defined inputs.

We use asserts like so -

var assert = require("assert");

function getSum(x, y) {
  return x + y;
}

assert(getSum(1, 2) === 3);
assert(getSum(3, 6) == 9);

The above code block will go through fine since there are no errors, but I am well capable of producing a few errors.

assert(getSum(1, 2) == 4);
// AssertionError [ERR_ASSERTION]: The expression evaluated to a falsy value:

Assert statements are great for unit tests, but can be equally useful for validations and checks in our normal programs.

var assert = require("assert");

function getSum(x, y) {
  assert(!!Number(x) == true);
  assert(!!Number(y) == true);

  return x + y;
}

console.log(getSum(1, 1));
// 2

console.log(getSum("a", 1));
// AssertionError [ERR_ASSERTION]: The expression evaluated to a falsy value:
//   assert(!!Number(x) == true)

This is especially useful in places where you need to check for warnings and start throwing errors for pre-defined warnings.

Instead of an explicit if -

// code
if (warning) throw "Warning, warning";
// code

.. we can now do -

// code
assert(warning == "whatever condition", "Warning, warning");
// code

/* output
Error:
AssertionError [ERR_ASSERTION]: Warning, warning
*/
comments powered by Disqus