-
-
Notifications
You must be signed in to change notification settings - Fork 737
/
Copy pathTestCafe.js
1417 lines (1210 loc) · 38.5 KB
/
TestCafe.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
// @ts-nocheck
const fs = require('fs');
const assert = require('assert');
const path = require('path');
const qrcode = require('qrcode-terminal');
const createTestCafe = require('testcafe');
const { Selector, ClientFunction } = require('testcafe');
const Helper = require('@codeceptjs/helper');
const ElementNotFound = require('./errors/ElementNotFound');
const testControllerHolder = require('./testcafe/testControllerHolder');
const {
mapError,
createTestFile,
createClientFunction,
} = require('./testcafe/testcafe-utils');
const stringIncludes = require('../assert/include').includes;
const { urlEquals } = require('../assert/equal');
const { empty } = require('../assert/empty');
const { truth } = require('../assert/truth');
const {
xpathLocator, normalizeSpacesInString,
} = require('../utils');
const Locator = require('../locator');
/**
* Client Functions
*/
const getPageUrl = t => ClientFunction(() => document.location.href).with({ boundTestRun: t });
const getHtmlSource = t => ClientFunction(() => document.getElementsByTagName('html')[0].innerHTML).with({ boundTestRun: t });
/**
* Uses [TestCafe](https://github.com/DevExpress/testcafe) library to run cross-browser tests.
* The browser version you want to use in tests must be installed on your system.
*
* Requires `testcafe` package to be installed.
*
* ```
* npm i testcafe --save-dev
* ```
*
* ## Configuration
*
* This helper should be configured in codecept.conf.ts or codecept.conf.js
*
* * `url`: base url of website to be tested
* * `show`: (optional, default: false) - show browser window.
* * `windowSize`: (optional) - set browser window width and height
* * `getPageTimeout` (optional, default: '30000') config option to set maximum navigation time in milliseconds.
* * `waitForTimeout`: (optional) default wait* timeout in ms. Default: 5000.
* * `browser`: (optional, default: chrome) - See https://devexpress.github.io/testcafe/documentation/using-testcafe/common-concepts/browsers/browser-support.html
*
*
* #### Example #1: Show chrome browser window
*
* ```js
* {
* helpers: {
* TestCafe : {
* url: "http://localhost",
* waitForTimeout: 15000,
* show: true,
* browser: "chrome"
* }
* }
* }
* ```
*
* To use remote device you can provide 'remote' as browser parameter this will display a link with QR Code
* See https://devexpress.github.io/testcafe/documentation/recipes/test-on-remote-computers-and-mobile-devices.html
* #### Example #2: Remote browser connection
*
* ```js
* {
* helpers: {
* TestCafe : {
* url: "http://localhost",
* waitForTimeout: 15000,
* browser: "remote"
* }
* }
* }
* ```
*
* ## Access From Helpers
*
* Call Testcafe methods directly using the testcafe controller.
*
* ```js
* const testcafeTestController = this.helpers['TestCafe'].t;
* const comboBox = Selector('.combo-box');
* await testcafeTestController
* .hover(comboBox) // hover over combo box
* .click('#i-prefer-both') // click some other element
* ```
*
* ## Methods
*/
class TestCafe extends Helper {
constructor(config) {
super(config);
this.testcafe = undefined; // testcafe instance
this.t = undefined; // testcafe test controller
this.dummyTestcafeFile; // generated testcafe test file
// context is used for within() function.
// It requires to have _withinBeginand _withinEnd implemented.
// Inside _withinBegin we should define that all next element calls should be started from a specific element (this.context).
this.context = undefined; // TODO Not sure if this applies to testcafe
this.options = {
url: 'http://localhost',
show: false,
browser: 'chrome',
restart: true, // TODO Test if restart false works
manualStart: false,
keepBrowserState: false,
waitForTimeout: 5000,
getPageTimeout: 30000,
fullPageScreenshots: false,
disableScreenshots: false,
windowSize: undefined,
...config,
};
}
// TOOD Do a requirements check
static _checkRequirements() {
try {
require('testcafe');
} catch (e) {
return ['testcafe@^1.1.0'];
}
}
static _config() {
return [
{ name: 'url', message: 'Base url of site to be tested', default: 'http://localhost' },
{ name: 'browser', message: 'Browser to be used', default: 'chrome' },
{
name: 'show', message: 'Show browser window', default: true, type: 'confirm',
},
];
}
async _configureAndStartBrowser() {
this.dummyTestcafeFile = createTestFile(global.output_dir); // create a dummy test file to get hold of the test controller
this.iteration += 2; // Use different ports for each test run
// @ts-ignore
this.testcafe = await createTestCafe('', null, null);
this.debugSection('_before', 'Starting testcafe browser...');
this.isRunning = true;
// TODO Do we have to cleanup the runner?
const runner = this.testcafe.createRunner();
this.options.browser !== 'remote' ? this._startBrowser(runner) : this._startRemoteBrowser(runner);
this.t = await testControllerHolder.get();
assert(this.t, 'Expected to have the testcafe test controller');
if (this.options.windowSize && this.options.windowSize.indexOf('x') > 0) {
const dimensions = this.options.windowSize.split('x');
await this.t.resizeWindow(parseInt(dimensions[0], 10), parseInt(dimensions[1], 10));
}
}
async _startBrowser(runner) {
runner
.src(this.dummyTestcafeFile)
.screenshots(global.output_dir, !this.options.disableScreenshots)
// .video(global.output_dir) // TODO Make this configurable
.browsers(this.options.show ? this.options.browser : `${this.options.browser}:headless`)
.reporter('minimal')
.run({
skipJsErrors: true,
skipUncaughtErrors: true,
quarantineMode: false,
// debugMode: true,
// debugOnFail: true,
// developmentMode: true,
pageLoadTimeout: this.options.getPageTimeout,
selectorTimeout: this.options.waitForTimeout,
assertionTimeout: this.options.waitForTimeout,
takeScreenshotsOnFails: true,
})
.catch((err) => {
this.debugSection('_before', `Error ${err.toString()}`);
this.isRunning = false;
this.testcafe.close();
});
}
async _startRemoteBrowser(runner) {
const remoteConnection = await this.testcafe.createBrowserConnection();
console.log('Connect your device to the following URL or scan QR Code: ', remoteConnection.url);
qrcode.generate(remoteConnection.url);
remoteConnection.once('ready', () => {
runner
.src(this.dummyTestcafeFile)
.browsers(remoteConnection)
.reporter('minimal')
.run({
selectorTimeout: this.options.waitForTimeout,
skipJsErrors: true,
skipUncaughtErrors: true,
})
.catch((err) => {
this.debugSection('_before', `Error ${err.toString()}`);
this.isRunning = false;
this.testcafe.close();
});
});
}
async _stopBrowser() {
this.debugSection('_after', 'Stopping testcafe browser...');
testControllerHolder.free();
if (this.testcafe) {
this.testcafe.close();
}
fs.unlinkSync(this.dummyTestcafeFile); // remove the dummy test
this.t = undefined;
this.isRunning = false;
}
_init() {
}
async _beforeSuite() {
if (!this.options.restart && !this.options.manualStart && !this.isRunning) {
this.debugSection('Session', 'Starting singleton browser session');
return this._configureAndStartBrowser();
}
}
async _before() {
if (this.options.restart && !this.options.manualStart) return this._configureAndStartBrowser();
if (!this.isRunning && !this.options.manualStart) return this._configureAndStartBrowser();
this.context = null;
}
async _after() {
if (!this.isRunning) return;
if (this.options.restart) {
this.isRunning = false;
return this._stopBrowser();
}
if (this.options.keepBrowserState) return;
if (!this.options.keepCookies) {
this.debugSection('Session', 'cleaning cookies and localStorage');
await this.clearCookie();
// TODO IMHO that should only happen when
await this.executeScript(() => localStorage.clear())
.catch((err) => {
if (!(err.message.indexOf("Storage is disabled inside 'data:' URLs.") > -1)) throw err;
});
}
}
_afterSuite() {
}
async _finishTest() {
if (!this.options.restart && this.isRunning) return this._stopBrowser();
}
/**
* Use [TestCafe](https://devexpress.github.io/testcafe/documentation/test-api/) API inside a test.
*
* First argument is a description of an action.
* Second argument is async function that gets this helper as parameter.
*
* { [`t`](https://devexpress.github.io/testcafe/documentation/test-api/test-code-structure.html#test-controller)) } object from TestCafe API is available.
*
* ```js
* I.useTestCafeTo('handle browser dialog', async ({ t }) {
* await t.setNativeDialogHandler(() => true);
* });
* ```
*
*
*
* @param {string} description used to show in logs.
* @param {function} fn async functuion that executed with TestCafe helper as argument
*/
useTestCafeTo(description, fn) {
return this._useTo(...arguments);
}
/**
* Get elements by different locator types, including strict locator
* Should be used in custom helpers:
*
* ```js
* const elements = await this.helpers['TestCafe']._locate('.item');
* ```
*
*/
async _locate(locator) {
return findElements.call(this, this.context, locator).catch(mapError);
}
async _withinBegin(locator) {
const els = await this._locate(locator);
assertElementExists(els, locator);
this.context = await els.nth(0);
}
async _withinEnd() {
this.context = null;
}
/**
* {{> amOnPage }}
*/
async amOnPage(url) {
if (!(/^\w+\:\/\//.test(url))) {
url = this.options.url + url;
}
return this.t.navigateTo(url)
.catch(mapError);
}
/**
* {{> resizeWindow }}
*/
async resizeWindow(width, height) {
if (width === 'maximize') {
return this.t.maximizeWindow().catch(mapError);
}
return this.t.resizeWindow(width, height).catch(mapError);
}
/**
* {{> focus }}
*
*/
async focus(locator) {
const els = await this._locate(locator);
await assertElementExists(els, locator, 'Element to focus');
const element = await els.nth(0);
const focusElement = ClientFunction(() => element().focus(), { boundTestRun: this.t, dependencies: { element } });
return focusElement();
}
/**
* {{> blur }}
*
*/
async blur(locator) {
const els = await this._locate(locator);
await assertElementExists(els, locator, 'Element to blur');
const element = await els.nth(0);
const blurElement = ClientFunction(() => element().blur(), { boundTestRun: this.t, dependencies: { element } });
return blurElement();
}
/**
* {{> click }}
*
*/
async click(locator, context = null) {
return proceedClick.call(this, locator, context);
}
/**
* {{> refreshPage }}
*/
async refreshPage() {
// eslint-disable-next-line no-restricted-globals
return this.t.eval(() => location.reload(true), { boundTestRun: this.t }).catch(mapError);
}
/**
* {{> waitForVisible }}
*
*/
async waitForVisible(locator, sec) {
const timeout = sec ? sec * 1000 : undefined;
return (await findElements.call(this, this.context, locator))
.with({ visibilityCheck: true, timeout })()
.catch(mapError);
}
/**
* {{> fillField }}
*/
async fillField(field, value) {
const els = await findFields.call(this, field);
assertElementExists(els, field, 'Field');
const el = await els.nth(0);
return this.t
.typeText(el, value.toString(), { replace: true })
.catch(mapError);
}
/**
* {{> clearField }}
*/
async clearField(field) {
const els = await findFields.call(this, field);
assertElementExists(els, field, 'Field');
const el = await els.nth(0);
const res = await this.t
.selectText(el)
.pressKey('delete');
return res;
}
/**
* {{> appendField }}
*
*/
async appendField(field, value) {
const els = await findFields.call(this, field);
assertElementExists(els, field, 'Field');
const el = await els.nth(0);
return this.t
.typeText(el, value.toString(), { replace: false })
.catch(mapError);
}
/**
* {{> attachFile }}
*
*/
async attachFile(field, pathToFile) {
const els = await findFields.call(this, field);
assertElementExists(els, field, 'Field');
const el = await els.nth(0);
const file = path.join(global.codecept_dir, pathToFile);
return this.t
.setFilesToUpload(el, [file])
.catch(mapError);
}
/**
* {{> pressKey }}
*
* {{ keys }}
*/
async pressKey(key) {
assert(key, 'Expected a sequence of keys or key combinations');
return this.t
.pressKey(key.toLowerCase()) // testcafe keys are lowercase
.catch(mapError);
}
/**
* {{> moveCursorTo }}
*
*/
async moveCursorTo(locator, offsetX = 0, offsetY = 0) {
const els = (await findElements.call(this, this.context, locator)).filterVisible();
await assertElementExists(els, locator);
return this.t
.hover(els.nth(0), { offsetX, offsetY })
.catch(mapError);
}
/**
* {{> doubleClick }}
*
*/
async doubleClick(locator, context = null) {
let matcher;
if (context) {
const els = await this._locate(context);
await assertElementExists(els, context);
matcher = await els.nth(0);
}
const els = (await findClickable.call(this, matcher, locator)).filterVisible();
return this.t
.doubleClick(els.nth(0))
.catch(mapError);
}
/**
* {{> rightClick }}
*
*/
async rightClick(locator, context = null) {
let matcher;
if (context) {
const els = await this._locate(context);
await assertElementExists(els, context);
matcher = await els.nth(0);
}
const els = (await findClickable.call(this, matcher, locator)).filterVisible();
assertElementExists(els, locator);
return this.t
.rightClick(els.nth(0))
.catch(mapError);
}
/**
* {{> checkOption }}
*/
async checkOption(field, context = null) {
const el = await findCheckable.call(this, field, context);
return this.t
.click(el)
.catch(mapError);
}
/**
* {{> uncheckOption }}
*/
async uncheckOption(field, context = null) {
const el = await findCheckable.call(this, field, context);
if (await el.checked) {
return this.t
.click(el)
.catch(mapError);
}
}
/**
* {{> seeCheckboxIsChecked }}
*/
async seeCheckboxIsChecked(field) {
return proceedIsChecked.call(this, 'assert', field);
}
/**
* {{> dontSeeCheckboxIsChecked }}
*/
async dontSeeCheckboxIsChecked(field) {
return proceedIsChecked.call(this, 'negate', field);
}
/**
* {{> selectOption }}
*/
async selectOption(select, option) {
const els = await findFields.call(this, select);
assertElementExists(els, select, 'Selectable field');
const el = await els.filterVisible().nth(0);
if ((await el.tagName).toLowerCase() !== 'select') {
throw new Error('Element is not <select>');
}
if (!Array.isArray(option)) option = [option];
// TODO As far as I understand the testcafe docs this should do a multi-select
// but it does not work
// const clickOpts = { ctrl: option.length > 1 };
await this.t.click(el).catch(mapError);
for (const key of option) {
const opt = key;
let optEl;
try {
optEl = el.child('option').withText(opt);
if (await optEl.count) {
await this.t.click(optEl).catch(mapError);
continue;
}
// eslint-disable-next-line no-empty
} catch (err) {
}
try {
const sel = `[value="${opt}"]`;
optEl = el.find(sel);
if (await optEl.count) {
await this.t.click(optEl).catch(mapError);
}
// eslint-disable-next-line no-empty
} catch (err) {
}
}
}
/**
* {{> seeInCurrentUrl }}
*/
async seeInCurrentUrl(url) {
stringIncludes('url').assert(url, await getPageUrl(this.t)().catch(mapError));
}
/**
* {{> dontSeeInCurrentUrl }}
*/
async dontSeeInCurrentUrl(url) {
stringIncludes('url').negate(url, await getPageUrl(this.t)().catch(mapError));
}
/**
* {{> seeCurrentUrlEquals }}
*/
async seeCurrentUrlEquals(url) {
urlEquals(this.options.url).assert(url, await getPageUrl(this.t)().catch(mapError));
}
/**
* {{> dontSeeCurrentUrlEquals }}
*/
async dontSeeCurrentUrlEquals(url) {
urlEquals(this.options.url).negate(url, await getPageUrl(this.t)().catch(mapError));
}
/**
* {{> see }}
*
*/
async see(text, context = null) {
let els;
if (context) {
els = (await findElements.call(this, this.context, context)).withText(normalizeSpacesInString(text));
} else {
els = (await findElements.call(this, this.context, '*')).withText(normalizeSpacesInString(text));
}
return this.t
.expect(els.filterVisible().count).gt(0, `No element with text "${text}" found`)
.catch(mapError);
}
/**
* {{> dontSee }}
*
*/
async dontSee(text, context = null) {
let els;
if (context) {
els = (await findElements.call(this, this.context, context)).withText(text);
} else {
els = (await findElements.call(this, this.context, 'body')).withText(text);
}
return this.t
.expect(els.filterVisible().count).eql(0, `Element with text "${text}" can still be seen`)
.catch(mapError);
}
/**
* {{> seeElement }}
*/
async seeElement(locator) {
const exists = (await findElements.call(this, this.context, locator)).filterVisible().exists;
return this.t
.expect(exists).ok(`No element "${(new Locator(locator))}" found`)
.catch(mapError);
}
/**
* {{> dontSeeElement }}
*/
async dontSeeElement(locator) {
const exists = (await findElements.call(this, this.context, locator)).filterVisible().exists;
return this.t
.expect(exists).notOk(`Element "${(new Locator(locator))}" is still visible`)
.catch(mapError);
}
/**
* {{> seeElementInDOM }}
*/
async seeElementInDOM(locator) {
const exists = (await findElements.call(this, this.context, locator)).exists;
return this.t
.expect(exists).ok(`No element "${(new Locator(locator))}" found in DOM`)
.catch(mapError);
}
/**
* {{> dontSeeElementInDOM }}
*/
async dontSeeElementInDOM(locator) {
const exists = (await findElements.call(this, this.context, locator)).exists;
return this.t
.expect(exists).notOk(`Element "${(new Locator(locator))}" is still in DOM`)
.catch(mapError);
}
/**
* {{> seeNumberOfVisibleElements }}
*
*/
async seeNumberOfVisibleElements(locator, num) {
const count = (await findElements.call(this, this.context, locator)).filterVisible().count;
return this.t
.expect(count).eql(num)
.catch(mapError);
}
/**
* {{> grabNumberOfVisibleElements }}
*/
async grabNumberOfVisibleElements(locator) {
const count = (await findElements.call(this, this.context, locator)).filterVisible().count;
return count;
}
/**
* {{> seeInField }}
*/
async seeInField(field, value) {
const _value = (typeof value === 'boolean') ? value : value.toString();
// const expectedValue = findElements.call(this, this.context, field).value;
const els = await findFields.call(this, field);
assertElementExists(els, field, 'Field');
const el = await els.nth(0);
return this.t
.expect(await el.value).eql(_value)
.catch(mapError);
}
/**
* {{> dontSeeInField }}
*/
async dontSeeInField(field, value) {
const _value = (typeof value === 'boolean') ? value : value.toString();
// const expectedValue = findElements.call(this, this.context, field).value;
const els = await findFields.call(this, field);
assertElementExists(els, field, 'Field');
const el = await els.nth(0);
return this.t
.expect(el.value).notEql(_value)
.catch(mapError);
}
/**
* Checks that text is equal to provided one.
*
* ```js
* I.seeTextEquals('text', 'h1');
* ```
*/
async seeTextEquals(text, context = null) {
const expectedText = findElements.call(this, context, undefined).textContent;
return this.t
.expect(expectedText).eql(text)
.catch(mapError);
}
/**
* {{> seeInSource }}
*/
async seeInSource(text) {
const source = await getHtmlSource(this.t)();
stringIncludes('HTML source of a page').assert(text, source);
}
/**
* {{> dontSeeInSource }}
*/
async dontSeeInSource(text) {
const source = await getHtmlSource(this.t)();
stringIncludes('HTML source of a page').negate(text, source);
}
/**
* {{> saveElementScreenshot }}
*
*/
async saveElementScreenshot(locator, fileName) {
const outputFile = path.join(global.output_dir, fileName);
const sel = await findElements.call(this, this.context, locator);
assertElementExists(sel, locator);
const firstElement = await sel.filterVisible().nth(0);
this.debug(`Screenshot of ${(new Locator(locator))} element has been saved to ${outputFile}`);
return this.t.takeElementScreenshot(firstElement, fileName);
}
/**
* {{> saveScreenshot }}
*/
// TODO Implement full page screenshots
async saveScreenshot(fileName) {
const outputFile = path.join(global.output_dir, fileName);
this.debug(`Screenshot is saving to ${outputFile}`);
// TODO testcafe automatically creates thumbnail images (which cant be turned off)
return this.t.takeScreenshot(fileName);
}
/**
* {{> wait }}
*/
async wait(sec) {
return new Promise(((done) => {
setTimeout(done, sec * 1000);
}));
}
/**
* {{> executeScript }}
*
* If a function returns a Promise It will wait for its resolution.
*/
async executeScript(fn, ...args) {
const browserFn = createClientFunction(fn, args).with({ boundTestRun: this.t });
return browserFn();
}
/**
* {{> grabTextFromAll }}
*/
async grabTextFromAll(locator) {
const sel = await findElements.call(this, this.context, locator);
const length = await sel.count;
const texts = [];
for (let i = 0; i < length; i++) {
texts.push(await sel.nth(i).innerText);
}
return texts;
}
/**
* {{> grabTextFrom }}
*/
async grabTextFrom(locator) {
const sel = await findElements.call(this, this.context, locator);
assertElementExists(sel, locator);
const texts = await this.grabTextFromAll(locator);
if (texts.length > 1) {
this.debugSection('GrabText', `Using first element out of ${texts.length}`);
}
return texts[0];
}
/**
* {{> grabAttributeFrom }}
*/
async grabAttributeFromAll(locator, attr) {
const sel = await findElements.call(this, this.context, locator);
const length = await sel.count;
const attrs = [];
for (let i = 0; i < length; i++) {
attrs.push(await (await sel.nth(i)).getAttribute(attr));
}
return attrs;
}
/**
* {{> grabAttributeFrom }}
*/
async grabAttributeFrom(locator, attr) {
const sel = await findElements.call(this, this.context, locator);
assertElementExists(sel, locator);
const attrs = await this.grabAttributeFromAll(locator, attr);
if (attrs.length > 1) {
this.debugSection('GrabAttribute', `Using first element out of ${attrs.length}`);
}
return attrs[0];
}
/**
* {{> grabValueFromAll }}
*/
async grabValueFromAll(locator) {
const sel = await findElements.call(this, this.context, locator);
const length = await sel.count;
const values = [];
for (let i = 0; i < length; i++) {
values.push(await (await sel.nth(i)).value);
}
return values;
}
/**
* {{> grabValueFrom }}
*/
async grabValueFrom(locator) {
const sel = await findElements.call(this, this.context, locator);
assertElementExists(sel, locator);
const values = await this.grabValueFromAll(locator);
if (values.length > 1) {
this.debugSection('GrabValue', `Using first element out of ${values.length}`);
}
return values[0];
}
/**
* {{> grabSource }}
*/
async grabSource() {
return ClientFunction(() => document.documentElement.innerHTML).with({ boundTestRun: this.t })();
}
/**
* Get JS log from browser.
*
* ```js
* let logs = await I.grabBrowserLogs();
* console.log(JSON.stringify(logs))
* ```
*/
async grabBrowserLogs() {
// TODO Must map?
return this.t.getBrowserConsoleMessages();
}
/**
* {{> grabCurrentUrl }}
*/
async grabCurrentUrl() {
return ClientFunction(() => document.location.href).with({ boundTestRun: this.t })();
}
/**
* {{> grabPageScrollPosition }}
*/
async grabPageScrollPosition() {
return ClientFunction(() => ({ x: window.pageXOffset, y: window.pageYOffset })).with({ boundTestRun: this.t })();
}
/**
* {{> scrollPageToTop }}
*/
scrollPageToTop() {
return ClientFunction(() => window.scrollTo(0, 0)).with({ boundTestRun: this.t })().catch(mapError);
}
/**
* {{> scrollPageToBottom }}
*/
scrollPageToBottom() {
return ClientFunction(() => {
const body = document.body;
const html = document.documentElement;
window.scrollTo(0, Math.max(
body.scrollHeight,
body.offsetHeight,
html.clientHeight,
html.scrollHeight,
html.offsetHeight,
));
}).with({ boundTestRun: this.t })().catch(mapError);
}
/**
* {{> scrollTo }}
*/
async scrollTo(locator, offsetX = 0, offsetY = 0) {
if (typeof locator === 'number' && typeof offsetX === 'number') {
offsetY = offsetX;
offsetX = locator;
locator = null;
}
const scrollBy = ClientFunction((offset) => {
if (window && window.scrollBy && offset) {
window.scrollBy(offset.x, offset.y);
}
}).with({ boundTestRun: this.t });
if (locator) {
const els = await this._locate(locator);
assertElementExists(els, locator, 'Element');
const el = await els.nth(0);
const x = (await el.offsetLeft) + offsetX;
const y = (await el.offsetTop) + offsetY;
return scrollBy({ x, y }).catch(mapError);
}
const x = offsetX;