I am attempting to get a set of asynchronous QUnit tests to run from an Ant build script, using PhantomJS. What I have seems to be working, but it seems like there should be a nicer way to achieve it.
The script (simplified) that runs when PhantomJS loads is as follows:
var page = require("webpage").create();
page.onConsoleMessage = function(msg) {
if(msg.indexOf("FINISHED") > -1) {
var failed = msg.split(" ");
phantom.exit(failed[1]);
}
};
page.open("testrunner.html", function() {
page.evaluate(function() {
QUnit.done = function(result) {
console.log("FINISHED " + result.failed);
};
});
});
This loads the file which contains the tests (testrunner.html
). It uses the PhantomJS evaluate
method to run some code in the context of the loaded page. That code binds an event handler to the QUnit done
event. In the event handler, all that happens is a simple call to console.log
.
PhantomJS does not do anything with console.log
calls by default, so I have also bound an event handler to the PhantomJS onConsoleMessage
event. When the console.log
call in the QUnit.done
event handler is executed, the onConsoleMessage
event is triggered. If the console message matches a given string, then we know the tests have finished running. We can then exit PhantomJS, with an exit code equal to the number of failed unit tests (this is used by the Ant script to determine whether or not this part of the build was successful).
My question is, is there a better way to find out when the unit tests have finished running?