5 * Copyright (c) 2012 "Cowboy" Ben Alman
6 * Licensed under the MIT license.
7 * https://github.com/gruntjs/grunt/blob/master/LICENSE-MIT
10 /*global phantom:true*/
12 var fs = require('fs');
14 // The temporary file used for communications.
15 var tmpfile = phantom.args[0];
16 // The QUnit helper file to be injected.
17 var qunit = phantom.args[1];
18 // The QUnit .html test file to run.
19 var url = phantom.args[2];
21 // Keep track of the last time a QUnit message was sent.
22 var last = new Date();
24 // Messages are sent to the parent by appending them to the tempfile.
25 function sendMessage(args) {
27 fs.write(tmpfile, JSON.stringify(args) + '\n', 'a');
28 // Exit when all done.
29 if (/^done/.test(args[0])) {
34 // Send a debugging message.
35 function sendDebugMessage() {
36 sendMessage(['debug'].concat([].slice.call(arguments)));
39 // Abort if QUnit doesn't do anything for a while.
40 setInterval(function() {
41 if (new Date() - last > 5000) {
42 sendMessage(['done_timeout']);
47 var page = require('webpage').create();
49 // QUnit sends its messages via alert(jsonstring);
50 page.onAlert = function(args) {
51 sendMessage(JSON.parse(args));
54 // Keep track if QUnit has been injected already.
57 // Additional message sending
58 page.onConsoleMessage = function(message) {
59 sendMessage(['console', message]);
61 page.onResourceRequested = function(request) {
62 if (/\/qunit\.js$/.test(request.url)) {
63 // Reset injected to false, if for some reason a redirect occurred and
64 // the test page (including qunit.js) had to be re-requested.
67 sendDebugMessage('onResourceRequested', request.url);
69 page.onResourceReceived = function(request) {
70 if (request.stage === 'end') {
71 sendDebugMessage('onResourceReceived', request.url);
75 page.open(url, function(status) {
76 // Only execute this code if QUnit has not yet been injected.
77 if (injected) { return; }
79 // The window has loaded.
80 if (status !== 'success') {
81 // File loading failure.
82 sendMessage(['done_fail', url]);
84 // Inject QUnit helper file.
85 sendDebugMessage('inject', qunit);
87 // Because injection happens after window load, "begin" must be sent
89 sendMessage(['begin']);