UNPKG

2.39 kBJavaScriptView Raw
1/*
2 * grunt
3 * http://gruntjs.com/
4 *
5 * Copyright (c) 2012 "Cowboy" Ben Alman
6 * Licensed under the MIT license.
7 * https://github.com/gruntjs/grunt/blob/master/LICENSE-MIT
8 */
9
10/*global phantom:true*/
11
12var fs = require('fs');
13
14// The temporary file used for communications.
15var tmpfile = phantom.args[0];
16// The QUnit helper file to be injected.
17var qunit = phantom.args[1];
18// The QUnit .html test file to run.
19var url = phantom.args[2];
20
21// Keep track of the last time a QUnit message was sent.
22var last = new Date();
23
24// Messages are sent to the parent by appending them to the tempfile.
25function sendMessage(args) {
26 last = new Date();
27 fs.write(tmpfile, JSON.stringify(args) + '\n', 'a');
28 // Exit when all done.
29 if (/^done/.test(args[0])) {
30 phantom.exit();
31 }
32}
33
34// Send a debugging message.
35function sendDebugMessage() {
36 sendMessage(['debug'].concat([].slice.call(arguments)));
37}
38
39// Abort if QUnit doesn't do anything for a while.
40setInterval(function() {
41 if (new Date() - last > 5000) {
42 sendMessage(['done_timeout']);
43 }
44}, 1000);
45
46// Create a new page.
47var page = require('webpage').create();
48
49// QUnit sends its messages via alert(jsonstring);
50page.onAlert = function(args) {
51 sendMessage(JSON.parse(args));
52};
53
54// Keep track if QUnit has been injected already.
55var injected;
56
57// Additional message sending
58page.onConsoleMessage = function(message) {
59 sendMessage(['console', message]);
60};
61page.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.
65 injected = false;
66 }
67 sendDebugMessage('onResourceRequested', request.url);
68};
69page.onResourceReceived = function(request) {
70 if (request.stage === 'end') {
71 sendDebugMessage('onResourceReceived', request.url);
72 }
73};
74
75page.open(url, function(status) {
76 // Only execute this code if QUnit has not yet been injected.
77 if (injected) { return; }
78 injected = true;
79 // The window has loaded.
80 if (status !== 'success') {
81 // File loading failure.
82 sendMessage(['done_fail', url]);
83 } else {
84 // Inject QUnit helper file.
85 sendDebugMessage('inject', qunit);
86 page.injectJs(qunit);
87 // Because injection happens after window load, "begin" must be sent
88 // manually.
89 sendMessage(['begin']);
90 }
91});