/
locator.js
338 lines (277 loc) · 9.12 KB
/
locator.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
const {By, RelativeBy, until} = require('selenium-webdriver');
const Element = require('./index.js');
const ElementsByRecursion = require('./locate/elements-by-recursion.js');
const SingleElementByRecursion = require('./locate/single-element-by-recursion.js');
const availableLocators = {
'css selector': 'css',
'id': 'id',
'link text': 'linkText',
'name': 'name',
'partial link text': 'partialLinkText',
'tag name': 'tagName',
'xpath': 'xpath',
'className': 'className'
};
class LocateElement {
/**
* @param {object|string} element
* @return {Element|By|RelativeBy}
*/
static create(element) {
if (!element) {
throw new Error(`Error while trying to locate element: missing element definition; got: "${element}".`);
}
if (element instanceof By) {
return element;
}
if (element.by instanceof By) {
return element.by;
}
if (element.value instanceof RelativeBy) {
return element.value;
}
if (typeof element != 'object' && typeof element != 'string') {
throw new Error(`Invalid element definition type; expected string or object, but got: ${typeof element}.`);
}
let selector;
let strategy;
if (typeof element == 'object' && element.value && element.using) {
selector = element.value;
strategy = element.using;
} else {
selector = element;
}
return Element.createFromSelector(selector, strategy);
}
get api() {
return this.nightwatchInstance.api;
}
get reporter() {
return this.nightwatchInstance.reporter;
}
get settings() {
return this.nightwatchInstance.settings;
}
get transport() {
return this.nightwatchInstance.transport;
}
get desiredCapabilities() {
return this.nightwatchInstance.session.desiredCapabilities;
}
constructor(nightwatchInstance) {
this.nightwatchInstance = nightwatchInstance;
}
resolveElementRecursively({element}) {
return this.findElement({element}).then(response => {
const firstElement = element.selector[element.selector.length - 1];
firstElement.resolvedElement = response;
const {selector, locateStrategy, name} = firstElement;
const {status, value} = response;
const WebdriverElementId = response && response.WebdriverElementId || null;
const result = {
selector,
locateStrategy,
name,
WebdriverElementId,
response: {
status,
value
}
};
if (!isNaN(firstElement.index)) {
result.index = firstElement.index;
}
return result;
});
}
/**
* Finds a single element by using the multiple locate elements, which instead of throwing an error returns an empty array
*
* @param {Element} element
* @param {String} commandName
* @param {String} id
* @param {String} transportAction
* @param {Boolean} [returnSingleElement]
* @param {Boolean} [cacheElementId]
* @return {Promise}
*/
async findElement({element, commandName, id, transportAction = 'locateMultipleElements', returnSingleElement = true, cacheElementId = true}) {
if (element && (element.webElement || element.webElementId)) {
const elementId = await (element.webElement || element.webElementId).getId();
element.setResolvedElement(elementId);
return {
value: this.transport.toElement(elementId),
status: 0
};
}
if (element.resolvedElement && cacheElementId) {
return Promise.resolve({
value: this.transport.toElement(element.resolvedElement),
status: 0
});
}
if (element.usingRecursion) {
if (transportAction === 'locateSingleElement') {
return this.findSingleElementUsingRecursion(element);
}
return this.findElementsUsingRecursion({element, returnSingleElement});
}
const result = await this.executeProtocolAction({element, commandName, id, transportAction, cacheElementId});
return this.handleLocateElement({result, element, returnSingleElement});
}
locateMultipleElements(element) {
const commandName = 'locateMultipleElements';
const transportAction = 'locateMultipleElements';
return this.executeProtocolAction({element, commandName, transportAction});
}
handleLocateElement({result, element, returnSingleElement}) {
const {status = 0, error} = result || {};
let {value} = result;
if (error instanceof Error) {
return {
error,
status: -1,
value
};
}
let WebdriverElementId;
const elementResult = this.transport.resolveElement(result, element, true);
if (elementResult) {
WebdriverElementId = this.transport.getElementId(elementResult);
element.setResolvedElement(WebdriverElementId);
}
if (returnSingleElement) {
value = elementResult;
}
return {
value,
status,
WebdriverElementId
};
}
/**
* @returns Promise({{
* value,
* status,
* result,
* now
* }})
*/
executeProtocolAction(opts = {}) {
const {id, element, transportAction, commandName, cacheElementId} = opts;
const args = {
id
};
if (element instanceof By) {
args.by = element;
} else {
args.using = element.locateStrategy;
args.value = element.selector;
}
return this.sendElementsAction({transportAction, args, element, cacheElementId})
.catch(err => {
if (this.transport.invalidSessionError(err)) {
return new Error(this.transport.getErrorMessage(err));
}
throw err;
})
.then(result => {
if (this.transport.isResultSuccess(result) && Element.requiresFiltering(element)) {
return this.filterElements(element, result);
}
return result;
})
// Catch errors from filterElements and from invalid session
.catch(error => {
return {
value: null,
status: -1,
error
};
});
}
async sendElementsAction({transportAction, args, element, cacheElementId} = {}) {
if (cacheElementId && transportAction === 'locateMultipleElements' && args && !(args.value instanceof RelativeBy)) {
const timeout = element.timeout || this.settings.globals.waitForConditionTimeout;
const retryInterval = element.retryInterval || this.settings.globals.waitForConditionPollInterval;
try {
const results = await this.transport.driver.wait(until.elementsLocated(args), timeout, null, retryInterval);
const {elementKey} = this.transport;
const value = await Promise.all(results.map(async webElement => {
const elementId = await webElement.getId();
return {[elementKey]: elementId};
}));
return {
status: 0,
value
};
} catch (err) {
if (err.name !== 'TimeoutError') {
throw err;
}
throw new NoSuchElementError({element, ms: timeout});
}
}
return this.transport.executeProtocolAction(transportAction, args);
}
/**
* Selects a subset of elements if the result requires filtering.
*
* @param {Element} element
* @param {object} result
* @return {*}
*/
filterElements(element, result) {
let filtered = Element.applyFiltering(element, result.value);
if (filtered) {
result.value = filtered;
return result;
}
const errorResult = this.transport.getElementNotFoundResult(result);
throw new Error(`Element ${element.toString()} not found.${errorResult.message ? (' ' + errorResult.message) : ''}`);
}
/**
* @param {Element} element
* @param {Boolean} returnSingleElement
* @return {Promise}
*/
findElementsUsingRecursion({element, returnSingleElement = true}) {
let recursion = new ElementsByRecursion(this.nightwatchInstance);
return recursion.locateElements({element, returnSingleElement});
}
findSingleElementUsingRecursion(element) {
let recursion = new SingleElementByRecursion(this.nightwatchInstance);
return recursion.locateElement(element.selector);
}
}
class Locator extends LocateElement {
/**
* @param {object|string} element
* @param {boolean} [isAppiumClient]
* @return {By|RelativeBy}
*/
static create(element, isAppiumClient) {
const elementInstance = super.create(element);
if (!(elementInstance instanceof Element)) {
// elementInstance actually an instance of By or RelativeBy
return elementInstance;
}
if (isAppiumClient && elementInstance.locateStrategy === 'id') {
return new By(elementInstance.locateStrategy, elementInstance.selector);
}
return By[availableLocators[elementInstance.locateStrategy]](elementInstance.selector);
}
}
class NoSuchElementError extends Error {
constructor({element, ms, abortOnFailure, retries}) {
super();
this.selector = element.selector;
this.abortOnFailure = abortOnFailure;
this.name = 'NoSuchElementError';
this.retries = retries;
this.strategy = element.locateStrategy;
this.message = `Timed out while waiting for element "${this.selector}" with "${this.strategy}" to be present for ${ms} milliseconds.`;
}
}
module.exports = Locator;
module.exports.NoSuchElementError = NoSuchElementError;