Created
November 30, 2013 21:40
-
-
Save vishaltelangre/7724819 to your computer and use it in GitHub Desktop.
A simple asynchronous test suite - from JS Ninja book by John Resig
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<html> | |
<head> | |
<title>Test Suite</title> | |
<script> | |
(function() { | |
var queue = [], paused = false, results; | |
this.test = function(name, fn) { | |
queue.push(function() { | |
results = document.getElementById("results"); | |
results = assert(true, name).appendChild( | |
document.createElement("ul")); | |
fn(); | |
}); | |
runTest(); | |
}; | |
this.pause = function() { | |
paused = true; | |
}; | |
this.resume = function() { | |
paused = false; | |
setTimeout(runTest, 1); | |
}; | |
function runTest() { | |
if (!paused && queue.length) { | |
queue.shift()(); | |
if (!paused) { | |
resume(); | |
} | |
} | |
} | |
this.assert = function assert(value, desc) { | |
var li = document.createElement("li"); | |
li.className = value ? "pass" : "fail"; | |
li.appendChild(document.createTextNode(desc)); | |
results.appendChild(li); | |
if (!value) { | |
li.parentNode.parentNode.className = "fail"; | |
} | |
return li; | |
}; | |
})(); | |
window.onload = function() { | |
test("Async Test #1", function() { | |
pause(); | |
setTimeout(function() { | |
assert(true, "First test completed"); | |
resume(); | |
}, 1000); | |
}); | |
test("Async Test #2", function() { | |
pause(); | |
setTimeout(function() { | |
assert(true, "Second test completed"); | |
resume(); | |
}, 1000); | |
}); | |
}; | |
</script> | |
<style> | |
#results li.pass { | |
color: green; | |
} | |
#results li.fail { | |
color: red; | |
} | |
</style> | |
</head> | |
<body> | |
<ul id="results"></ul> | |
</body> | |
</html> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment