There is no built-in assert()
function in JavaScript. However if rather simple to write such a function yourself
It's important to note that in NodeJS
there is a standard library assert
that includes such functions and even more.
What is the purpose of the assert function and how is it used?
The purpose of an assert()
function is to check if a given condition is true
. If the condition is true
the function does nothing. However, if the condition is false
, the assert()
function throws an error, which can be caught and used to identify the issue. This method is used mainly in automated tests and when debugging.
Example of assert() function in JavaScript
function assert(condition) {
if (!condition) {
throw new Error("Assertion failed");
}
}
Example test case where assert
function comes in handy.
// Let's say we have a function which whenever called returns 1 each time.
function returnOnlyOne() {
return 1;
}
// If we want to test this functions just to make sure it works as expected
// We can do the following
console.log('Start tests');
assert(returnOnlyOne() == 1);
console.log('Test 1 passed!');
outputs
$ Start tests
$ Test 1 passed!
So we've validated that our function behaves as expected!
If we swap the returnOnlyOne
function to give in the wrong behavior with
function returnOnlyOne() {
return 2;
}
Then the output will be
$ Start tests
$ Error: Assertion failed
The assert statement will catch the error and throw an exception.