index.js
9.17 KB
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
/**
* 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 webdriver = require('selenium-webdriver');
/**
* Wraps a function so that all passed arguments are ignored.
* @param {!Function} fn The function to wrap.
* @return {!Function} The wrapped function.
*/
function seal(fn) {
return function() {
fn();
};
}
/**
* 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 && Object.prototype.toString.call(functionToValidate) === '[object 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');
}
}
/**
* Wraps a function so it runs inside a webdriver.promise.ControlFlow and
* waits for the flow to complete before continuing.
* @param {!Function} globalFn The function to wrap.
* @return {!Function} The new function.
*/
function wrapInControlFlow(flow, 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;
testFn = fn.bind(this);
flow.execute(function controlFlowExecute() {
return new webdriver.promise.Promise(function(fulfill, reject) {
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 = function(err) {
var wrappedErr = new Error(err);
reject(wrappedErr);
};
testFn(proxyDone);
} else {
// Without a callback, testFn can return a promise, or it will
// be assumed to have completed synchronously.
fulfill(testFn());
}
}, flow);
}, 'Run ' + fnName + description + ' in control flow').then(seal(done), function(err) {
if (!err) {
err = new Error('Unknown Error');
err.stack = '';
}
err.stack = err.stack + '\nFrom asynchronous test: \n' + driverError.stack;
done.fail(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 webdriver instance. We
* pass webdriver here instead of using require() in order to ensure Protractor
* and Jasminews are using the same webdriver instance.
* @param {Object} flow. The ControlFlow to wrap tests in.
*/
function initJasmineWd(flow) {
if (jasmine.JasmineWdInitialized) {
throw Error('JasmineWd already initialized when init() was called');
}
jasmine.JasmineWdInitialized = true;
global.it = wrapInControlFlow(flow, global.it, 'it');
global.fit = wrapInControlFlow(flow, global.fit, 'fit');
global.beforeEach = wrapInControlFlow(flow, global.beforeEach, 'beforeEach');
global.afterEach = wrapInControlFlow(flow, global.afterEach, 'afterEach');
global.beforeAll = wrapInControlFlow(flow, global.beforeAll, 'beforeAll');
global.afterAll = wrapInControlFlow(flow, global.afterAll, 'afterAll');
// 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.');
flow.reset();
}));
}
var originalExpect = global.expect;
global.expect = function(actual) {
if (actual instanceof webdriver.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.
*/
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/, '');
if (!webdriver.promise.isPromise(expectation.actual) &&
!webdriver.promise.isPromise(expected)) {
compare(expectation.actual, expected);
} else {
webdriver.promise.when(expectation.actual).then(function(actual) {
return webdriver.promise.all(expected).then(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);
if (webdriver.promise.isPromise(result.pass)) {
return webdriver.promise.when(result.pass).then(compareDone);
} else {
return compareDone(result.pass);
}
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();
} 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);
if (webdriver.promise.isPromise(result.pass)) {
result.pass = result.pass.then(function(pass) {
return !pass;
});
} else {
result.pass = !result.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;