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 -
1
2
3
4
5
6
7
8
|
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.
1
2
|
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.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
|
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
-
1
2
3
|
// code
if (warning) throw "Warning, warning";
// code
|
.. we can now do -
1
2
3
4
5
6
7
8
|
// code
assert(warning == "whatever condition", "Warning, warning");
// code
/* output
Error:
AssertionError [ERR_ASSERTION]: Warning, warning
*/
|