-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathrun-jasmine.js
256 lines (231 loc) · 9.93 KB
/
run-jasmine.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
// Verify arguments
if (phantom.args.length === 0) {
console.log("Simple JasmineBDD test runner for phantom.js");
console.log("Usage: phantomjs-testrunner.js url_to_runner.html");
console.log("Accepts http:// and file:// urls");
console.log("");
console.log("NOTE: This script depends on jasmine.TrivialReporter being used\non the page, for the DOM elements it creates.\n");
phantom.exit(2);
}
else {
var args = phantom.args;
var pages = [], page, address, resultsKey, i, l;
var setupPageFn = function(p, k) {
return function() {
overloadPageEvaluate(p);
setupWriteFileFunction(p, k);
};
};
var xml_filename = args[1];
address = args[0];
console.log("Loading " + address);
// if provided a url without a protocol, exit
if (address.indexOf("://") === -1) {
console.log("No protocol supplied for page address: " + address);
phantom.exit(1);
}
// create a WebPage object to work with
page = require("webpage").create();
page.url = address;
// When initialized, inject the reporting functions before the page is loaded
// (and thus before it will try to utilize the functions)
resultsKey = "__jr" + Math.ceil(Math.random() * 1000000);
page.onInitialized = setupPageFn(page, resultsKey);
page.onResourceReceived = function(resource) {
if (resource.url == address && resource.status != 200) {
console.log('Error loading target: ' + address);
console.log('Response code: ' + resource.status);
phantom.exit(1);
}
};
page.open(address, processPage(null, page, resultsKey));
pages.push(page);
page.onConsoleMessage = logAndWorkAroundDefaultLineBreaking;
// bail when all pages have been processed
setInterval(function(){
var exit_code = 0;
for (i = 0, l = pages.length; i < l; i++) {
page = pages[i];
if (page.__exit_code === null) {
// wait until later
return;
}
exit_code |= page.__exit_code;
}
phantom.exit(exit_code);
}, 100);
}
// Thanks to hoisting, these helpers are still available when needed above
/**
* Logs a message. Does not add a line-break for single characters '.' and 'F' or lines ending in ' ...'
*
* @param msg
*/
function logAndWorkAroundDefaultLineBreaking(msg) {
var interpretAsWithoutNewline = /(^(\033\[\d+m)*[\.F](\033\[\d+m)*$)|( \.\.\.$)/;
if (navigator.userAgent.indexOf("Windows") < 0 && interpretAsWithoutNewline.test(msg)) {
var fs = require('fs');
// system.stdout.write(msg) ? wait for http://code.google.com/p/phantomjs/issues/detail?id=243 to be implemented
fs.write('/dev/stdout', msg, 'w');
} else {
console.log(msg);
}
}
/**
* Stringifies the function, replacing any %placeholders% with mapped values.
*
* @param {function} fn The function to replace occurrences within.
* @param {object} replacements Key => Value object of string replacements.
*/
function replaceFunctionPlaceholders(fn, replacements) {
if (replacements && typeof replacements === "object") {
fn = fn.toString();
for (var p in replacements) {
if (replacements.hasOwnProperty(p)) {
var match = new RegExp("%" + p + "%", "g");
do {
fn = fn.replace(match, replacements[p]);
} while(fn.indexOf(match) !== -1);
}
}
}
return fn;
}
/**
* Replaces the "evaluate" method with one we can easily do substitution with.
*
* @param {phantomjs.WebPage} page The WebPage object to overload
*/
function overloadPageEvaluate(page) {
page._evaluate = page.evaluate;
page.evaluate = function(fn, replacements) { return page._evaluate(replaceFunctionPlaceholders(fn, replacements)); };
return page;
}
/** Stubs a fake writeFile function into the test runner.
*
* @param {phantomjs.WebPage} page The WebPage object to inject functions into.
* @param {string} key The name of the global object in which file data should
* be stored for later retrieval.
*/
// TODO: not bothering with error checking for now (closed environment)
function setupWriteFileFunction(page, key) {
page.evaluate(function(){
window["%resultsObj%"] = {};
window.__phantom_writeFile = function(filename, text) {
window["%resultsObj%"][filename] = text;
};
}, {resultsObj: key});
}
/**
* Returns the loaded page's filename => output object.
*
* @param {phantomjs.WebPage} page The WebPage object to retrieve data from.
* @param {string} key The name of the global object to be returned. Should
* be the same key provided to setupWriteFileFunction.
*/
function getXmlResults(page, key) {
return page.evaluate(function(){
return window["%resultsObj%"] || {};
}, {resultsObj: key});
}
/**
* Processes a page.
*
* @param {string} status The status from opening the page via WebPage#open.
* @param {phantomjs.WebPage} page The WebPage to be processed.
*/
function processPage(status, page, resultsKey) {
if (status === null && page) {
page.__exit_code = null;
return function(stat){
processPage(stat, page, resultsKey);
};
}
if (status !== "success") {
console.error("Unable to load resource: " + address);
page.__exit_code = 2;
}
else {
var isFinished = function() {
return page.evaluate(function(){
try {
// if there's a JUnitXmlReporter, return a boolean indicating if it is finished
if (jasmine.JUnitXmlReporter) {
return jasmine.JUnitXmlReporter.finished_at !== null;
}
} catch(err) {
console.dir(err);
return true;
}
// otherwise, see if there is anything in a "finished-at" element
return document.getElementsByClassName("finished-at").length &&
document.getElementsByClassName("finished-at")[0].innerHTML.length > 0;
});
};
var getResults = function() {
return page.evaluate(function(){
var writeToConsole = function() {
var suites = document.body.querySelectorAll('.suite');
for (var i = 0; i < suites.length; i++){
var suite = suites[i];
var suiteName = suite.querySelector('.description').innerText;
var passOrFail = suite.className.indexOf('passed') != -1 ? "Passed" : "Failed!";
console.log('Suite: '+suiteName+'\t'+passOrFail);
console.log('--------------------------------------------------------');
var specs = suite.querySelectorAll('.spec');
for (var j = 0; j < specs.length; j++){
var spec = specs[j];
var passed = spec.className.indexOf('passed') != -1;
var specName = spec.querySelector('.description').innerText;
var passOrFail = passed ? 'Passed' : "Failed!"
console.log('\t'+specName+'\t'+passOrFail);
if(!passed){
console.log('\t\t-> Message: '+spec.querySelector('.resultMessage.fail').innerText);
var trace = spec.querySelector('.stackTrace');
console.log('\t\t-> Stack: '+(trace!=null ? trace.innerText : 'not supported by phantomJS yet'));
}
}
console.log('');
}
var runner = document.body.querySelector('.runner');
console.log('--------------------------------------------------------');
console.log('Finished: '+runner.querySelector('.description').innerText);
};
writeToConsole();
return document.getElementsByClassName("description").length &&
document.getElementsByClassName("description")[0].innerHTML.match(/(\d+) spec.* (\d+) failure.*/) ||
["Unable to determine success or failure."];
});
};
var ival = setInterval(function(){
if (isFinished()) {
if(xml_filename != undefined && xml_filename.length > 0) {
// get the results that need to be written to disk
var fs = require("fs"),
xml_results = getXmlResults(page, resultsKey),
output,
agg_xml = '<?xml version="1.0" encoding="UTF-8" ?>\n\n<!-- Jasmine tests -->\n<testsuites>';
for (var filename in xml_results) {
if (xml_results.hasOwnProperty(filename) && (output = xml_results[filename]) && typeof(output) === "string") {
agg_xml += output.replace('<?xml version="1.0" encoding="UTF-8" ?>', '')
.replace('<testsuites>', '').replace('</testsuites>', '');
}
}
agg_xml += '\n</testsuites>\n';
fs.write(xml_filename, agg_xml, "w");
}
// print out a success / failure message of the results
var results = getResults();
var failures = Number(results[2]);
if (failures > 0) {
page.__exit_code = 1;
clearInterval(ival);
}
else {
page.__exit_code = 0;
clearInterval(ival);
}
}
}, 100);
}
}