-
Notifications
You must be signed in to change notification settings - Fork 36
/
Copy pathindex.js
354 lines (319 loc) · 11.8 KB
/
index.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
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
/**
* Adapts Jasmine-Node tests to work better with WebDriverJS. Borrows
* heavily from the mocha WebDriverJS adapter at
* https://code.google.com/p/selenium/source/browse/javascript/node/selenium-webdriver/testing/index.js
*/
var WebElement; // Equal to webdriver.WebElement
var idleEventName = 'idle'; // Equal to webdriver.promise.ControlFlow.EventType.IDLE
var maybePromise = require('./maybePromise');
/**
* Validates that the parameter is a function.
* @param {Object} functionToValidate The function to validate.
* @throws {Error}
* @return {Object} The original parameter.
*/
function validateFunction(functionToValidate) {
if (functionToValidate && typeof functionToValidate === 'function') {
return functionToValidate;
} else {
throw Error(functionToValidate + ' is not a function');
}
}
/**
* Validates that the parameter is a number.
* @param {Object} numberToValidate The number to validate.
* @throws {Error}
* @return {Object} The original number.
*/
function validateNumber(numberToValidate) {
if (!isNaN(numberToValidate)) {
return numberToValidate;
} else {
throw Error(numberToValidate + ' is not a number');
}
}
/**
* Validates that the parameter is a string.
* @param {Object} stringToValidate The string to validate.
* @throws {Error}
* @return {Object} The original string.
*/
function validateString(stringtoValidate) {
if (typeof stringtoValidate == 'string' || stringtoValidate instanceof String) {
return stringtoValidate;
} else {
throw Error(stringtoValidate + ' is not a string');
}
}
/**
* Calls a function once the scheduler is idle. If the scheduler does not support the idle API,
* calls the function immediately. See scheduler.md#idle-api for details.
*
* @param {Object} scheduler The scheduler to wait for.
* @param {!Function} fn The function to call.
*/
function callWhenIdle(scheduler, fn) {
if (!scheduler.once || !scheduler.isIdle || scheduler.isIdle()) {
fn();
} else {
scheduler.once(idleEventName, function() { fn(); });
}
}
/**
* Wraps a function so it runs inside a scheduler's `execute()` block.
*
* In the most common case, this means wrapping in a `webdriver.promise.ControlFlow` instance
* to wait for the control flow to complete one task before starting the next. See scheduler.md
* for details.
*
* @param {!Object} scheduler See scheduler.md for details.
* @param {!Function} newPromise Makes a new promise using whatever implementation the scheduler
* prefers.
* @param {!Function} globalFn The function to wrap.
* @param {!string} fnName The name of the function being wrapped (e.g. `'it'`).
* @return {!Function} The new function.
*/
function wrapInScheduler(scheduler, newPromise, globalFn, fnName) {
return function() {
var driverError = new Error();
driverError.stack = driverError.stack.replace(/ +at.+jasminewd.+\n/, '');
function asyncTestFn(fn, description) {
description = description ? ('("' + description + '")') : '';
return function(done) {
var async = fn.length > 0;
var testFn = fn.bind(this);
scheduler.execute(function schedulerExecute() {
return newPromise(function(fulfill, reject) {
function wrappedReject(err) {
if(err instanceof Error)
reject(err);
else
reject(new Error(err));
}
if (async) {
// If testFn is async (it expects a done callback), resolve the promise of this
// test whenever that callback says to. Any promises returned from testFn are
// ignored.
var proxyDone = fulfill;
proxyDone.fail = wrappedReject;
testFn(proxyDone);
} else {
// Without a callback, testFn can return a promise, or it will
// be assumed to have completed synchronously.
var ret = testFn();
if (maybePromise.isPromise(ret)) {
ret.then(fulfill, wrappedReject);
} else {
fulfill(ret);
}
}
});
}, 'Run ' + fnName + description + ' in control flow').then(
callWhenIdle.bind(null, scheduler, done), function(err) {
if (!err) {
err = new Error('Unknown Error');
err.stack = '';
}
err.stack = err.stack + '\nFrom asynchronous test: \n' + driverError.stack;
callWhenIdle(scheduler, done.fail.bind(done, err));
}
);
};
}
var description, func, timeout;
switch (fnName) {
case 'it':
case 'fit':
description = validateString(arguments[0]);
if (!arguments[1]) {
return globalFn(description);
}
func = validateFunction(arguments[1]);
if (!arguments[2]) {
return globalFn(description, asyncTestFn(func, description));
} else {
timeout = validateNumber(arguments[2]);
return globalFn(description, asyncTestFn(func, description), timeout);
}
break;
case 'beforeEach':
case 'afterEach':
case 'beforeAll':
case 'afterAll':
func = validateFunction(arguments[0]);
if (!arguments[1]) {
globalFn(asyncTestFn(func));
} else {
timeout = validateNumber(arguments[1]);
globalFn(asyncTestFn(func), timeout);
}
break;
default:
throw Error('invalid function: ' + fnName);
}
};
}
/**
* Initialize the JasmineWd adapter with a particlar scheduler, generally a webdriver control flow.
*
* @param {Object=} scheduler The scheduler to wrap tests in. See scheduler.md for details.
* Defaults to a mock scheduler that calls functions immediately.
* @param {Object=} webdriver The result of `require('selenium-webdriver')`. Passed in here rather
* than required by jasminewd directly so that jasminewd can't end up up with a different version
* of `selenium-webdriver` than your tests use. If not specified, jasminewd will still work, but
* it won't check for `WebElement` instances in expect() statements and could cause control flow
* problems if your tests are using an old version of `selenium-webdriver` (e.g. version 2.53.0).
*/
function initJasmineWd(scheduler, webdriver) {
if (jasmine.JasmineWdInitialized) {
throw Error('JasmineWd already initialized when init() was called');
}
jasmine.JasmineWdInitialized = true;
// Pull information from webdriver instance
if (webdriver) {
WebElement = webdriver.WebElement || WebElement;
idleEventName = (
webdriver.promise &&
webdriver.promise.ControlFlow &&
webdriver.promise.ControlFlow.EventType &&
webdriver.promise.ControlFlow.EventType.IDLE
) || idleEventname;
}
// Default to mock scheduler
if (!scheduler) {
scheduler = { execute: function(fn) {
return Promise.resolve().then(fn);
} };
}
// Figure out how we're getting new promises
var newPromise;
if (typeof scheduler.promise == 'function') {
newPromise = scheduler.promise.bind(scheduler);
} else if (webdriver && webdriver.promise && webdriver.promise.ControlFlow &&
(scheduler instanceof webdriver.promise.ControlFlow) &&
(webdriver.promise.USE_PROMISE_MANAGER !== false)) {
newPromise = function(resolver) {
return new webdriver.promise.Promise(resolver, scheduler);
};
} else {
newPromise = function(resolver) {
return new Promise(resolver);
};
}
// Wrap functions
global.it = wrapInScheduler(scheduler, newPromise, global.it, 'it');
global.fit = wrapInScheduler(scheduler, newPromise, global.fit, 'fit');
global.beforeEach = wrapInScheduler(scheduler, newPromise, global.beforeEach, 'beforeEach');
global.afterEach = wrapInScheduler(scheduler, newPromise, global.afterEach, 'afterEach');
global.beforeAll = wrapInScheduler(scheduler, newPromise, global.beforeAll, 'beforeAll');
global.afterAll = wrapInScheduler(scheduler, newPromise, global.afterAll, 'afterAll');
// Reset API
if (scheduler.reset) {
// On timeout, the flow should be reset. This will prevent webdriver tasks
// from overflowing into the next test and causing it to fail or timeout
// as well. This is done in the reporter instead of an afterEach block
// to ensure that it runs after any afterEach() blocks with webdriver tasks
// get to complete first.
jasmine.getEnv().addReporter(new OnTimeoutReporter(function() {
console.warn('A Jasmine spec timed out. Resetting the WebDriver Control Flow.');
scheduler.reset();
}));
}
}
var originalExpect = global.expect;
global.expect = function(actual) {
if (WebElement && (actual instanceof WebElement)) {
throw Error('expect called with WebElement argument, expected a Promise. ' +
'Did you mean to use .getText()?');
}
return originalExpect(actual);
};
/**
* Creates a matcher wrapper that resolves any promises given for actual and
* expected values, as well as the `pass` property of the result.
*
* Wrapped matchers will return either `undefined` or a promise which resolves
* when the matcher is complete, depending on if the matcher had to resolve any
* promises.
*/
jasmine.Expectation.prototype.wrapCompare = function(name, matcherFactory) {
return function() {
var expected = Array.prototype.slice.call(arguments, 0),
expectation = this,
matchError = new Error("Failed expectation");
matchError.stack = matchError.stack.replace(/ +at.+jasminewd.+\n/, '');
// Return either undefined or a promise of undefined
return maybePromise(expectation.actual, function(actual) {
return maybePromise.all(expected, function(expected) {
return compare(actual, expected);
});
});
function compare(actual, expected) {
var args = expected.slice(0);
args.unshift(actual);
var matcher = matcherFactory(expectation.util, expectation.customEqualityTesters);
var matcherCompare = matcher.compare;
if (expectation.isNot) {
matcherCompare = matcher.negativeCompare || defaultNegativeCompare;
}
var result = matcherCompare.apply(null, args);
return maybePromise(result.pass, compareDone);
// compareDone always returns undefined
function compareDone(pass) {
var message = '';
if (!pass) {
if (!result.message) {
args.unshift(expectation.isNot);
args.unshift(name);
message = expectation.util.buildFailureMessage.apply(null, args);
} else {
if (Object.prototype.toString.apply(result.message) === '[object Function]') {
message = result.message(expectation.isNot);
} else {
message = result.message;
}
}
}
if (expected.length == 1) {
expected = expected[0];
}
var res = {
matcherName: name,
passed: pass,
message: message,
actual: actual,
expected: expected,
error: matchError
};
expectation.addExpectationResult(pass, res);
}
function defaultNegativeCompare() {
var result = matcher.compare.apply(null, args);
result.pass = maybePromise(result.pass, function(pass) {
return !pass;
});
return result;
}
}
};
};
// Re-add core matchers so they are wrapped.
jasmine.Expectation.addCoreMatchers(jasmine.matchers);
/**
* A Jasmine reporter which does nothing but execute the input function
* on a timeout failure.
*/
var OnTimeoutReporter = function(fn) {
this.callback = fn;
};
OnTimeoutReporter.prototype.specDone = function(result) {
if (result.status === 'failed') {
for (var i = 0; i < result.failedExpectations.length; i++) {
var failureMessage = result.failedExpectations[i].message;
if (failureMessage.match(/Timeout/)) {
this.callback();
}
}
}
};
module.exports.init = initJasmineWd;