-
Notifications
You must be signed in to change notification settings - Fork 444
/
taiko.js
1999 lines (1853 loc) · 74.1 KB
/
taiko.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
const cri = require('chrome-remote-interface');
const childProcess = require('child_process');
const BrowserFetcher = require('./browserFetcher');
const removeFolder = require('rimraf');
const { helper, waitFor, isString, isFunction } = require('./helper');
const removeFolderAsync = helper.promisify(removeFolder);
const inputHandler = require('./inputHandler');
const domHandler = require('./domHandler');
const networkHandler = require('./networkHandler');
const pageHandler = require('./pageHandler');
const targetHandler = require('./targetHandler');
const fs = require('fs');
const os = require('os');
const mkdtempAsync = helper.promisify(fs.mkdtemp);
const path = require('path');
const CHROME_PROFILE_PATH = path.join(os.tmpdir(), 'taiko_dev_profile-');
const EventEmiter = require('events').EventEmitter;
const xhrEvent = new EventEmiter();
const default_timeout = 15000;
let chromeProcess, temporaryUserDataDir, page, network, runtime, input, client, dom, emulation, overlay, criTarget, currentPort, currentHost, rootId = null,
headful, security, ignoreSSLErrors, observe, observeTime;
const connect_to_cri = async (target) => {
if(client){
client.removeAllListeners();
}
return new Promise(async function connect(resolve) {
try {
if (!target) target = await cri.New({ host: currentHost, port: currentPort });
await cri({ target }, async (c) => {
client = c;
page = c.Page;
network = c.Network;
runtime = c.Runtime;
input = c.Input;
dom = c.DOM;
emulation = c.Emulation;
criTarget = c.Target;
overlay = c.Overlay;
security = c.Security;
await Promise.all([network.enable(), page.enable(), dom.enable(), overlay.enable(), security.enable()]);
await networkHandler.setNetwork(network, xhrEvent);
await inputHandler.setInput(input);
await domHandler.setDOM(dom);
await targetHandler.setTarget(criTarget, xhrEvent, connect_to_cri, currentHost, currentPort);
await pageHandler.setPage(page, xhrEvent, async function () {
if (!client) return;
rootId = null;
const { root: { nodeId } } = await dom.getDocument();
rootId = nodeId;
});
if (ignoreSSLErrors) security.setIgnoreCertificateErrors({ ignore: true });
resolve();
});
} catch (e) { setTimeout(() => { connect(resolve); }, 1000).unref(); }
});
};
const setBrowserOptions = (options) => {
options.port = options.port || 0;
options.host = options.host || '127.0.0.1';
options.headless = options.headless === undefined || options.headless === null ? true : options.headless;
headful = !options.headless;
ignoreSSLErrors = options.ignoreCertificateErrors;
observe = options.observe || false;
observeTime = options.observeTime || 3000;
return options;
};
/**
* Launches a browser with a tab. The browser will be closed when the parent node.js process is closed.
*
* @example
* openBrowser()
* openBrowser({ headless: false })
* openBrowser({args:['--window-size=1440,900']})
* openBrowser({args: [
* '--disable-gpu',
* '--disable-dev-shm-usage',
* '--disable-setuid-sandbox',
* '--no-first-run',
* '--no-sandbox',
* '--no-zygote']}) - These are recommended args that has to be passed when running in docker
*
* @param {Object} options {headless: true|false, args:['--window-size=1440,900']}
* @param {boolean} [options.headless=true] - Option to open browser in headless/headful mode.
* @param {Array} [options.args] - Args to open chromium https://peter.sh/experiments/chromium-command-line-switches/.
* @param {number} [options.port=0] - Remote debugging port if not given connects to any open port.
* @param {boolean} [options.ignoreCertificateErrors=false] - Option to ignore certificate errors.
* @param {boolean} [options.observe=false] - Option to run commands with delay to observe what's happening.
* @param {number} [option.observeTime=3000] - Option to modify delay time for observe mode.
* @returns {Promise<Object>} - Object with the description of the action performed.
*/
module.exports.openBrowser = async (options = { headless: true }) => {
const browserFetcher = new BrowserFetcher();
const chromeExecutable = browserFetcher.getExecutablePath();
options = setBrowserOptions(options);
let args = [`--remote-debugging-port=${options.port}`,'--use-mock-keychain'];
if (!args.some(arg => arg.startsWith('--user-data-dir'))) {
temporaryUserDataDir = await mkdtempAsync(CHROME_PROFILE_PATH);
args.push(`--user-data-dir=${temporaryUserDataDir}`);
}
if (options.headless) args = args.concat(['--headless', '--window-size=1440,900']);
if (options.args) args = args.concat(options.args);
chromeProcess = childProcess.spawn(chromeExecutable, args);
const endpoint = await browserFetcher.waitForWSEndpoint(chromeProcess, default_timeout);
currentHost = endpoint.host;
currentPort = endpoint.port;
await connect_to_cri();
return { description: 'Browser opened' };
};
/**
* Closes the browser and all of its tabs (if any were opened).
*
* @example
* closeBrowser()
*
* @returns {Promise<Object>} - Object with the description of the action performed.
*/
module.exports.closeBrowser = async () => {
validate();
await _closeBrowser();
networkHandler.resetInterceptors();
return { description: 'Browser closed' };
};
const _closeBrowser = async () => {
if (client) {
await page.close();
await client.close();
client = null;
}
chromeProcess.kill('SIGTERM');
chromeProcess.once('exit', async () => {
if (temporaryUserDataDir) {
try {
await removeFolderAsync(temporaryUserDataDir);
} catch (e) { }
}
});
};
/**
* Gives CRI client object.
*
* @returns {Object}
*/
module.exports.client = () => client;
/**
* Allows to switch between tabs using URL or page title.
*
* @example
* switchTo('https://taiko.gauge.org/') - switch using URL
* switchTo('Taiko') - switch using Title
*
* @param {string} targetUrl - URL/Page title of the tab to switch.
* @returns {Promise<Object>} - Object with the description of the action performed.
*/
module.exports.switchTo = async (targetUrl) => {
const target = await targetHandler.getCriTarget(targetUrl);
await connect_to_cri(target);
const { root: { nodeId } } = await dom.getDocument();
rootId = nodeId;
return { description: `Switched to tab with url "${targetUrl}"` };
};
/**
* Sets page viewport
*
* @example
* setViewPort({width:600,height:800})
*
* @param {Object} options - https://chromedevtools.github.io/devtools-protocol/tot/Emulation#method-setDeviceMetricsOverride
* @returns {Promise<Object>} - Object with the description of the action performed.
*/
module.exports.setViewPort = async (options) => {
if (options.height === undefined || options.width === undefined) throw new Error('No height and width provided');
options.mobile = options.mobile || false;
options.deviceScaleFactor = options.deviceScaleFactor || 1;
await emulation.setDeviceMetricsOverride(options);
return { description: `ViewPort is set to width ${options.width} and height ${options.height}` };
};
/**
* Launches a new tab with given url.
*
* @example
* openTab('https://taiko.gauge.org/')
*
* @param {string} targetUrl - URL/Page title of the tab to switch.
* @returns {Promise<Object>} - Object with the description of the action performed.
*/
module.exports.openTab = async (targetUrl, options = { timeout: 30000 }) => {
if (!/^https?:\/\//i.test(targetUrl) && !/^file/i.test(targetUrl)) targetUrl = 'http://' + targetUrl;
const targetPromise = new Promise((resolve) => {
xhrEvent.addListener('targetNavigated', resolve);
});
const promises = [targetPromise];
await criTarget.createTarget({ url: targetUrl });
await waitForNavigation(options.timeout, promises).catch(handleTimeout(options.timeout));
xhrEvent.removeAllListeners();
return { description: `Opened tab with url "${targetUrl}"` };
};
/**
* Closes the given tab with given url or closes current tab.
*
* @example
* closeTab() - Closes the current tab.
* closeTab('https://gauge.org') - Closes the tab with url 'https://gauge.org'.
*
* @param {string} targetUrl - URL/Page title of the tab to switch.
* @returns {Promise<Object>} - Object with the description of the action performed.
*/
module.exports.closeTab = async (targetUrl) => {
if (!targetUrl) {
targetUrl = await _getDocumentUrl();
}
let target = await targetHandler.getCriTarget(targetUrl);
let targetToConnect = await targetHandler.getTargetToConnect(targetUrl);
if (!targetToConnect) {
await _closeBrowser();
return { description: 'Closing last target and browser.' };
}
await cri.Close({ host: currentHost, port: currentPort, id: target.id });
await connect_to_cri(targetHandler.constructCriTarget(targetToConnect));
const { root: { nodeId } } = await dom.getDocument();
rootId = nodeId;
return { description: `Closed tab with url "${targetUrl}"` };
};
/**
* Opens the specified URL in the browser's tab. Adds `http` protocol to the URL if not present.
*
* @example
* goto('https://google.com')
* goto('google.com')
*
* @param {string} url - URL to navigate page to.
* @param {Object} options - {timeout:5000, headers:{'Authorization':'Basic cG9zdG1hbjpwYXNzd29y2A=='}} Default timeout is 30 seconds to override set options = {timeout:10000}, headers to override defaults.
* @returns {Promise<Object>} - Object with the description of the action performed and the final URL.
*/
module.exports.goto = async (url, options = { timeout: 30000 }) => {
validate();
if (!/^https?:\/\//i.test(url) && !/^file/i.test(url)) url = 'http://' + url;
const promises = [page.loadEventFired(),
page.frameStoppedLoading(),
page.domContentEventFired(),
new Promise((resolve) => {
xhrEvent.addListener('networkIdle', resolve);
}),
new Promise((resolve) => {
xhrEvent.addListener('firstMeaningfulPaint', resolve);
})
];
if (options.headers) await network.setExtraHTTPHeaders({ headers: options.headers });
const res = await page.navigate({ url: url });
if (res.errorText) throw new Error(`Navigation to url ${url} failed.\n REASON: ${res.errorText}`);
await waitForNavigation(options.timeout, promises).catch(handleTimeout(options.timeout));
xhrEvent.removeAllListeners();
return { description: `Navigated to url "${url}"`, url: url };
};
/**
* Reloads the page.
*
* @example
* reload('https://google.com')
* reload('https://google.com', { timeout: 10000 })
*
* @param {string} url - URL to reload
* @returns {Promise<Object>} - Object with the description of the action performed and the final URL.
*/
module.exports.reload = async (url) => {
validate();
await page.reload(url);
return { description: `"${url}" reloaded`, url: url };
};
/**
* Returns page's title.
*
* @returns {Promise<String>}
*/
module.exports.title = async () => {
validate();
const result = await runtime.evaluate({
expression: 'document.querySelector("title").textContent'
});
return result.result.value;
};
const setNavigationOptions = (options) => {
options.awaitNavigation = options.waitForNavigation === undefined || options.waitForNavigation === null ?
true : options.waitForNavigation;
options.timeout = options.timeout || default_timeout;
options.waitForStart = options.waitForStart || 500;
return options;
};
const setOptions = (options, x, y) => {
options = setNavigationOptions(options);
options.x = x;
options.y = y;
options.button = options.button || 'left';
options.clickCount = options.clickCount || 1;
options.elementsToMatch = options.elementsToMatch || 10;
return options;
};
const checkIfElementAtPointOrChild = async (e, x, y) => {
function isElementAtPointOrChild(value) {
const node = document.elementFromPoint(value.x, value.y);
return this.contains(node) ||
(window.getComputedStyle(node).getPropertyValue('opacity') < 0.1) ||
(window.getComputedStyle(this).getPropertyValue('opacity') < 0.1);
}
const { object: { objectId } } = await dom.resolveNode({ nodeId: e });
const res = await runtime.callFunctionOn({
functionDeclaration: isElementAtPointOrChild.toString(),
'arguments': [{ value: { x: x, y: y } }],
objectId
});
return res.result.value;
};
const getChildNodes = async (element) => {
function getChild() {
return this.childNodes;
}
const childNodes = [];
const res = await evaluate(element, getChild);
const { result } = await runtime.getProperties(res);
for (const r of result) {
if (isNaN(r.name)) break;
childNodes.push((await dom.requestNode({ objectId: r.value.objectId })).nodeId);
}
return childNodes;
};
const checkIfChildOfOtherMatches = async (elements, x, y) => {
const result = await runtime.evaluate({ expression: `document.elementFromPoint(${x},${y})` });
const { nodeId } = await dom.requestNode({ objectId: result.result.objectId });
if (elements.includes(nodeId)) return true;
for (const element of elements) {
const childNodes = await getChildNodes(element);
if (childNodes.includes(nodeId)) return true;
}
const childOfNodeAtPoint = await getChildNodes(nodeId);
if (childOfNodeAtPoint.some((val) => elements.includes(val))) return true;
return false;
};
const checkIfElementIsCovered = async (elem, x, y, elems, isElemAtPoint) => {
isElemAtPoint = await checkIfElementAtPointOrChild(elem, parseInt(x), parseInt(y));
//If element to be clicked and element at point are different check if it is any other element matching the selector
if (!isElemAtPoint)
isElemAtPoint = await checkIfChildOfOtherMatches(elems, parseInt(x), parseInt(y));
return isElemAtPoint;
};
/**
* Fetches an element with the given selector, scrolls it into view if needed, and then clicks in the center of the element. If there's no element matching selector, the method throws an error.
*
* @example
* click('Get Started')
* click(link('Get Started'))
*
* @param {selector|string} selector - A selector to search for element to click. If there are multiple elements satisfying the selector, the first will be clicked.
* @param {Object} options - Click options.
* @param {boolean} [options.waitForNavigation=true] - Wait for navigation after the click. Default navigation timeout is 15 seconds, to override pass `{ timeout: 10000 }` in `options` parameter.
* @param {number} [options.waitForStart=500] - wait for navigation to start. Default to 500ms
* @param {number} [options.timeout=5000] - Timeout value in milliseconds for navigation after click.
* @param {string} [options.button='left'] - `left`, `right`, or `middle`.
* @param {number} [options.clickCount=1] - Number of times to click on the element.
* @param {number} [options.elementsToMatch=10] - Number of elements to loop through to match the element with given selector.
* @returns {Promise<Object>} - Object with the description of the action performed.
*/
module.exports.click = click;
async function click(selector, options = {}, ...args) {
validate();
if (options instanceof RelativeSearchElement) {
args = [options].concat(args);
options = {};
}
const elems = isNaN(selector) ? (await handleRelativeSearch(await elements(selector), args)) : [selector];
let elemsLength = elems.length;
let isElemAtPoint;
options = setOptions(options);
if (elemsLength > options.elementsToMatch) {
elems.splice(options.elementsToMatch, elems.length);
}
for (let elem of elems) {
isElemAtPoint = false;
await scrollTo(elem);
const { x, y } = await domHandler.boundingBoxCenter(elem);
isElemAtPoint = await checkIfElementIsCovered(elem, x, y, elems, isElemAtPoint);
options = setOptions(options, x, y);
if (isElemAtPoint) {
const type = (await evaluate(elem, function getType() { return this.type; })).value;
assertType(elem, () => type !== 'file', 'Unsupported operation, use `attach` on file input field');
if (headful) await highlightElemOnAction(elem);
break;
}
}
if (!isElemAtPoint && elemsLength != elems.length)
throw Error('Please provide a better selector, Too many matches.');
if (!isElemAtPoint)
throw Error(description(selector) + ' is coverred by other element');
await doActionAwaitingNavigation(options, async () => {
options.type = 'mouseMoved';
await input.dispatchMouseEvent(options);
options.type = 'mousePressed';
await input.dispatchMouseEvent(options);
options.type = 'mouseReleased';
await input.dispatchMouseEvent(options);
});
return { description: 'Clicked ' + description(selector, true) };
}
/**
* Fetches an element with the given selector, scrolls it into view if needed, and then double clicks the element. If there's no element matching selector, the method throws an error.
*
* @example
* doubleClick('Get Started')
* doubleClick(button('Get Started'))
*
* @param {selector|string} selector - A selector to search for element to click. If there are multiple elements satisfying the selector, the first will be double clicked.
* @param {Object} options - Click options.
* @param {boolean} [options.waitForNavigation=true] - Wait for navigation after the click. Default navigation timout is 15 seconds, to override pass `{ timeout: 10000 }` in `options` parameter.
* @returns {Promise<Object>} - Object with the description of the action performed.
*/
module.exports.doubleClick = async (selector, options = {}, ...args) => {
if (options instanceof RelativeSearchElement) {
args = [options].concat(args);
options = {};
}
options = {
waitForNavigation: options.waitForNavigation !== undefined ? options.waitForNavigation : false,
clickCount: 2
};
await click(selector, options, ...args);
return { description: 'Double clicked ' + description(selector, true) };
};
/**
* Fetches an element with the given selector, scrolls it into view if needed, and then right clicks the element. If there's no element matching selector, the method throws an error.
*
* @example
* rightClick('Get Started')
* rightClick(text('Get Started'))
*
* @param {selector|string} selector - A selector to search for element to right click. If there are multiple elements satisfying the selector, the first will be double clicked.
* @param {Object} options - Click options.
* @param {boolean} [options.waitForNavigation=true] - Wait for navigation after the click. Default navigation timout is 15 seconds, to override pass `{ timeout: 10000 }` in `options` parameter.
* @returns {Promise<Object>} - Object with the description of the action performed.
*/
module.exports.rightClick = async (selector, options = {}, ...args) => {
if (options instanceof RelativeSearchElement) {
args = [options].concat(args);
options = {};
}
options = {
waitForNavigation: options.waitForNavigation !== undefined ? options.waitForNavigation : false,
button: 'right'
};
await click(selector, options, ...args);
return { description: 'Right clicked ' + description(selector, true) };
};
/**
* Fetches an element with the given selector, scrolls it into view if needed, and then hovers over the center of the element. If there's no element matching selector, the method throws an error.
*
* @example
* hover('Get Started')
* hover(link('Get Started'))
*
* @param {selector|string} selector - A selector to search for element to right click. If there are multiple elements satisfying the selector, the first will be hovered.
* @returns {Promise<Object>} - Object with the description of the action performed.
*/
module.exports.hover = async (selector, options = {}) => {
validate();
options = setNavigationOptions(options);
const e = await element(selector);
await scrollTo(e);
if (headful) await highlightElemOnAction(e);
const { x, y } = await domHandler.boundingBoxCenter(e);
const option = {
x: x,
y: y
};
await doActionAwaitingNavigation(options, async () => {
Promise.resolve().then(() => {
option.type = 'mouseMoved';
return input.dispatchMouseEvent(option);
}).catch((err) => {
throw new Error(err);
});
});
return { description: 'Hovered over the ' + description(selector, true) };
};
/**
* Fetches an element with the given selector and focuses it. If there's no element matching selector, the method throws an error.
*
* @example
* focus(textField('Username:'))
*
* @param {selector|string} selector - A selector of an element to focus. If there are multiple elements satisfying the selector, the first will be focused.
* @param {object} options - {waitForNavigation:true,waitForStart:500,timeout:10000}
* @returns {Promise<Object>} - Object with the description of the action performed.
*/
module.exports.focus = async (selector, options = {}) => {
validate();
options = setNavigationOptions(options);
await doActionAwaitingNavigation(options, async () => {
if (headful) await highlightElemOnAction(await element(selector));
await _focus(selector);
});
return { description: 'Focussed on the ' + description(selector, true) };
};
/**
* Types the given text into the focused or given element.
*
* @example
* write('admin', into('Username:'))
* write('admin', 'Username:')
* write('admin')
*
* @param {string} text - Text to type into the element.
* @param {selector|string} [into] - A selector of an element to write into.
* @param {Object} [options]
* @param {number} options.delay - Time to wait between key presses in milliseconds.
* @param {boolean} [options.waitForNavigation=true] - Wait for navigation after the click. Default navigation timeout is 15 seconds, to override pass `{ timeout: 10000 }` in `options` parameter.
* @param {number} [options.waitForStart=500] - wait for navigation to start. Default to 500ms
* @param {number} [options.timeout=5000] - Timeout value in milliseconds for navigation after click
* @returns {Promise<Object>} - Object with the description of the action performed.
*/
module.exports.write = async (text, into, options = { delay: 10 }) => {
validate();
let desc;
if (into && into.delay) {
options.delay = into.delay;
into = undefined;
}
options = setNavigationOptions(options);
await doActionAwaitingNavigation(options, async () => {
if (into) {
const selector = isString(into) ? textField(into) : into;
await _focus(selector);
await _write(text, options);
text = (await isPasswordField()) ? '*****' : text;
desc = `Wrote ${text} into the ` + description(selector, true);
return;
} else {
await _waitForFocus(options.timeout || default_timeout);
await _write(text, options);
text = (await isPasswordField()) ? '*****' : text;
desc = `Wrote ${text} into the focused element.`;
return;
}
});
return { description: desc };
};
const _waitForFocus = (timeout) => {
return Promise.race([
new Promise(resolve => { setTimeout(() => resolve(), timeout).unref(); }),
new Promise(resolve => {
setTimeout(() => {
runtime.evaluate({ expression: 'document.hasFocus()' }).then((result) => {
if (result) resolve();
});
}, 500).unref();
})
]);
};
const isPasswordField = async () => {
const result = await runtime.evaluate({
expression: 'document.activeElement.type'
});
return (result.result.value === 'password');
};
const _getActiveElementTagName = async () => {
const result = await runtime.evaluate({
expression: 'document.activeElement.tagName'
});
return result.result.value;
};
const _getActiveElementIsContentEditable = async () => {
const result = await runtime.evaluate({
expression: 'document.activeElement.isContentEditable'
});
return result.result.value;
};
const _getActiveElementDisabled = async () => {
const result = await runtime.evaluate({
expression: 'document.activeElement.disabled'
});
return result.result.value;
};
const _isActiveFieldNotWritable = async () => {
const editable = (['INPUT', 'TEXTAREA', 'SELECT'].includes(await _getActiveElementTagName()) || (await _getActiveElementIsContentEditable()));
const disabled = await _getActiveElementDisabled();
return !editable || disabled;
};
const _write = async (text, options) => {
if (await _isActiveFieldNotWritable())
throw new Error('Element focused is not writable');
if (headful) {
const result = await runtime.evaluate({ expression: 'document.activeElement' });
const { nodeId } = await dom.requestNode({ objectId: result.result.objectId });
await highlightElemOnAction(nodeId);
}
for (const char of text) {
await new Promise(resolve => setTimeout(resolve, options.delay).unref());
await input.dispatchKeyEvent({ type: 'char', text: char });
}
};
const _getDocumentUrl = async () => {
const result = await runtime.evaluate({
expression: 'window.location.toString()'
});
return result.result.value;
};
/**
* Clears the value of given selector. If no selector is given clears the current active element.
*
* @example
* clear()
* clear(inputField({placeholder:'Email'}))
*
* @param {selector} selector - A selector to search for element to clear. If there are multiple elements satisfying the selector, the first will be cleared.
* @param {Object} options - Click options.
* @param {boolean} [options.waitForNavigation=true] - Wait for navigation after clear. Default navigation timeout is 15 seconds, to override pass `{ timeout: 10000 }` in `options` parameter.
* @param {number} [options.waitForStart=500] - wait for navigation to start. Default to 500ms
* @param {number} [options.timeout=5000] - Timeout value in milliseconds for navigation after click.
* @returns {Promise<Object>} - Object with the description of the action performed.
*/
module.exports.clear = async (selector, options = {}) => {
let nodeId, desc;
options = setNavigationOptions(options);
if(selector)await _focus(selector);
if (await _isActiveFieldNotWritable())
throw new Error('Element cannot be cleared');
if (!selector) {
const result = await runtime.evaluate({ expression: 'document.activeElement' });
const res = await dom.requestNode({ objectId: result.result.objectId });
nodeId = res.nodeId;
desc = { description: 'Cleared element on focus' };
} else {
nodeId = await element(selector);
desc = { description: 'Cleared ' + description(selector, true) };
}
await doActionAwaitingNavigation(options, async () => {
await _clear(nodeId);
if (headful) await highlightElemOnAction(nodeId);
});
return desc;
};
const _clear = async (elem) => {
await click(elem, { clickCount: 3, waitForNavigation: false });
await inputHandler.down('Backspace');
await inputHandler.up('Backspace');
};
/**
* Attaches a file to a file input element.
*
* @example
* attach('c:/abc.txt', to('Please select a file:'))
* attach('c:/abc.txt', 'Please select a file:')
*
* @param {string} filepath - The path of the file to be attached.
* @param {selector|string} to - The file input element to which to attach the file.
* @returns {Promise<Object>} - Object with the description of the action performed.
*/
module.exports.attach = async (filepath, to) => {
validate();
let resolvedPath = filepath ? path.resolve(process.cwd(), filepath) : path.resolve(process.cwd());
fs.open(resolvedPath, 'r', (err) => {
if (err && err.code === 'ENOENT') {
throw new Error(`File ${resolvedPath} doesnot exists.`);
}
});
if (isString(to)) to = fileField(to);
else if (!isSelector(to)) throw Error('Invalid element passed as paramenter');
const nodeId = await element(to);
if (headful) await highlightElemOnAction(nodeId);
await dom.setFileInputFiles({
nodeId: nodeId,
files: [resolvedPath]
});
return { description: `Attached ${resolvedPath} to the ` + description(to, true) };
};
/**
* Presses the given keys.
*
* @example
* press('Enter')
* press('a')
* press(['Shift', 'ArrowLeft', 'ArrowLeft'])
*
* @param {string | Array<string> } keys - Name of keys to press, such as ArrowLeft. See [USKeyboardLayout](https://github.com/getgauge/taiko/blob/master/lib/USKeyboardLayout.js) for a list of all key names.
* @param {Object} options
* @param {string} [options.text] - If specified, generates an input event with this text.
* @param {number} [options.delay=0] - Time to wait between keydown and keyup in milliseconds.
* @param {boolean} [options.waitForNavigation=true] - Wait for navigation after the click. Default navigation timeout is 15 seconds, to override pass `{ timeout: 10000 }` in `options` parameter.
* @param {number} [options.waitForStart=500] - wait for navigation to start. Default to 500ms
* @param {number} [options.timeout=5000] - Timeout value in milliseconds for navigation after click.
* @returns {Promise<Object>} - Object with the description of the action performed.
*/
module.exports.press = async (keys, options = {}) => {
validate();
options = setNavigationOptions(options);
return await _press(new Array().concat(keys), options);
};
async function _press(keys, options) {
await doActionAwaitingNavigation(options, async () => {
for (let i = 0; i < keys.length; i++) await inputHandler.down(keys[i], options);
if (options && options.delay) await new Promise(f => setTimeout(f, options.delay).unref());
keys = keys.reverse();
for (let i = 0; i < keys.length; i++) await inputHandler.up(keys[i]);
});
return { description: `Pressed the ${keys.reverse().join(' + ')} key` };
}
/**
* Highlights the given element on the page by drawing a red rectangle around it. This is useful for debugging purposes.
*
* @example
* highlight('Get Started')
* highlight(link('Get Started'))
*
* @param {selector|string} selector - A selector of an element to highlight. If there are multiple elements satisfying the selector, the first will be highlighted.
* @param {...relativeSelector} args - Proximity selectors
* @returns {Promise<Object>} - Object with the description of the action performed.
*/
module.exports.highlight = highlight;
async function highlight(selector, ...args) {
validate();
function highlightNode() {
this.style.border = '0.5em solid red';
return true;
}
let elems = await handleRelativeSearch(await elements(selector), args);
await evaluate(elems[0], highlightNode);
return { description: 'Highlighted the ' + description(selector, true) };
}
/**
* Scrolls the page to the given element.
*
* @example
* scrollTo('Get Started')
* scrollTo(link('Get Started'))
*
* @param {selector|string} selector - A selector of an element to scroll to.
* @returns {Promise<Object>} - Object with the description of the action performed.
*/
module.exports.scrollTo = async (selector, options = {}) => {
options = setNavigationOptions(options);
await doActionAwaitingNavigation(options, async () => {
await scrollTo(selector);
});
if (headful) await highlightElemOnAction(await element(selector));
return { description: 'Scrolled to the ' + description(selector, true) };
};
async function scrollTo(selector) {
validate();
function scrollToNode() {
this.scrollIntoViewIfNeeded();
return 'result';
}
await evaluate(selector, scrollToNode);
}
const scroll = async (e, px, scrollPage, scrollElement, direction) => {
e = e || 100;
if (Number.isInteger(e)) {
await runtime.evaluate({ expression: `(${scrollPage}).apply(null, ${JSON.stringify([e])})` });
return { description: `Scrolled ${direction} the page by ${e} pixels` };
}
const nodeId = await element(e);
if (headful) await highlightElemOnAction(nodeId);
const { object: { objectId } } = await dom.resolveNode({ nodeId });
//TODO: Allow user to set options for scroll
const options = setNavigationOptions({});
await doActionAwaitingNavigation(options, async () => {
await runtime.callFunctionOn({
functionDeclaration: scrollElement.toString(),
'arguments': [{ value: px }],
objectId
});
});
return { description: `Scrolled ${direction} ` + description(e, true) + ` by ${px} pixels` };
};
/**
* Scrolls the page/element to the right.
*
* @example
* scrollRight()
* scrollRight(1000)
* scrollRight('Element containing text')
* scrollRight('Element containing text', 1000)
*
* @param {selector|string|number} [e='Window']
* @param {number} [px=100]
* @returns {Promise<Object>} - Object with the description of the action performed.
*/
module.exports.scrollRight = async (e, px = 100) => {
validate();
return await scroll(e, px, px => window.scrollBy(px, 0), function sr(px) { this.scrollLeft += px; return true; }, 'right');
};
/**
* Scrolls the page/element to the left.
*
* @example
* scrollLeft()
* scrollLeft(1000)
* scrollLeft('Element containing text')
* scrollLeft('Element containing text', 1000)
*
* @param {selector|string|number} [e='Window']
* @param {number} [px=100]
* @returns {Promise<Object>} - Object with the description of the action performed.
*/
module.exports.scrollLeft = async (e, px = 100) => {
validate();
return await scroll(e, px, px => window.scrollBy(px * -1, 0), function sl(px) { this.scrollLeft -= px; return true; }, 'left');
};
/**
* Scrolls up the page/element.
*
* @example
* scrollUp()
* scrollUp(1000)
* scrollUp('Element containing text')
* scrollUp('Element containing text', 1000)
*
* @param {selector|string|number} [e='Window']
* @param {number} [px=100]
* @returns {Promise<Object>} - Object with the description of the action performed.
*/
module.exports.scrollUp = async (e, px = 100) => {
validate();
return await scroll(e, px, px => window.scrollBy(0, px * -1), function su(px) { this.scrollTop -= px; return true; }, 'up');
};
/**
* Scrolls down the page/element.
*
* @example
* scrollDown()
* scrollDown(1000)
* scrollDown('Element containing text')
* scrollDown('Element containing text', 1000)
*
* @param {selector|string|number} [e='Window']
* @param {number} [px=100]
* @returns {Promise<Object>} - Object with the description of the action performed.
*/
module.exports.scrollDown = async (e, px = 100) => {
validate();
return await scroll(e, px, px => window.scrollBy(0, px), function sd(px) { this.scrollTop += px; return true; }, 'down');
};
/**
* Captures a screenshot of the page. Appends timeStamp to filename if no filepath given.
*
* @example
* screenshot()
* screenshot({path : 'screenshot.png'})
*
* @param {object} options - {path:'screenshot.png'} or {encoding:'base64'}
* @returns {Promise<Buffer>} - Promise which resolves to buffer with captured screenshot if {encoding:'base64} given.
* @returns {Promise<object>} - Object with the description of the action performed
*/
module.exports.screenshot = async (options = {}) => {
validate();
options.path = options.path || `Screenshot-${Date.now()}.png`;
const { data } = await page.captureScreenshot();
if (options.encoding === 'base64') return data;
fs.writeFileSync(options.path, Buffer.from(data, 'base64'));
return { description: `Screenshot is created at "${options.path}"` };
};
/**
* This {@link selector} lets you identify elements on the web page via XPath or CSS selector.
* @example
* highlight($(`//*[text()='text']`))
* $(`//*[text()='text']`).exists()
* $(`#id`)
*
* @param {string} selector - XPath or CSS selector.
* @param {...relativeSelector} args - Proximity selectors
* @returns {ElementWrapper}
*/
module.exports.$ = (selector, ...args) => {
validate();
const get = async () => await handleRelativeSearch(await (selector.startsWith('//') || selector.startsWith('(') ? $$xpath(selector) : $$(selector)), args);
return {
get: getIfExists(get),
exists: exists(getIfExists(get)),
description: `Custom selector $(${selector})`,
text: selectorText(get)
};
};
const getValues = (attrValuePairs, args) => {
if (attrValuePairs instanceof RelativeSearchElement) {
args = [attrValuePairs].concat(args);
return { args: args };
}
if (isString(attrValuePairs) || isSelector(attrValuePairs)) {
return { label: attrValuePairs, args: args };
}
return { attrValuePairs: attrValuePairs, args: args };
};
const getQuery = (attrValuePairs, tag = '') => {
let xpath = tag;
for (const key in attrValuePairs) {
if (key === 'class') xpath += `[${key}*="${attrValuePairs[key]}"]`;
else xpath += `[${key}="${attrValuePairs[key]}"]`;
}
return xpath;
};
const getElementGetter = (selector, query, tag) => {
let get;
if (selector.attrValuePairs) get = async () => await handleRelativeSearch(await $$(getQuery(selector.attrValuePairs, tag)), selector.args);
else if (selector.label) get = async () => await handleRelativeSearch(await query(), selector.args);
else get = async () => await handleRelativeSearch(await $$(tag), selector.args);
return get;
};
const desc = (selector, query, tag) => {
let description = '';
if (selector.attrValuePairs) description = getQuery(selector.attrValuePairs, tag);
else if (selector.label) description = `${tag} with ${query} ${selector.label} `;
for (const arg of selector.args) {
description += description === '' ? tag : ' and';
description += ' ' + arg.toString();
}
return description;
};
/**
* This {@link selector} lets you identify an image on a web page. Typically, this is done via the image's alt text or attribute and value pairs.
*
* @example
* click(image('alt'))
* image('alt').exists()
*
* @param {string} alt - The image's alt text.
* @param {object} attrValuePairs - Pairs of attribute and value like {"id":"name","class":"class-name"}
* @param {...relativeSelector} args - Proximity selectors
* @returns {ElementWrapper}
*/
module.exports.image = (attrValuePairs, ...args) => {
validate();
const selector = getValues(attrValuePairs, args);
const get = getElementGetter(selector, async () => await $$xpath(`//img[contains(@alt, ${xpath(selector.label)})]`), 'img');
return { get: getIfExists(get), exists: exists(getIfExists(get)), description: desc(selector, 'alt', 'Image'), text: selectorText(get) };
};