-
Notifications
You must be signed in to change notification settings - Fork 0
/
utils.js
97 lines (92 loc) · 3.43 KB
/
utils.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
var async = require('asyncawait/async'),
await = require('asyncawait/await'),
webdriver = require('selenium-webdriver');
function makeTimeoutPromise(originalFunction, maxRuntime) {
return function() {
var originalArguments = arguments,
p = new Promise(function(resolve, reject) {
var errStack = (new Error()).stack,
timeout = maxRuntime ? setTimeout(function() {
reject("Promise timed out after "
+maxRuntime+"ms\n"+errStack);
}, maxRuntime) : undefined;
this.resolve = function(result) {
clearTimeout(timeout);
resolve(result);
};
this.reject = function(result) {
clearTimeout(timeout);
reject(result+"\n"+errStack);
};
try {
originalFunction.apply(this, originalArguments);
} catch(e) {
clearTimeout(timeout);
reject("An exception occurred: "+e.toString()+errStack);
}
}.bind(new Object()));
return p;
};
}
function sleep(milliseconds) {
await(new Promise(function(resolve, reject) {
setTimeout(function() {
resolve(true);
}, milliseconds);
}));
}
function awaitWebElements(obj) {
var myObjs;
if(obj instanceof webdriver.WebElement) {
myObjs = [obj];
} else if(obj instanceof Array &&
obj[0] instanceof webdriver.WebElement) {
myObjs = obj;
} else {
return obj;
}
myObjs.forEach(function(element) {
var methods = ["click","getText","getAttribute","findElement",
"findElements","getCssValue","getId","getLocation",
"getSize","getTagName","isDisplayed","isEnabled",
"sendKeys","clear","isSelected","submit",
"takeScreenshot"];
element._origMethods = {};
methods.forEach(function(method) {
if(!element[method]) {
return;
}
element._origMethods[method] = element[method];
element[method] = function() {
var retval = await(element._origMethods[method]
.apply(this, arguments));
//Why? Because WebElement.findElement(s)
return awaitWebElements(retval);
};
});
});
if(obj instanceof Array) {
return myObjs;
} else {
return obj;
}
}
function awaitSeleniumDriver(d) {
var methods = ["quit","get","findElement","findElements",
"getCurrentUrl","getPageSource","getSession",
"getTitle","sleep","takeScreenshot","wait",
"call","close","executeScript","getAllWindowHandles",
"getCapabilities","getWindowHandle",
"switchTo"];
d._origMethods = {};
methods.forEach(function(method) {
d._origMethods[method] = d[method];
d[method] = function() {
var retval = await(d._origMethods[method].apply(this, arguments));
return d._awaitWebElements ? awaitWebElements(retval) : retval;
};
});
}
exports.makeTimeoutPromise = makeTimeoutPromise;
exports.sleep = sleep;
exports.awaitSeleniumDriver = awaitSeleniumDriver;