Skip to content

Instantly share code, notes, and snippets.

@daogurtsov
Last active December 17, 2015 12:19
Show Gist options
  • Save daogurtsov/5609292 to your computer and use it in GitHub Desktop.
Save daogurtsov/5609292 to your computer and use it in GitHub Desktop.
JS assertion function with grouping by John Resig from JavaScript Ninja
<html>
<head>
<title>Test Suite</title>
</head>
<body>
<script>
(function () {
var results = document.createElement("ul");
results.id = "results";
var html = results.outerHTML;
document.write(html);
results = document.getElementById("results");
this.assert = function assert(value, desc) {
var li = document.createElement("li");
li.className = value ? "pass" : "fail";
if(li.className === "pass"){
li.style.color = "green";
}else{
li.style.color = "red";
}
li.appendChild(document.createTextNode(desc));
results.appendChild(li);
if (!value) {
li.parentNode.parentNode.className = "fail";
li.parentNode.parentNode.style.color = "red";
}
return li;
};
this.test = function test(name, fn) {
results = document.getElementById("results");
results = assert(true, name).appendChild(
document.createElement("ul"));
fn();
};
})();
window.onload = function() {
test("A test.", function() {
assert(true, "First assertion completed");
assert(true, "Second assertion completed");
assert(true, "Third assertion completed");
});
test("Another test.", function() {
assert(true, "First test completed");
assert(false, "Second test failed");
assert(true, "Third assertion completed");
});
test("A third test.", function() {
assert(null, "fail");
assert(5, "pass")
});
};
</script>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment