Created
December 13, 2012 11:58
-
-
Save sfoster/4275965 to your computer and use it in GitHub Desktop.
Exploring layout of a sequence of async steps to setup, run and teardown a series of unit tests, using task.js. You'll need a recent Firefox for the generator (yield) support.
This file contains hidden or 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>Async unit testing with task.js (exploration)</title></head> | |
<script type="application/javascript" src="https://raw.github.com/mozilla/task.js/master/lib/task.js"></script> | |
<script type="application/javascript;version=1.8"> | |
function go() { | |
var { spawn, join, TaskResult, Deferred } = task; | |
var mydata = { foo: "bar" }; | |
// shared functions for test setup | |
function reset() { | |
var defd = new Deferred(); | |
setTimeout(function(){ | |
delete mydata.foo; | |
delete mydata.ready; | |
delete mydata.buzz; | |
defd.resolve(mydata); | |
}, 0); | |
return defd.promise; | |
} | |
function initialData(){ | |
var defd = new Deferred(); | |
setTimeout(function(){ | |
mydata.ready = true; | |
defd.resolve(mydata); | |
}, 0); | |
return defd.promise; | |
} | |
// indicate test group completion | |
function finish(){ | |
console.log("Tests done"); | |
} | |
spawn(function(){ | |
yield spawn(function() { | |
var emptyData = yield reset(); | |
console.log("Verify setup"); | |
console.assert(undefined === mydata.foo, "foo is undefined"); | |
console.assert(!mydata.ready, "ready is falsy"); | |
// more setup | |
var readyData = yield initialData(); | |
console.assert(!!mydata.ready, "ready is truthy"); | |
console.log("/Verify setup"); | |
console.log("conduct test"); | |
var outcome = yield testSomething(); | |
console.log("/conduct test"); | |
}); | |
yield spawn(function() { | |
console.log("test setup"); | |
var emptyData = yield reset(); | |
var readyData = yield initialData(); | |
console.assert(undefined === mydata.buzz, "buzz is undefined"); | |
// more setup | |
console.log("/test setup, conduct test"); | |
var outcome = yield testSomething(); | |
console.log("/conduct test"); | |
}); | |
finish(); | |
}); | |
function testSomething(){ | |
var defd = new Deferred(); | |
console.assert(undefined == mydata.buzz); | |
setTimeout(function(){ | |
mydata.buzz = Date.now(); | |
setTimeout(function(){ | |
var now = Date.now(); | |
console.assert(now < mydata.buzz, "some time elapsed (fails)"); | |
defd.resolve(true); | |
}, 25); | |
}, 25); | |
return defd.promise; | |
} | |
} | |
</script> | |
<body onload="go()"> | |
<h1>Async unit testing w. task.js</h1> | |
<p>Just a proof of concept. See console for output</p> | |
</body> | |
</html> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment