Whenever you code, testing is vital. Test early and often.
With this in mind, it can be useful to create a function that is used purely for testing.
The assert function is written in pure JavaScript and can be used to make assertion when coding.
/**
* Used to test assertions.
* @param {boolean} value - Test expression which is expected to return true.
* @param {string} description - Description of the assertion.
* @param {boolean} list - True displays results in a list, false returns to console.
*/
function assert(value, description, list){
//If the list parameter is not defined, output to console
if (list === undefined || list === false){
description = value ? "PASS - " + description : "FAIL - " + description;
console.log(description);
}else{
//Else, display results in a list on the page
//Check if results list exists. If not, create it.
if(document.getElementById("test-results") === null){
var results = document.createElement("ul");
results.id = "test-results";
document.body.appendChild(results);
}
//Create a new list item and add its class and prefix based on the 'value' parameter
var test = document.createElement("li");
test.className = value ? "pass" : "fail";
description = value ? "PASS - " + description : "FAIL - " + description;
test.appendChild(document.createTextNode(description));
//Add list item to results list
document.getElementById("test-results").appendChild(test);
}
}
//assert(1 == 1, "This test passes, the results are printed to the console");
//assert(1 == 2, "This test fails, the results are printed to the page", true);