-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathenhancedScripts.html
More file actions
561 lines (513 loc) · 23.6 KB
/
enhancedScripts.html
File metadata and controls
561 lines (513 loc) · 23.6 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
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
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
<!DOCTYPE html>
<html>
<head>
<meta charset='utf-8'>
<meta http-equiv="X-UA-Compatible" content="chrome=1">
<link href='https://fonts.googleapis.com/css?family=Chivo:900' rel='stylesheet' type='text/css'>
<link rel="stylesheet" type="text/css" href="stylesheets/stylesheet.css" media="screen">
<link rel="stylesheet" type="text/css" href="stylesheets/pygment_trac.css" media="screen">
<link rel="stylesheet" type="text/css" href="stylesheets/print.css" media="print">
<link rel="stylesheet" href="//cdnjs.cloudflare.com/ajax/libs/highlight.js/8.3/styles/default.min.css">
<script src="//cdnjs.cloudflare.com/ajax/libs/highlight.js/8.3/highlight.min.js"></script>
<!--[if lt IE 9]>
<script src="//html5shiv.googlecode.com/svn/trunk/html5.js"></script>
<![endif]-->
<script>hljs.initHighlightingOnLoad();</script>
<title>Testing With Node by NickTulett</title>
</head>
<body>
<div id="container">
<div class="inner">
<header>
<h1>Readable test scripts</h1>
<h2></h2>
</header>
<!--
<section id="downloads" class="clearfix">
<a href="https://github.com/NickTulett/TestingWithNode/zipball/master" id="download-zip" class="button">
<span>Download .zip</span>
</a>
<a href="https://github.com/NickTulett/TestingWithNode/tarball/master" id="download-tar-gz" class="button">
<span>Download .tar.gz</span>
</a>
<a href="https://github.com/NickTulett/TestingWithNode" id="view-on-github" class="button">
<span>View on GitHub</span>
</a>
</section>
-->
<hr>
<section id="main_content">
<h2>
<a name="using-nodejs-a-an-automated-test-engine" class="anchor" href="#using-nodejs-a-an-automated-test-engine">
<span class="octicon octicon-link"></span>
</a>Better selectors</h2>
<p>Webdriver-sync is a wrapper around the java webdriver client and out of the box has a very wordy selector syntax (last line):</p>
<pre><code class="javascript">
var wd = require("webdriver-sync");
var caps = new wd.DesiredCapabilities["chrome"]();
var driver = new wd["ChromeDriver"](caps);
var By = wd.By;
var elements = driver.findElements(By.tagName('html'));
</code></pre>
<p>Compared to established front-end frameworks such as jQuery, it's a lot of typing, so let's do something about that.</p>
<h3>Selector types</h3>
<p>What are the selector types in the <a href="https://github.com/jsdevel/webdriver-sync/blob/master/src/classes/By.js">By method</a>?</p>
<ul>
<li>className</li>
<li>cssSelector</li>
<li>id</li>
<li>name</li>
<li>tagName</li>
<li>xpath</li>
<li>linkText</li>
<li>partialLinkText</li>
</ul>
<p>The first 5 are standard HTML element properties and easily resolve to a jQuery selector syntax (other than "name", which I never use as a selector).</p>
<p>Xpath selectors are a law unto themselves, but can be very useful once you get your head around the syntax.</p>
<p>The last 2 are not typical in other selector libraries but can be very useful for testing, so we will implement those as well.</p>
<h3>cssSelector is almost all we need</h3>
<p>cssSelector already covers us for class, id and tag selectors:</p>
<pre><code class="javascript">
// By tagName
var tableBody = driver.findElement(By.cssSelector("tbody"));
// By className
var blueElements = driver.findElements(By.cssSelector(".blue"));
// By id
var silicon = driver.findElement(By.cssSelector("#element14"));
</code></pre>
<p>It also covers us for <a href="http://css-tricks.com/child-and-sibling-selectors/">child and sibling selectors</a></p>
<pre><code class="javascript">
// div followed by a span child element
driver.findElement(By.cssSelector("div span"));
//div with immediate anchor child
driver.findElement(By.cssSelector("div>a"));
//div with adjacent legend
driver.findElement(By.cssSelector("div+legend"));
</code></pre>
<h3>Selectors for AngularJS elements</h3>
<p>Angular relies heavily on custom elements. CSS selectors and <a href="https://developer.mozilla.org/en-US/docs/Web/CSS/Pseudo-classes">pseudo classes</a> have these covered too:</p>
<pre><code class="javascript">
// angular button with ng-click event
driver.findElement(By.cssSelector("button[ng-click='openFileUploadDialog()']"));
// angular button in 3rd table row built by ng-repeat
driver.findElement(By.cssSelector("tr[ng-repeat='variation in model.variations']
:nth-child(2) button[ng-click='checkReRunModel(variation)']"));
</code></pre>
<h3>Text content and Xpath selectors</h3>
<p>I haven't found linkText to be useful and just use partialLinkText for links. Obviously this depends on how uniquely your links are worded.</p>
<p>Generalising the text selectors for any element means relying on Xpath:</p>
<pre><code class="javascript">
// By exact text content
var abortButton = driver.findElement(By.xpath("//*[text()='Abort!']"));
// By contains text
var allTheThings = driver.findElements(By.xpath("//*[contains(text(),'Thing')]"));
// parent element
driver.findElements(By.xpath(".."))
</code></pre>
<p>Xpath selectors offer a flexible interface to navigate the DOM, but at a price in performance. Where possible, try to identify the equivalent CSS selector first as this will offer a 5-10x speed increase over Xpath. For text and parent selectors, Xpath is currently the only option.</p>
<h3>Better selectors</h3>
<p>So far all we've done is remove some of the redundant selector types and generalise the text ones. The syntax still isn't exactly concise.</p>
<p>This is where we look back and say "What would jQuery do?". Well, something like this:</p>
<pre><code class="javascript">
// By tagName
var tableBody = $("tbody");
// By className
var blueElements = $(".blue");
// By id
var silicon = $("#element14");
//By partial link text
var nextPageLink = $("^Next");
// By exact text content
// (note the nested quotes now)
var abortButton = $("'Abort!'");
// By contains text
var allTheThings = $("*Thing*");
// By parent element
var listContainer =
$("ul.containedList").$("parent");
// By partial attribute
var visibleCalendar =
$("ul[ng-change='dateSelection()'][style*='display: block']");
</code></pre>
<p>OK so that's concise and consistent and reasonably easy to follow, so how is it done?
<!-- Will need to replace the text selectors and advise against using xpath -->
<!-- and check the xpath chaining -->
<pre><code class="javascript">
function $by(selector) {
//first character indicates the selection type
var by = selector.slice(0,1);
if (by.match(/(\.|#|\w)/)) {
by = "cssSelector";
}
if (by === "^") {
by = "partialLinkText";
selector = selector.slice(1);
}
if (by === "*") {
by = "xpath";
selector = "//*[contains(text(),'"
+ selector.slice(1, -1) + "')]";
}
if (by === "'") {
by = "xpath";
selector = "//*[text()=" + selector + "]";
}
if (by === "@") {
by = "xpath";
selector = "//*[" + selector + "]";
}
if (selector.slice(0,2) === "//") {
by = "xpath";
}
console.log("LOCATING ELEMENT " + selector + " BY " + by);
return By[by](selector);
}
</code></pre>
<p>Note that this does not give us the $ method yet, we're reserving that for a general element handler, below.</p>
<h3>General element handler</h3>
<p>Selecting an element is only half the story, testing will involve reading its text, checking its properties, pushing its buttons, etc. So we extend our selector approach to dealing with elements generally.</p>
<p>What sorts of things will we do with elements?</p>
<ul>
<li>Select single elements</li>
<li>Select multiple elements</li>
<li>Select child element(s)</li>
<li>Select parent element</li>
<li>Click element</li>
<li>Right-click element</li>
<li>Hover over element</li>
<li>Scroll to element</li>
<li>Read element value</li>
<li>Set element value</li>
<li>Trigger element event</li>
<li>Show element's dropdown menu</li>
<li>Enumerate element lists</li>
</ul>
<p>Let's put all that together (extending the above $by method for parent selection):</p>
<pre><code class="javascript">
function WD_findElement(selector, root, index) {
if (!selector) {
console.error("NO SELECTOR SPECIFIED FOR $()");
return null;
}
//replace the verbose By syntax with sizzle-like succint selectors
function $by(selector) {
root = root || driver;
var by = selector.slice(0,1);
if (by.match(/(\.|#|\w|\[)/)) {
by = "cssSelector";
}
if (by === "^") {
by = "partialLinkText";
selector = selector.slice(1);
}
//wildcard text content selector
if (by === "*") {
by = "xpath";
selector = "//*[contains(text(),'" + selector.slice(1, -1) + "')]";
}
//literal text content selector
if (by === "'") {
by = "xpath";
selector = "//*[text()=" + selector + "]";
}
if (by === "@") {
by = "xpath";
selector = "//*[" + selector + "]";
}
if (selector.slice(0,2) === "//") {
by = "xpath";
if (root != driver) {//sub-element needs to search from current element not doc root
selector = "." + selector;
}
}
if (selector === "parent") {
by = "xpath";
selector = "..";
}
console.log("LOCATING ELEMENT " + selector + " BY " + by);
return By[by](selector);
}
//ultimately findElement returns a WebElement or array of WebElements
//here we add some extra methods and properties useful for testing
function augmentedElement(element, elementIndex) {
element.selector = selector;
if (element.length) {
element = element[elementIndex || 0];
}
element["$"] = function subElement(sel, subindex) {
return WD_findElement(sel, element, subindex);
};
//bit of syntactic sugar as getAttribute is a pain to type
element["_"] = function element_getAttribute(attr) {
return element.getAttribute(attr);
};
element.scrollTo = function scrollTo() {
driver.executeScript("arguments[0].scrollIntoView(true)", element._instance);
};
element.set = function setValue(newValue) {
console.log("SETTING VALUE " + (selector.match(/password/)
? "********" : ("" + newValue)));
if ((element.getAttribute("type") !== "file")
&& (element.getAttribute("nodeName") !== "SELECT")) {
element.clear();
}
return element.sendKeys(newValue);
};
element.trigger = function trigger(action) {
driver.executeScript("$(arguments[0]).trigger('" + action + "')", element._instance);
};
element.dropdown = function dropdown() {
driver.executeScript("$(arguments[0]).next().show()", element._instance);
};
element.setAttribute = function dropdown(attr, value) {
driver.executeScript("$(arguments[0]).attr('" + attr + "', '" + value + "')",
element._instance);
};
element.hover = function hover(x, y) {
if (arguments.length) {
driver.getMouse()._instance
.mouseMoveSync(element._instance.getCoordinatesSync(), ~~x, ~~y);
} else {
driver.getMouse()._instance
.mouseMoveSync(element._instance.getCoordinatesSync());
}
};
element.coordinates = function coordinates () {
//returns the on-page coordinates as a simple JSON object, e.g. {"y": 345, "x": 1237}
return element._instance.getCoordinatesSync().onPageSync();
};
element.rClick = function rClick() {
driver.getMouse()._instance.contextClickSync(element._instance.getCoordinatesSync());
};
element.clickAt = function clickAt(xOffset, yOffset) {
var elementCoordinates = element.coordinates();
browser.getMouse()._instance.clickSync(
{y: elementCoordinates.y + yOffset,
x: elementCoordinates.x + xOffset});
};
element.isChecked = function () {
return element.getAttribute("checked") === true;
};
element.forEach = element.map = function only(fn) {
return fn(element, 0);
};
element.length = 1;
return element;
}
var element;
if (typeof root != "object") {
index = root;
root = driver;
}
var indexSet = (typeof index === "number");
var firstElement = indexSet && (index === 0);
try {
element = firstElement
? [root.findElement($by(selector))] : root.findElements($by(selector));
} catch (e) {
return {
length: 0
};
}
var elementIndex = index || 0;
if (element) {
if ((!element.length) || (indexSet && indexSet > element.length)) {
element.isDisplayed = function elementNotPresent() {
return false;
};
element.getText = function elementNotPresentText() {
return "";
};
return element;
}
if ((element.length === 1) || indexSet) {
return augmentedElement(element, elementIndex);
} else {
return element.map(augmentedElement);
}
} else {
console.error(selector + " not found");
}
return element;
}
</code></pre>
<p>An example of what you would do with a map method is extracting the text of a list of elements:</p>
<pre><code class="javascript">
var legend = $(".nv-legendWrap text").map(function (barLegend) {
return barLegend.getText();
}).join();
</code></pre>
<p>Here I'm joining the text in the elements into a single string (for easy comparison with expected values).</p>
<p>You may have noticed that we still don't have a $ method - that will come when we modularise our scripts.</p>
<h3>More readable selectors</h3>
<p>Even with the concise selector syntax, it may not be obvious what the selector refers to if it is particularly complex.</p>
<p>e.g. what happens if I click this?</p>
<pre><code class="javascript">
$("//ul[contains(@class, 'navbar')]//a[starts-with(@href, '/user/show/')]");
</code></pre>
<p>This where I introduced the idea of locators to keep the scripts readable, by giving selectors more human-friendly aliases:</p>
<pre><code class="javascript">
locators = {
"Signed In User Link":
"//ul[contains(@class, 'navbar')]//a[starts-with(@href, '/user/show/')]",
"Other complicated selector":
"horrendous Xpath"
//etc.
}
</code></pre>
<p>Then I decided to have an alternative to things like $([locator resolved to selector]).click():</p>
<pre><code class="javascript">
function button(buttonorlink, index) {
return $(locators[buttonorlink] || null, index);
}
function link(buttonorlink, index) {
return button(buttonorlink, index);
}
function tab(tabName, index) {
return button(tabName + " Tab", index);
}
function click(buttonorlink, checkStateOrIndex) {
if (typeof checkStateOrIndex == "number") {//actually the button index
return button(buttonorlink, checkStateOrIndex).click();
}
var clickable = button(buttonorlink);
if (clickable) {
//mung checked atribute to a Boolean
if (arguments.length == 1 || (!!clickable.getAttribute("checked") != checkState)) {
clickable.click();
}
}
}
</code></pre>
<p>So eventually we get from:</p>
<pre><code class="javascript">
driver.findElements(By.xpath(
"//ul[contains(@class, 'navbar')]//a[starts-with(@href, '/user/show/')]")).click();
</code></pre>
<p>to:</p>
<pre><code class="javascript">
click("Signed In User Link");
</code></pre>
<p>Then you also get the benefit of only having to change the selector in one place in your scripts when it changes.</p>
<h2>Browser navigation</h2>
<h3>Navigating to a page</h3>
<p>webdriver has a get() method to navigate to a URL, but that's a bit boring, so to save time only navigate if the page is different and log the timestamp and url for later troubleshooting:</p>
<pre><code class="javascript">
function WD_go(url) {
if (driver.getCurrentUrl() != url) {
console.log(new Date());
console.log("NAVIGATING TO " + url);
driver.get(url);
}
}
</code></pre>
<h3>Getting a JSON response</h3>
<p>Sometimes you just want to test the data returned to a page, rather than the page itself. This is easy enough to do by running javascript in the browser instance (as we did for dropdown and other element methods above):</p>
<pre><code class="javascript">
function WD_getJSON(url) {
var xhr = driver.executeScript(
"xhr = new XMLHttpRequest();" +
"xhr.open('GET', '" + url + "', false);" +
"xhr.send();" +
"return (xhr.status + '###' + xhr.responseText);"
);
xhr = xhr.split("###");
return {status: xhr[0], responseText: xhr[1]};
}
</code></pre>
<h3>Checking headers</h3>
<p>Similarly, we can request just the headers for a particular response (for instance you might want to check for a 404 or a particular content-type):</p>
<pre><code class="javascript">
function WD_getHeaders(url, specificHeader) {
var xhr_headers = driver.executeScript(
"xhr = new XMLHttpRequest();" +
"xhr.open('GET', '" + url + "', false);" +
"xhr.setRequestHeader('Accept-Encoding', 'gzip');" +
"xhr.send();" +
(specificHeader ?
"return xhr.getResponseHeader('" + specificHeader + "');" :
"return xhr.getAllResponseHeaders();"
)
);
return xhr_headers;
}
</code></pre>
<h2>Waiting for elements</h2>
<p>I started using webdriver-sync before the <a href="https://github.com/jsdevel/webdriver-sync/blob/master/test/classes/WebDriverWait.js">WebDriverWait</a> class was implemented and ended up writing my own waitFor method. This is used when there may be some delay in rendering an element. It has a default timeout that can be overriden.</p>
<pre><code class="javascript">
function waitFor(msg, selector, index) {
var waitTime = 60;
//no point waiting for longer than a minute because request will have timed out
//arguments can be overriden depending on type
//should probably use a parameters object and keep it tidy
if (typeof msg == "number") {
waitTime = arguments[0];
msg = arguments[1];
selector = arguments[2];
index = arguments[3] || null;
}
//selector could be a bare selector or a locator (see above)
if (locators[msg]) {
selector = locators[msg];
msg = msg.toUpperCase();
}
var foundElement, elementList;
console.log("WAITING " + waitTime + " SECONDS FOR " + msg);
while (!(foundElement = $(selector)).length) {
Delay(1e3, true);
--waitTime;
if (!waitTime) {
if (typeof arguments[3] !== "boolean") {
log.error("TIMED OUT");
}
return false;
}
}
//handle single elements
if (foundElement.length === 1) {
while (!(foundElement = $(selector)).isDisplayed()) {
console.log("WAITING FOR " + msg + " TO APPEAR");
Delay(1e3);
}
return foundElement;
}
if (typeof index === "number") {
while (!(foundElement = $(selector)[index]).isDisplayed()) {
console.log("WAITING FOR " + msg + " TO APPEAR");
Delay(1e3);
}
return foundElement;
}
//found a list of elements
elementList = foundElement;
elementList.every(function (el) {
if (el.isDisplayed()) {
foundElement = el;
return false;
}
console.log("WAITING FOR " + msg + " TO APPEAR");
Delay(1e3);
return true;
});
return foundElement;
}
</code></pre>
<p>waitFor() will post a message to the log saying which element is being waited for and wait up to a minute (or a specified timeout value) before abandoning. There are a number of ways waitFor can be called:</p>
<pre><code class="javascript">
//using a locator (and default timeout)
waitFor("Utility Power Actuals Link");
//using a selector and index
waitFor("ACTUALS BUTTON", "'Sub-metering actuals'", 2);
//using a specific timeout
waitFor(20, "VARIANCE CHART", ".barchart");
</code></pre>
<a href="modularScripts.html">Next: Modular scripts</a>
</section>
<footer>
<a href="/TestingWithNode/">Testing With Node</a> is maintained by <a href="https://github.com/NickTulett">NickTulett</a>
<br>This page was generated by <a href="http://pages.github.com">GitHub Pages</a>. Tactile theme by <a href="https://twitter.com/jasonlong">Jason Long</a>.
</footer>
</div>
</div>
</body>
</html>