-
-
Notifications
You must be signed in to change notification settings - Fork 719
/
WebDriverIO.js
1953 lines (1752 loc) · 59.3 KB
/
WebDriverIO.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
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
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
let webdriverio;
const requireg = require('requireg');
const Helper = require('../helper');
const stringIncludes = require('../assert/include').includes;
const { urlEquals, equals } = require('../assert/equal');
const empty = require('../assert/empty').empty;
const truth = require('../assert/truth').truth;
const {
xpathLocator, fileExists, clearString, decodeUrl, chunkArray,
} = require('../utils');
const ElementNotFound = require('./errors/ElementNotFound');
const assert = require('assert');
const path = require('path');
const webRoot = 'body';
const Locator = require('../locator');
let withinStore = {};
/**
* WebDriverIO helper which wraps [webdriverio](http://webdriver.io/) library to
* manipulate browser using Selenium WebDriver or PhantomJS.
*
* WebDriverIO requires [Selenium Server and ChromeDriver/GeckoDriver to be installed](http://codecept.io/quickstart/#prepare-selenium-server).
*
* ### Configuration
*
* This helper should be configured in codecept.json
*
* * `url` - base url of website to be tested
* * `browser` - browser in which perform testing
* * `restart` (optional, default: true) - restart browser between tests.
* * `smartWait`: (optional) **enables [SmartWait](http://codecept.io/acceptance/#smartwait)**; wait for additional milliseconds for element to appear. Enable for 5 secs: "smartWait": 5000
* * `disableScreenshots` (optional, default: false) - don't save screenshot on failure
* * `uniqueScreenshotNames` (optional, default: false) - option to prevent screenshot override if you have scenarios with the same name in different suites
* * `keepBrowserState` (optional, default: false) - keep browser state between tests when `restart` set to false.
* * `keepCookies` (optional, default: false) - keep cookies between tests when `restart` set to false.
* * `windowSize`: (optional) default window size. Set to `maximize` or a dimension in the format `640x480`.
* * `waitForTimeout`: (option) sets default wait time in *ms* for all `wait*` functions. 1000 by default;
* * `desiredCapabilities`: Selenium's [desired
* capabilities](https://github.com/SeleniumHQ/selenium/wiki/DesiredCapabilities)
* * `manualStart` (optional, default: false) - do not start browser before a test, start it manually inside a helper
* with `this.helpers["WebDriverIO"]._startBrowser()`
* * `timeouts`: [WebDriverIO timeouts](http://webdriver.io/guide/testrunner/timeouts.html) defined as hash.
*
* Example:
*
* ```json
* {
* "helpers": {
* "WebDriverIO" : {
* "smartWait": 5000,
* "browser": "chrome",
* "restart": false,
* "windowSize": "maximize",
* "timeouts": {
* "script": 60000,
* "page load": 10000
* }
* }
* }
* }
* ```
*
* Additional configuration params can be used from [webdriverio
* website](http://webdriver.io/guide/getstarted/configuration.html).
*
* ### Headless Chrome
*
* ```json
* {
* "helpers": {
* "WebDriverIO" : {
* "url": "http://localhost",
* "browser": "chrome",
* "desiredCapabilities": {
* "chromeOptions": {
* "args": [ "--headless", "--disable-gpu", "--window-size=800,600" ]
* }
* }
* }
* }
* }
* ```
*
* ### Connect through proxy
*
* CodeceptJS also provides flexible options when you want to execute tests to Selenium servers through proxy. You will
* need to update the `helpers.WebDriverIO.desiredCapabilities.proxy` key.
*
* ```js
* {
* "helpers": {
* "WebDriverIO": {
* "desiredCapabilities": {
* "proxy": {
* "proxyType": "manual|pac",
* "proxyAutoconfigUrl": "URL TO PAC FILE",
* "httpProxy": "PROXY SERVER",
* "sslProxy": "PROXY SERVER",
* "ftpProxy": "PROXY SERVER",
* "socksProxy": "PROXY SERVER",
* "socksUsername": "USERNAME",
* "socksPassword": "PASSWORD",
* "noProxy": "BYPASS ADDRESSES"
* }
* }
* }
* }
* }
* ```
* For example,
*
* ```js
* {
* "helpers": {
* "WebDriverIO": {
* "desiredCapabilities": {
* "proxy": {
* "proxyType": "manual",
* "httpProxy": "http://corporate.proxy:8080",
* "socksUsername": "codeceptjs",
* "socksPassword": "secret",
* "noProxy": "127.0.0.1,localhost"
* }
* }
* }
* }
* }
* ```
*
* Please refer to [Selenium - Proxy Object](https://github.com/SeleniumHQ/selenium/wiki/DesiredCapabilities) for more
* information.
*
* ### Cloud Providers
*
* WebDriverIO makes it possible to execute tests against services like `Sauce Labs` `BrowserStack` `TestingBot`
* Check out their documentation on [available parameters](http://webdriver.io/guide/usage/cloudservices.html)
*
* Connecting to `BrowserStack` and `Sauce Labs` is simple. All you need to do
* is set the `user` and `key` parameters. WebDriverIO automatically know which
* service provider to connect to.
*
* ```js
* {
* "helpers":{
* "WebDriverIO": {
* "url": "YOUR_DESIRED_HOST",
* "user": "YOUR_BROWSERSTACK_USER",
* "key": "YOUR_BROWSERSTACK_KEY",
* "desiredCapabilities": {
* "browserName": "chrome",
*
* // only set this if you're using BrowserStackLocal to test a local domain
* // "browserstack.local": true,
*
* // set this option to tell browserstack to provide addition debugging info
* // "browserstack.debug": true,
* }
* }
* }
* }
* ```
*
* ### Multiremote Capabilities
*
* This is a work in progress but you can control two browsers at a time right out of the box.
* Individual control is something that is planned for a later version.
*
* Here is the [webdriverio docs](http://webdriver.io/guide/usage/multiremote.html) on the subject
*
* ```js
* {
* "helpers": {
* "WebDriverIO": {
* "multiremote": {
* "MyChrome": {
* "desiredCapabilities": {
* "browserName": "chrome"
* }
* },
* "MyFirefox": {
* "desiredCapabilities": {
* "browserName": "firefox"
* }
* }
* }
* }
* }
* }
* ```
*
*
* ## Access From Helpers
*
* Receive a WebDriverIO client from a custom helper by accessing `browser` property:
*
* ```js
* this.helpers['WebDriverIO'].browser
* ```
*/
class WebDriverIO extends Helper {
constructor(config) {
super(config);
webdriverio = requireg('webdriverio');
this.options = {
smartWait: 0,
waitForTimeout: 1000, // ms
desiredCapabilities: {},
restart: true,
uniqueScreenshotNames: false,
disableScreenshots: false,
fullPageScreenshots: true,
manualStart: false,
keepCookies: false,
keepBrowserState: false,
deprecationWarnings: false,
timeouts: {
script: 1000, // ms
},
};
this._validateConfig(config);
}
_validateConfig(config) {
// set defaults
this.root = webRoot;
this.isRunning = false;
// override defaults with config
Object.assign(this.options, config);
this.options.baseUrl = this.options.url || this.options.baseUrl;
this.options.desiredCapabilities.browserName = this.options.browser || this.options.desiredCapabilities.browserName;
this.options.waitForTimeout /= 1000; // convert to seconds
if (!this.options.desiredCapabilities.platformName && (!this.options.url || !this.options.browser)) {
throw new Error(`
WebDriverIO requires at url and browser to be set.
Check your codeceptjs config file to ensure these are set properly
{
"helpers": {
"WebDriverIO": {
"url": "YOUR_HOST"
"browser": "YOUR_PREFERRED_TESTING_BROWSER"
}
}
}
`);
}
}
static _checkRequirements() {
try {
requireg('webdriverio');
} catch (e) {
return ['webdriverio'];
}
}
static _config() {
return [{
name: 'url',
message: 'Base url of site to be tested',
default: 'http://localhost',
}, {
name: 'browser',
message: 'Browser in which testing will be performed',
default: 'chrome',
}];
}
_beforeSuite() {
if (!this.options.restart && !this.options.manualStart && !this.isRunning) {
this.debugSection('Session', 'Starting singleton browser session');
return this._startBrowser();
}
}
async _startBrowser() {
if (this.options.multiremote) {
this.browser = webdriverio.multiremote(this.options.multiremote).init();
} else {
this.browser = webdriverio.remote(this.options).init();
}
await this.browser;
this.isRunning = true;
if (this.options.timeouts) {
await this.defineTimeout(this.options.timeouts);
}
if (this.options.windowSize === 'maximize') {
await this.resizeWindow('maximize');
} else if (this.options.windowSize && this.options.windowSize.indexOf('x') > 0) {
const dimensions = this.options.windowSize.split('x');
await this.resizeWindow(dimensions[0], dimensions[1]);
}
return this.browser;
}
async _before() {
this.context = this.root;
if (this.options.restart && !this.options.manualStart) return this._startBrowser();
if (!this.isRunning && !this.options.manualStart) return this._startBrowser();
return this.browser;
}
async _after() {
if (!this.isRunning) return;
if (this.options.restart) {
this.isRunning = false;
return this.browser.end();
}
if (this.options.keepBrowserState) return;
if (!this.options.keepCookies && this.options.desiredCapabilities.browserName) {
this.debugSection('Session', 'cleaning cookies and localStorage');
await this.browser.deleteCookie();
}
await this.browser.execute('localStorage.clear();').catch((err) => {
if (!(err.message.indexOf("Storage is disabled inside 'data:' URLs.") > -1)) throw err;
});
await this.closeOtherTabs();
return this.browser;
}
_afterSuite() {
}
_finishTest() {
if (!this.options.restart && this.isRunning) return this.browser.end();
}
async _failed(test) {
if (Object.keys(withinStore).length !== 0) await this._withinEnd();
if (!this.options.disableScreenshots) {
let fileName = clearString(test.title);
if (test.ctx && test.ctx.test && test.ctx.test.type === 'hook') fileName = clearString(`${test.title}_${test.ctx.test.title}`);
if (this.options.uniqueScreenshotNames) {
const uuid = test.uuid || test.ctx.test.uuid;
fileName = `${fileName.substring(0, 10)}_${uuid}.failed.png`;
} else {
fileName += '.failed.png';
}
await this.saveScreenshot(fileName, this.options.fullPageScreenshots).catch((err) => {
if (err &&
err.type &&
err.type === 'RuntimeError' &&
err.message &&
(err.message.indexOf('was terminated due to') > -1 || err.message.indexOf('no such window: target window already closed') > -1)
) {
this.isRunning = false;
}
});
}
}
async _withinBegin(locator) {
const frame = isFrameLocator(locator);
const client = this.browser;
if (frame) {
if (Array.isArray(frame)) {
withinStore.frame = frame.join('>');
return client
.frame(null)
.then(() => frame.reduce((p, frameLocator) => p.then(() => this.switchTo(frameLocator)), Promise.resolve()));
}
withinStore.frame = frame;
return this.switchTo(frame);
}
withinStore.elFn = this.browser.element;
withinStore.elsFn = this.browser.elements;
this.context = locator;
const res = await client.element(withStrictLocator.call(this, locator));
this.browser.element = function (l) {
return this.elementIdElement(res.value.ELEMENT, l);
};
this.browser.elements = function (l) {
return this.elementIdElements(res.value.ELEMENT, l);
};
return this.browser;
}
async _withinEnd() {
if (withinStore.frame) {
withinStore = {};
return this.switchTo(null);
}
this.context = this.root;
this.browser.element = withinStore.elFn;
this.browser.elements = withinStore.elsFn;
withinStore = {};
}
/**
* Get elements by different locator types, including strict locator
* Should be used in custom helpers:
*
* ```js
* this.helpers['WebDriverIO']._locate({name: 'password'}).then //...
* ```
*/
async _locate(locator, smartWait = false) {
if (!this.options.smartWait || !smartWait) return this.browser.elements(withStrictLocator.call(this, locator));
this.debugSection(`SmartWait (${this.options.smartWait}ms)`, `Locating ${locator} in ${this.options.smartWait}`);
await this.defineTimeout({ implicit: this.options.smartWait });
const els = await this.browser.elements(withStrictLocator.call(this, locator));
await this.defineTimeout({ implicit: 0 });
return els;
}
/**
* Find a checkbox by providing human readable text:
*
* ```js
* this.helpers['WebDriverIO']._locateCheckable('I agree with terms and conditions').then // ...
* ```
*/
async _locateCheckable(locator) {
return findCheckable.call(this, locator, this.browser.elements.bind(this)).then(res => res.value);
}
/**
* Find a clickable element by providing human readable text:
*
* ```js
* this.helpers['WebDriverIO']._locateClickable('Next page').then // ...
* ```
*/
async _locateClickable(locator) {
return findClickable.call(this, locator, this.browser.elements.bind(this)).then(res => res.value);
}
/**
* Find field elements by providing human readable text:
*
* ```js
* this.helpers['WebDriverIO']._locateFields('Your email').then // ...
* ```
*/
async _locateFields(locator) {
return findFields.call(this, locator).then(res => res.value);
}
/**
* Set [WebDriverIO timeouts](http://webdriver.io/guide/testrunner/timeouts.html) in realtime.
* Appium: support only web testing
* Timeouts are expected to be passed as object:
*
* ```js
* I.defineTimeout({ script: 5000 });
* I.defineTimeout({ implicit: 10000, pageLoad: 10000, script: 5000 });
* ```
*/
async defineTimeout(timeouts) {
if (timeouts.implicit) {
await this.browser.timeouts('implicit', timeouts.implicit);
}
if (timeouts['page load']) {
await this.browser.timeouts('page load', timeouts['page load']);
}
// both pageLoad and page load are accepted
// see http://webdriver.io/api/protocol/timeouts.html
if (timeouts.pageLoad) {
await this.browser.timeouts('page load', timeouts.pageLoad);
}
if (timeouts.script) {
await this.browser.timeouts('script', timeouts.script);
}
return this.browser; // return the last response
}
/**
* {{> ../webapi/amOnPage }}
* Appium: support only web testing
*/
amOnPage(url) {
return this.browser.url(url).url((err, res) => {
if (err) throw err;
this.debugSection('Url', res.value);
});
}
/**
* {{> ../webapi/click }}
* Appium: support
*/
async click(locator, context = null) {
const clickMethod = this.browser.isMobile ? 'touchClick' : 'elementIdClick';
const locateFn = prepareLocateFn.call(this, context);
const res = await findClickable.call(this, locator, locateFn);
if (context) {
assertElementExists(res, locator, 'Clickable element', `was not found inside element ${new Locator(context).toString()}`);
} else {
assertElementExists(res, locator, 'Clickable element');
}
return this.browser[clickMethod](res.value[0].ELEMENT);
}
/**
* {{> ../webapi/doubleClick }}
* Appium: support only web testing
*/
async doubleClick(locator, context = null) {
const clickMethod = this.browser.isMobile ? 'touchClick' : 'elementIdClick';
const locateFn = prepareLocateFn.call(this, context);
const res = await findClickable.call(this, locator, locateFn);
if (context) {
assertElementExists(res, locator, 'Clickable element', `was not found inside element ${new Locator(context).toString()}`);
} else {
assertElementExists(res, locator, 'Clickable element');
}
const elem = res.value[0];
return this.browser.moveTo(elem.ELEMENT).doDoubleClick();
}
/**
* Performs right click on an element matched by CSS or XPath.
* Appium: support, but in apps works as usual click
*/
async rightClick(locator) {
/**
* just press button if no selector is given
*/
if (locator === undefined) {
return this.browser.buttonPress('right');
}
const res = await this._locate(locator, true);
assertElementExists(res, locator, 'Clickable element');
const elem = res.value[0];
if (this.browser.isMobile) return this.browser.touchClick(elem.ELEMENT);
return this.browser.moveTo(elem.ELEMENT).buttonPress('right');
}
/**
* {{> ../webapi/fillField }}
* Appium: support
*/
async fillField(field, value) {
const res = await findFields.call(this, field);
assertElementExists(res, field, 'Field');
const elem = res.value[0];
return this.browser.elementIdClear(elem.ELEMENT).elementIdValue(elem.ELEMENT, value);
}
/**
* {{> ../webapi/appendField }}
* Appium: support, but it's clear a field before insert in apps
*/
async appendField(field, value) {
const res = await findFields.call(this, field);
assertElementExists(res, field, 'Field');
const elem = res.value[0];
return this.browser.elementIdValue(elem.ELEMENT, value);
}
/**
* {{> ../webapi/clearField}}
* Appium: support
*/
async clearField(field) {
const res = await findFields.call(this, field);
assertElementExists(res, field, 'Field');
const elem = res.value[0];
return this.browser.elementIdClear(elem.ELEMENT);
}
/**
* {{> ../webapi/selectOption}}
*/
async selectOption(select, option) {
const res = await findFields.call(this, select);
assertElementExists(res, select, 'Selectable field');
const elem = res.value[0];
let commands = [];
if (!Array.isArray(option)) {
option = [option];
}
// select options by visible text
option.forEach(opt => commands.push(this.browser.elementIdElements(elem.ELEMENT, Locator.select.byVisibleText(xpathLocator.literal(opt)))));
let els = await this.browser.unify(commands, { extractValue: true });
commands = [];
const clickOptionFn = (el) => {
if (el[0]) el = el[0];
if (el && el.ELEMENT) commands.push(this.browser.elementIdClick(el.ELEMENT));
};
if (els.length) {
els.forEach(clickOptionFn);
return this.browser.unify(commands);
}
// select options by value
option.forEach(opt => commands.push(this.browser.elementIdElements(elem.ELEMENT, Locator.select.byValue(xpathLocator.literal(opt)))));
els = await this.browser.unify(commands, { extractValue: true });
if (els.length === 0) {
throw new ElementNotFound(select, `Option ${option} in`, 'was found neither by visible text not by value');
}
commands = [];
els.forEach(clickOptionFn);
return this.browser.unify(commands);
}
/**
* {{> ../webapi/attachFile }}
* Appium: not tested
*/
async attachFile(locator, pathToFile) {
const file = path.join(global.codecept_dir, pathToFile);
if (!fileExists(file)) {
throw new Error(`File at ${file} can not be found on local system`);
}
const el = await findFields.call(this, locator);
this.debug(`Uploading ${file}`);
const res = await this.browser.uploadFile(file);
assertElementExists(el, locator, 'File field');
return this.browser.elementIdValue(el.value[0].ELEMENT, res.value);
}
/**
* {{> ../webapi/checkOption }}
* Appium: not tested
*/
async checkOption(field, context = null) {
const clickMethod = this.browser.isMobile ? 'touchClick' : 'elementIdClick';
const locateFn = prepareLocateFn.call(this, context);
const res = await findCheckable.call(this, field, locateFn);
assertElementExists(res, field, 'Checkable');
const elem = res.value[0];
const isSelected = await this.browser.elementIdSelected(elem.ELEMENT);
if (isSelected.value) return Promise.resolve(true);
return this.browser[clickMethod](elem.ELEMENT);
}
/**
* {{> ../webapi/uncheckOption }}
* Appium: not tested
*/
async uncheckOption(field, context = null) {
const clickMethod = this.browser.isMobile ? 'touchClick' : 'elementIdClick';
const locateFn = prepareLocateFn.call(this, context);
const res = await findCheckable.call(this, field, locateFn);
assertElementExists(res, field, 'Checkable');
const elem = res.value[0];
const isSelected = await this.browser.elementIdSelected(elem.ELEMENT);
if (!isSelected.value) return Promise.resolve(true);
return this.browser[clickMethod](elem.ELEMENT);
}
/**
* {{> ../webapi/grabTextFrom }}
* Appium: support
*/
async grabTextFrom(locator) {
const res = await this._locate(locator, true);
assertElementExists(res, locator);
const commands = [];
res.value.forEach(el => commands.push(this.browser.elementIdText(el.ELEMENT)));
return this.browser.unify(commands, {
extractValue: true,
}).then(selected => selected);
}
/**
* Retrieves the innerHTML from an element located by CSS or XPath and returns it to test.
* Resumes test execution, so **should be used inside a generator with `yield`** operator.
* Appium: support only web testing
*
*
* ```js
* let postHTML = yield I.grabHTMLFrom('#post');
* ```
*/
async grabHTMLFrom(locator) {
return this.browser.getHTML(withStrictLocator.call(this, locator)).then(html => html);
}
/**
* {{> ../webapi/grabValueFrom }}
* Appium: support only web testing
*/
async grabValueFrom(locator) {
const res = await this._locate(locator, true);
assertElementExists(res, locator);
const commands = [];
res.value.forEach(el => commands.push(this.browser.elementIdAttribute(el.ELEMENT, 'value')));
return this.browser.unify(commands, {
extractValue: true,
}).then(selected => selected);
}
/**
* Grab CSS property for given locator
*
* ```js
* I.grabCssPropertyFrom('h3', 'font-weight');
* ```
*/
async grabCssPropertyFrom(locator, cssProperty) {
const res = await this._locate(locator, true);
assertElementExists(res, locator);
const commands = [];
res.value.forEach(el => commands.push(this.browser.elementIdCssProperty(el.ELEMENT, cssProperty)));
return this.browser.unify(commands, {
extractValue: true,
}).then(selected => selected);
}
/**
* {{> ../webapi/grabAttributeFrom }}
* Appium: can be used for apps only with several values ("contentDescription", "text", "className", "resourceId")
*/
async grabAttributeFrom(locator, attr) {
const res = await this._locate(locator, true);
assertElementExists(res, locator);
const commands = [];
res.value.forEach(el => commands.push(this.browser.elementIdAttribute(el.ELEMENT, attr)));
return this.browser.unify(commands, {
extractValue: true,
}).then(selected => selected);
}
/**
* {{> ../webapi/seeInTitle }}
* Appium: support only web testing
*/
async seeInTitle(text) {
const title = await this.browser.getTitle();
return stringIncludes('web page title').assert(text, title);
}
/**
* Checks that title is equal to provided one.
*
* ```js
* I.seeTitleEquals('Test title.');
* ```
*/
async seeTitleEquals(text) {
const title = await this.browser.getTitle();
return assert.equal(title, text, `expected web page title to be ${text}, but found ${title}`);
}
/**
* {{> ../webapi/dontSeeInTitle }}
* Appium: support only web testing
*/
async dontSeeInTitle(text) {
const title = await this.browser.getTitle();
return stringIncludes('web page title').negate(text, title);
}
/**
* {{> ../webapi/grabTitle }}
* Appium: support only web testing
*/
async grabTitle() {
const title = await this.browser.getTitle();
this.debugSection('Title', title);
return title;
}
/**
* {{> ../webapi/see }}
* Appium: support with context in apps
*/
async see(text, context = null) {
return proceedSee.call(this, 'assert', text, context);
}
/**
* Checks that text is equal to provided one.
*
* ```js
* I.seeTextEquals('text', 'h1');
* ```
*/
async seeTextEquals(text, context = null) {
return proceedSee.call(this, 'assert', text, context, true);
}
/**
* {{> ../webapi/dontSee }}
* Appium: support with context in apps
*/
async dontSee(text, context = null) {
return proceedSee.call(this, 'negate', text, context);
}
/**
* {{> ../webapi/seeInField }}
* Appium: support only web testing
*/
async seeInField(field, value) {
return proceedSeeField.call(this, 'assert', field, value);
}
/**
* {{> ../webapi/dontSeeInField }}
* Appium: support only web testing
*/
async dontSeeInField(field, value) {
return proceedSeeField.call(this, 'negate', field, value);
}
/**
* {{> ../webapi/seeCheckboxIsChecked }}
* Appium: not tested
*/
async seeCheckboxIsChecked(field) {
return proceedSeeCheckbox.call(this, 'assert', field);
}
/**
* {{> ../webapi/dontSeeCheckboxIsChecked }}
* Appium: not tested
*/
async dontSeeCheckboxIsChecked(field) {
return proceedSeeCheckbox.call(this, 'negate', field);
}
/**
* {{> ../webapi/seeElement }}
* Appium: support
*/
async seeElement(locator) {
const res = await this._locate(locator, true);
if (!res.value || res.value.length === 0) {
return truth(`elements of ${locator}`, 'to be seen').assert(false);
}
const commands = [];
res.value.forEach(el => commands.push(this.browser.elementIdDisplayed(el.ELEMENT)));
const selected = await this.browser.unify(commands, { extractValue: true });
return truth(`elements of ${locator}`, 'to be seen').assert(selected);
}
/**
* {{> ../webapi/dontSeeElement}}
* Appium: support
*/
async dontSeeElement(locator) {
const res = await this._locate(locator, false);
if (!res.value || res.value.length === 0) {
return truth(`elements of ${locator}`, 'to be seen').negate(false);
}
const commands = [];
res.value.forEach(el => commands.push(this.browser.elementIdDisplayed(el.ELEMENT)));
const selected = await this.browser.unify(commands, { extractValue: true });
return truth(`elements of ${locator}`, 'to be seen').negate(selected);
}
/**
* {{> ../webapi/seeElementInDOM }}
* Appium: support
*/
async seeElementInDOM(locator) {
const res = await this.browser.elements(withStrictLocator.call(this, locator));
return empty('elements').negate(res.value);
}
/**
* {{> ../webapi/dontSeeElementInDOM }}
* Appium: support
*/
async dontSeeElementInDOM(locator) {
const res = await this.browser.elements(withStrictLocator.call(this, locator));
return empty('elements').assert(res.value);
}
/**
* {{> ../webapi/seeInSource }}
* Appium: support
*/
async seeInSource(text) {
const source = await this.browser.getSource();
return stringIncludes('HTML source of a page').assert(text, source);
}
/**
* {{> ../webapi/seeInSource }}
* Appium: support
*/
async grabSource() {
return this.browser.getSource();
}
/**
* Get JS log from browser. Log buffer is reset after each request.
*
* ```js
* let logs = yield I.grabBrowserLogs();
* console.log(JSON.stringify(logs))
* ```
*/
async grabBrowserLogs() {
return this.browser.log('browser').then(res => res.value);
}
/**
* Get current URL from browser.
*
* ```js
* let url = yield I.grabBrowserUrl();
* console.log(`Current URL is [${url}]`);
* ```
*/
async grabBrowserUrl() {
const res = await this.browser.url();
return res.value;
}
/**
* {{> ../webapi/dontSeeInSource }}
* Appium: support
*/
async dontSeeInSource(text) {
const source = await this.browser.getSource();
return stringIncludes('HTML source of a page').negate(text, source);
}
/**
* asserts that an element appears a given number of times in the DOM
* Element is located by label or name or CSS or XPath.
* Appium: support
*
* ```js
* I.seeNumberOfElements('#submitBtn', 1);
* ```
*/
async seeNumberOfElements(selector, num) {
const res = await this._locate(withStrictLocator.call(this, selector));
return assert.equal(res.value.length, num, `expected number of elements (${selector}) is ${num}, but found ${res.value.length}`);
}
/**
* asserts that an element is visible a given number of times
* Element is located by CSS or XPath.
*
* ```js
* I.seeNumberOfVisibleElements('.buttons', 3);
* ```
*/
async seeNumberOfVisibleElements(locator, num) {
const res = await this.grabNumberOfVisibleElements(locator);
return assert.equal(res, num, `expected number of visible elements (${locator}) is ${num}, but found ${res}`);
}
/**
* Checks that all elements with given locator have given CSS properties.
*
* ```js
* I.seeCssPropertiesOnElements('h3', { 'font-weight': "bold"});
* ```
*/
async seeCssPropertiesOnElements(locator, cssProperties) {
const res = await this._locate(locator);
assertElementExists(res, locator);
const elemAmount = res.value.length;
const commands = [];
res.value.forEach((el) => {
Object.keys(cssProperties).forEach((prop) => {
commands.push(this.browser.elementIdCssProperty(el.ELEMENT, prop));
});
});
let props = await this.browser.unify(commands, { extractValue: true });
const values = Object.keys(cssProperties).map(key => cssProperties[key]);
if (!Array.isArray(props)) props = [props];
let chunked = chunkArray(props, values.length);
chunked = chunked.filter((val) => {
for (let i = 0; i < val.length; ++i) {
if (val[i] !== values[i]) return false;
}
return true;
});
return assert.ok(
chunked.length === elemAmount,
`Not all elements (${locator}) have CSS property ${JSON.stringify(cssProperties)}`,