-
Notifications
You must be signed in to change notification settings - Fork 38
/
mocha-phantomjs-core.js
249 lines (229 loc) · 7.21 KB
/
mocha-phantomjs-core.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
/*
This file is a part of:
https://github.com/nathanboktae/mocha-phantomjs-core
It's licensed under MIT, see
https://github.com/nathanboktae/mocha-phantomjs-core/blob/master/MIT-LICENSE
and local copy:
mocha-phantomjs-core_LICENSE.txt
*/
var
system = require('system'),
webpage = require('webpage'),
fs = require('fs'),
stderr = system.stderr || system.stdout,
url = system.args[1],
reporter = system.args[2] || 'spec',
configured = false,
runStarted = false,
isSlimer = 'MozApplicationEvent' in window,
config = {},
hookData
try {
config = JSON.parse(system.args[3] || '{}')
} catch (e) {
console.log(e)
console.log('Bad JSON options')
phantom.exit(255)
}
if (!url) {
system.stdout.writeLine("Usage: " + (isSlimer ? 'slimerjs' : 'phantomjs') + " mocha-phantomjs-core.js URL REPORTER [CONFIG-AS-JSON]")
phantom.exit(255)
}
if (phantom.version.major < 1 || (phantom.version.major === 1 && phantom.version.minor < 9)) {
stderr.writeLine('mocha-phantomjs requires PhantomJS > 1.9.1')
phantom.exit(-2)
}
// Create and configure the client page
var
output = config.file ? fs.open(config.file, 'w') : system.stdout,
page = webpage.create({
settings: config.settings
}),
fail = function(msg, errno) {
if (output && config.file) {
output.close()
}
if (msg) {
stderr.writeLine(msg)
}
return phantom.exit(errno || 1)
}
if (config.hooks) {
hookData = {
page: page,
config: config,
reporter: reporter
}
try {
config.hooks = require(config.hooks)
}
catch (e) {
stderr.writeLine('Error loading hooks: ' + e.message)
phantom.exit(253)
}
} else {
config.hooks = {}
}
if (config.headers) {
page.customHeaders = config.headers
}
(config.cookies || []).forEach(function(cookie) {
page.addCookie(cookie)
})
if (config.viewportSize) {
page.viewportSize = config.viewportSize
}
page.onConsoleMessage = function(msg) {
return system.stdout.writeLine(msg)
}
page.onResourceError = function(resErr) {
if (!config.ignoreResourceErrors) {
return stderr.writeLine("Error loading resource " + resErr.url + " (" + resErr.errorCode + "). Details: " + resErr.errorString)
}
}
page.onError = function(msg, traces) {
if (page.evaluate(function() { return !!window.onerror })) return
fail(msg + '\n' + traces.reduce(function(stack, trace) {
return stack + '\n ' + (trace.function ? ' in ' + trace.function + '' : '')
+ ' at ' + trace.file + ':' + trace.line
}, ''))
}
// Load the test page
page.open(url)
page.onInitialized = function() {
page.injectJs('browser-shim.js')
if (isSlimer && config.settings && config.settings.userAgent) {
page.evaluate(function(ua) {
navigator.__defineGetter__('userAgent', function() { return ua })
}, config.settings.userAgent)
}
}
page.onResourceReceived = function(resource) {
if (resource.url.match(/mocha\.js$/)) {
page.evaluate(function() {
checkForMocha()
})
}
}
page.onCallback = function(data) {
if (data) {
if (data.stdout) {
output.write(data.stdout)
} else if (typeof data.screenshot === 'string') {
page.render(data.screenshot + '.png')
} else if (data.viewportSize && (data.viewportSize.width || data.viewportSize.height)) {
page.viewportSize = {
width: data.viewportSize.width || page.viewportSize.width,
height: data.viewportSize.height || page.viewportSize.height,
}
} else if (data.configureColWidth) {
page.evaluate(function(columns) {
Mocha.reporters.Base.window.width = columns
}, parseInt(system.env.COLUMNS || 75) * .75 | 0)
} else if (data.configureMocha) {
configureMocha()
} else if ('testRunStarted' in data) {
if (data.testRunStarted == 0) {
fail('mocha.run() was called with no tests')
}
runStarted = true
} else if (data.testRunEnded) {
if (typeof config.hooks.afterEnd === 'function') {
hookData.runner = data.testRunEnded
config.hooks.afterEnd(hookData)
}
if (config.file) {
output.close()
}
setTimeout(function() {
phantom.exit(data.testRunEnded.failures)
}, 100)
} else if (data.sendEvent) {
page.sendEvent.apply(page, data.sendEvent)
}
}
return true
}
page.onLoadFinished = function(status) {
page.onLoadFinished = null
if (status !== 'success') {
fail('Failed to load the page. Check the url: ' + url)
return
}
var loadTimeout = config.loadTimeout || 10000
setTimeout(function() {
if (!configured) {
if (page.evaluate(function() { return !window.mocha })) {
fail('mocha was not found in the page within ' + loadTimeout + 'ms of the page loading.')
} else if (page.evaluate(function() { return window.initMochaPhantomJS })) {
fail('Likely due to external resource loading and timing, your tests require calling `window.initMochaPhantomJS()` before calling any mocha setup functions. See https://github.com/nathanboktae/mocha-phantomjs-core/issues/12')
} else {
fail('mocha was not initialized within ' + loadTimeout + 'ms of the page loading. Make sure to call `mocha.ui` or `mocha.setup`.')
}
} else if (!runStarted) {
fail('mocha.run() was not called within ' + loadTimeout + 'ms of the page loading.')
}
}, loadTimeout)
}
function configureMocha() {
page.evaluate(function(config, env) {
mocha.env = env
mocha.useColors(config.useColors)
mocha.bail(config.bail)
if (config.timeout) {
mocha.timeout(config.timeout)
}
if (config.grep) {
mocha.grep(config.grep)
}
if (config.invert) {
mocha.invert()
}
}, config, system.env)
// setup a the reporter
if (page.evaluate(setupReporter, reporter) !== true) {
// we failed to set the reporter - likely a 3rd party reporter than needs to be wrapped
try {
var customReporter = fs.read(reporter)
} catch(e) {
fail('Unable to open file \'' + reporter + '\'')
}
var wrapper = function() {
var exports, module, process, require;
require = function(what) {
what = what.replace(/[^a-zA-Z0-9]/g, '')
for (var r in Mocha.reporters) {
if (r.toLowerCase() === what) {
return Mocha.reporters[r]
}
}
throw new Error("Your custom reporter tried to require '" + what + "', but Mocha is not running in Node.js in mocha-phantomjs, so Node modules cannot be required - only other reporters");
};
module = {};
exports = undefined;
process = Mocha.process;
'customreporter';
return Mocha.reporters.Custom = exports || module.exports;
},
wrappedReporter = wrapper.toString().replace("'customreporter'", "(function() {" + (customReporter.toString()) + "})()")
page.evaluate(wrappedReporter)
if (page.evaluate(function() { return !Mocha.reporters.Custom }) ||
page.evaluate(setupReporter) !== true) {
fail('Failed to use load and use the custom reporter ' + reporter)
}
}
if (typeof config.hooks.beforeStart === 'function') {
config.hooks.beforeStart(hookData)
}
configured = true
}
function setupReporter(reporter) {
try {
mocha.setup({
reporter: reporter || Mocha.reporters.Custom
})
return true
} catch (error) {
return error
}
}