JavaScript: assert() function
Blogs20142014-08-19
JavaScript: assert() function
In JavaScript, there is no assert function, only console.assert is available. According to stackoverflow: there isn’t an assert function built into ECMAScript5 (e.g. JavaScript that works basically everywhere) but some browsers give it to you or have add-ons that provide that functionality. So use Jasmine/QUnit to do the test if possible. A simple example which can be used inside the codes is below:
var assert = function(condition, message) {
if (!condition)
throw Error("Assert failed" + (typeof message!=="undefined" ? ": " + message : ""));
};
assert(1===1); // nothing return, true.
assert(null==undefined, "Should be equal");
//Error: Assert failed: Should not be equal
assert(null===undefined, "Should not be equal");
//Error: Assert failed: Should not be true
assert(false, "Should not be true"); 