-
-
Notifications
You must be signed in to change notification settings - Fork 731
/
Copy pathPlaywright.js
2527 lines (2265 loc) · 72.1 KB
/
Playwright.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 path = require('path');
const fs = require('fs');
const Helper = require('../helper');
const Locator = require('../locator');
const recorder = require('../recorder');
const stringIncludes = require('../assert/include').includes;
const { urlEquals } = require('../assert/equal');
const { equals } = require('../assert/equal');
const { empty } = require('../assert/empty');
const { truth } = require('../assert/truth');
const {
xpathLocator,
ucfirst,
fileExists,
chunkArray,
toCamelCase,
convertCssPropertiesToCamelCase,
screenshotOutputFolder,
getNormalizedKeyAttributeValue,
isModifierKey,
} = require('../utils');
const {
isColorProperty,
convertColorToRGBA,
} = require('../colorUtils');
const ElementNotFound = require('./errors/ElementNotFound');
const RemoteBrowserConnectionRefused = require('./errors/RemoteBrowserConnectionRefused');
const Popup = require('./extras/Popup');
const Console = require('./extras/Console');
let playwright;
let perfTiming;
let defaultSelectorEnginesInitialized = false;
const popupStore = new Popup();
const consoleLogStore = new Console();
const availableBrowsers = ['chromium', 'webkit', 'firefox'];
const { createValueEngine, createDisabledEngine } = require('./extras/PlaywrightPropEngine');
/**
* Uses [Playwright](https://github.com/microsoft/playwright) library to run tests inside:
*
* * Chromium
* * Firefox
* * Webkit (Safari)
*
* This helper works with a browser out of the box with no additional tools required to install.
*
* Requires `playwright` package version ^1 to be installed:
*
* ```
* npm i playwright@^1 --save
* ```
*
* ## Configuration
*
* This helper should be configured in codecept.json or codecept.conf.js
*
* * `url`: base url of website to be tested
* * `browser`: a browser to test on, either: `chromium`, `firefox`, `webkit`. Default: chromium.
* * `show`: (optional, default: false) - show browser window.
* * `restart`: (optional, default: true) - restart browser between tests.
* * `disableScreenshots`: (optional, default: false) - don't save screenshot on failure.
* * `emulate`: (optional, default: {}) launch browser in device emulation mode.
* * `fullPageScreenshots` (optional, default: false) - make full page screenshots 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` is set to false.
* * `keepCookies`: (optional, default: false) - keep cookies between tests when `restart` is set to false.
* * `waitForAction`: (optional) how long to wait after click, doubleClick or PressKey actions in ms. Default: 100.
* * `waitForNavigation`: (optional, default: 'load'). When to consider navigation succeeded. Possible options: `load`, `domcontentloaded`, `networkidle`. Choose one of those options is possible. See [Playwright API](https://github.com/microsoft/playwright/blob/master/docs/api.md#pagewaitfornavigationoptions).
* * `pressKeyDelay`: (optional, default: '10'). Delay between key presses in ms. Used when calling Playwrights page.type(...) in fillField/appendField
* * `getPageTimeout` (optional, default: '0') config option to set maximum navigation time in milliseconds.
* * `waitForTimeout`: (optional) default wait* timeout in ms. Default: 1000.
* * `basicAuth`: (optional) the basic authentication to pass to base url. Example: {username: 'username', password: 'password'}
* * `windowSize`: (optional) default window size. Set a dimension like `640x480`.
* * `userAgent`: (optional) user-agent string.
* * `manualStart`: (optional, default: false) - do not start browser before a test, start it manually inside a helper with `this.helpers["Playwright"]._startBrowser()`.
* * `chromium`: (optional) pass additional chromium options
*
* #### Example #1: Wait for 0 network connections.
*
* ```js
* {
* helpers: {
* Playwright : {
* url: "http://localhost",
* restart: false,
* waitForNavigation: "networkidle0",
* waitForAction: 500
* }
* }
* }
* ```
*
* #### Example #2: Wait for DOMContentLoaded event
*
* ```js
* {
* helpers: {
* Playwright : {
* url: "http://localhost",
* restart: false,
* waitForNavigation: "domcontentloaded",
* waitForAction: 500
* }
* }
* }
* ```
*
* #### Example #3: Debug in window mode
*
* ```js
* {
* helpers: {
* Playwright : {
* url: "http://localhost",
* show: true
* }
* }
* }
* ```
*
* #### Example #4: Connect to remote browser by specifying [websocket endpoint](https://chromedevtools.github.io/devtools-protocol/#how-do-i-access-the-browser-target)
*
* ```js
* {
* helpers: {
* Playwright: {
* url: "http://localhost",
* chromium: {
* browserWSEndpoint: "ws://localhost:9222/devtools/browser/c5aa6160-b5bc-4d53-bb49-6ecb36cd2e0a"
* }
* }
* }
* }
* ```
*
* #### Example #5: Testing with Chromium extensions
*
* [official docs](https://github.com/microsoft/playwright/blob/v0.11.0/docs/api.md#working-with-chrome-extensions)
*
* ```js
* {
* helpers: {
* Playwright: {
* url: "http://localhost",
* show: true // headless mode not supported for extensions
* chromium: {
* args: [
* `--disable-extensions-except=${pathToExtension}`,
* `--load-extension=${pathToExtension}`
* ]
* }
* }
* }
* }
* ```
*
* #### Example #6: Launch tests emulating iPhone 6
*
*
*
* ```js
* const { devices } = require('playwright');
*
* {
* helpers: {
* Playwright: {
* url: "http://localhost",
* emulate: devices['iPhone 6'],
* }
* }
* }
* ```
*
* Note: When connecting to remote browser `show` and specific `chrome` options (e.g. `headless` or `devtools`) are ignored.
*
* ## Access From Helpers
*
* Receive Playwright client from a custom helper by accessing `browser` for the Browser object or `page` for the current Page object:
*
* ```js
* const { browser } = this.helpers.Playwright;
* await browser.pages(); // List of pages in the browser
*
* // get current page
* const { page } = this.helpers.Playwright;
* await page.url(); // Get the url of the current page
*
* const { browserContext } = this.helpers.Playwright;
* await browserContext.cookies(); // get current browser context
* ```
*
* ## Methods
*/
class Playwright extends Helper {
constructor(config) {
super(config);
playwright = require('playwright');
// set defaults
this.isRemoteBrowser = false;
this.isRunning = false;
this.isAuthenticated = false;
this.sessionPages = {};
this.activeSessionName = '';
// override defaults with config
this._setConfig(config);
}
_validateConfig(config) {
const defaults = {
// options to emulate context
emulate: {},
browser: 'chromium',
waitForAction: 100,
waitForTimeout: 1000,
pressKeyDelay: 10,
fullPageScreenshots: false,
disableScreenshots: false,
uniqueScreenshotNames: false,
manualStart: false,
getPageTimeout: 0,
waitForNavigation: 'load',
restart: false,
keepCookies: false,
keepBrowserState: false,
show: false,
defaultPopupAction: 'accept',
ignoreHTTPSErrors: false, // Adding it here o that context can be set up to ignore the SSL errors
};
config = Object.assign(defaults, config);
if (availableBrowsers.indexOf(config.browser) < 0) {
throw new Error(`Invalid config. Can't use browser "${config.browser}". Accepted values: ${availableBrowsers.join(', ')}`);
}
return config;
}
_getOptionsForBrowser(config) {
return config[config.browser] ? {
...config[config.browser],
wsEndpoint: config[config.browser].browserWSEndpoint,
} : {};
}
_setConfig(config) {
this.options = this._validateConfig(config);
this.playwrightOptions = {
headless: !this.options.show,
...this._getOptionsForBrowser(config),
};
this.isRemoteBrowser = !!this.playwrightOptions.browserWSEndpoint;
popupStore.defaultAction = this.options.defaultPopupAction;
}
static _config() {
return [
{ name: 'url', message: 'Base url of site to be tested', default: 'http://localhost' },
{
name: 'show', message: 'Show browser window', default: true, type: 'confirm',
},
{
name: 'browser',
message: 'Browser in which testing will be performed. Possible options: chromium, firefox or webkit',
default: 'chromium',
},
];
}
static _checkRequirements() {
try {
require('playwright');
} catch (e) {
return ['playwright@^1'];
}
}
async _init() {
// register an internal selector engine for reading value property of elements in a selector
if (defaultSelectorEnginesInitialized) return;
defaultSelectorEnginesInitialized = true;
try {
await playwright.selectors.register('__value', createValueEngine);
await playwright.selectors.register('__disabled', createDisabledEngine);
} catch (e) {
console.warn(e);
}
}
_beforeSuite() {
if (!this.options.restart && !this.options.manualStart && !this.isRunning) {
this.debugSection('Session', 'Starting singleton browser session');
return this._startBrowser();
}
}
async _before() {
recorder.retry({
retries: 5,
when: err => {
if (!err || typeof (err.message) !== 'string') {
return false;
}
// ignore context errors
return err.message.includes('context');
},
});
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;
// close other sessions
const contexts = await this.browser.contexts();
contexts.shift();
await Promise.all(contexts.map(c => c.close()));
if (this.options.restart) {
this.isRunning = false;
return this._stopBrowser();
}
// ensure current page is in default context
if (this.page) {
const existingPages = await this.browserContext.pages();
await this._setPage(existingPages[0]);
}
if (this.options.keepBrowserState) return;
if (!this.options.keepCookies) {
this.debugSection('Session', 'cleaning cookies and localStorage');
await this.clearCookie();
}
const currentUrl = await this.grabCurrentUrl();
if (currentUrl.startsWith('http')) {
await this.executeScript('localStorage.clear();').catch((err) => {
if (!(err.message.indexOf("Storage is disabled inside 'data:' URLs.") > -1)) throw err;
});
await this.executeScript('sessionStorage.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._stopBrowser();
}
_session() {
const defaultContext = this.browserContext;
return {
start: async (sessionName = '', config) => {
this.debugSection('New Context', config ? JSON.stringify(config) : 'opened');
this.activeSessionName = sessionName;
const bc = await this.browser.newContext(config);
const page = await bc.newPage();
targetCreatedHandler.call(this, page);
this._setPage(page);
// Create a new page inside context.
return bc;
},
stop: async () => {
// is closed by _after
},
loadVars: async (context) => {
this.browserContext = context;
const existingPages = await context.pages();
this.sessionPages[this.activeSessionName] = existingPages[0];
return this._setPage(this.sessionPages[this.activeSessionName]);
},
restoreVars: async (session) => {
this.withinLocator = null;
this.browserContext = defaultContext;
if (!session) {
this.activeSessionName = '';
} else {
this.activeSessionName = session;
}
const existingPages = await this.browserContext.pages();
await this._setPage(existingPages[0]);
return this._waitForAction();
},
};
}
/**
* Use Playwright API inside a test.
*
* First argument is a description of an action.
* Second argument is async function that gets this helper as parameter.
*
* { [`page`](https://github.com/microsoft/playwright/blob/master/docs/api.md#class-page), [`context`](https://github.com/microsoft/playwright/blob/master/docs/api.md#class-context) [`browser`](https://github.com/microsoft/playwright/blob/master/docs/api.md#class-browser) } objects from Playwright API are available.
*
* ```js
* I.usePlaywrightTo('emulate offline mode', async ({ context }) {
* await context.setOffline(true);
* });
* ```
*
* @param {string} description used to show in logs.
* @param {function} fn async functuion that executed with Playwright helper as argument
*/
usePlaywrightTo(description, fn) {
return this._useTo(...arguments);
}
/**
* Set the automatic popup response to Accept.
* This must be set before a popup is triggered.
*
* ```js
* I.amAcceptingPopups();
* I.click('#triggerPopup');
* I.acceptPopup();
* ```
*/
amAcceptingPopups() {
popupStore.actionType = 'accept';
}
/**
* Accepts the active JavaScript native popup window, as created by window.alert|window.confirm|window.prompt.
* Don't confuse popups with modal windows, as created by [various
* libraries](http://jster.net/category/windows-modals-popups).
*/
acceptPopup() {
popupStore.assertPopupActionType('accept');
}
/**
* Set the automatic popup response to Cancel/Dismiss.
* This must be set before a popup is triggered.
*
* ```js
* I.amCancellingPopups();
* I.click('#triggerPopup');
* I.cancelPopup();
* ```
*/
amCancellingPopups() {
popupStore.actionType = 'cancel';
}
/**
* Dismisses the active JavaScript popup, as created by window.alert|window.confirm|window.prompt.
*/
cancelPopup() {
popupStore.assertPopupActionType('cancel');
}
/**
* {{> seeInPopup }}
*/
async seeInPopup(text) {
popupStore.assertPopupVisible();
const popupText = await popupStore.popup.message();
stringIncludes('text in popup').assert(text, popupText);
}
/**
* Set current page
* @param {object} page page to set
*/
async _setPage(page) {
page = await page;
this._addPopupListener(page);
this.page = page;
if (!page) return;
page.setDefaultNavigationTimeout(this.options.getPageTimeout);
this.context = await this.page.$('body');
if (this.config.browser === 'chrome') {
await page.bringToFront();
}
}
/**
* Add the 'dialog' event listener to a page
* @page {playwright.Page}
*
* The popup listener handles the dialog with the predefined action when it appears on the page.
* It also saves a reference to the object which is used in seeInPopup.
*/
_addPopupListener(page) {
if (!page) {
return;
}
page.on('dialog', async (dialog) => {
popupStore.popup = dialog;
const action = popupStore.actionType || this.options.defaultPopupAction;
await this._waitForAction();
switch (action) {
case 'accept':
return dialog.accept();
case 'cancel':
return dialog.dismiss();
default: {
throw new Error('Unknown popup action type. Only "accept" or "cancel" are accepted');
}
}
});
}
/**
* Gets page URL including hash.
*/
async _getPageUrl() {
return this.executeScript(() => window.location.href);
}
/**
* Grab the text within the popup. If no popup is visible then it will return null
*
* ```js
* await I.grabPopupText();
* ```
* @return {Promise<string | null>}
*/
async grabPopupText() {
if (popupStore.popup) {
return popupStore.popup.message();
}
return null;
}
async _startBrowser() {
if (this.isRemoteBrowser) {
try {
this.browser = await playwright[this.options.browser].connect(this.playwrightOptions);
} catch (err) {
if (err.toString().indexOf('ECONNREFUSED')) {
throw new RemoteBrowserConnectionRefused(err);
}
throw err;
}
} else {
this.browser = await playwright[this.options.browser].launch(this.playwrightOptions);
}
// works only for Chromium
this.browser.on('targetchanged', (target) => {
this.debugSection('Url', target.url());
});
this.browserContext = await this.browser.newContext({ ignoreHTTPSErrors: this.options.ignoreHTTPSErrors, acceptDownloads: true, ...this.options.emulate });// Adding the HTTPSError ignore in the context so that we can ignore those errors
const existingPages = await this.browserContext.pages();
const mainPage = existingPages[0] || await this.browserContext.newPage();
targetCreatedHandler.call(this, mainPage);
await this._setPage(mainPage);
await this.closeOtherTabs();
this.isRunning = true;
}
async _stopBrowser() {
this.withinLocator = null;
this._setPage(null);
this.context = null;
popupStore.clear();
await this.browser.close();
}
async _evaluateHandeInContext(...args) {
const context = await this._getContext();
return context.evaluateHandle(...args);
}
async _withinBegin(locator) {
if (this.withinLocator) {
throw new Error('Can\'t start within block inside another within block');
}
const frame = isFrameLocator(locator);
if (frame) {
if (Array.isArray(frame)) {
await this.switchTo(null);
return frame.reduce((p, frameLocator) => p.then(() => this.switchTo(frameLocator)), Promise.resolve());
}
await this.switchTo(locator);
this.withinLocator = new Locator(locator);
return;
}
const els = await this._locate(locator);
assertElementExists(els, locator);
this.context = els[0];
this.withinLocator = new Locator(locator);
}
async _withinEnd() {
this.withinLocator = null;
this.context = await this.page.mainFrame().$('body');
}
_extractDataFromPerformanceTiming(timing, ...dataNames) {
const navigationStart = timing.navigationStart;
const extractedData = {};
dataNames.forEach((name) => {
extractedData[name] = timing[name] - navigationStart;
});
return extractedData;
}
/**
* {{> amOnPage }}
*/
async amOnPage(url) {
if (!(/^\w+\:\/\//.test(url))) {
url = this.options.url + url;
}
if (this.config.basicAuth && (this.isAuthenticated !== true)) {
if (url.includes(this.options.url)) {
await this.browserContext.setHTTPCredentials(this.config.basicAuth);
this.isAuthenticated = true;
}
}
await this.page.goto(url, { waitUntil: this.options.waitForNavigation });
const performanceTiming = JSON.parse(await this.page.evaluate(() => JSON.stringify(window.performance.timing)));
perfTiming = this._extractDataFromPerformanceTiming(
performanceTiming,
'responseEnd',
'domInteractive',
'domContentLoadedEventEnd',
'loadEventEnd',
);
return this._waitForAction();
}
/**
* {{> resizeWindow }}
*
* Unlike other drivers Playwright changes the size of a viewport, not the window!
* Playwright does not control the window of a browser so it can't adjust its real size.
* It also can't maximize a window.
*
* Update configuration to change real window size on start:
*
* ```js
* // inside codecept.conf.js
* // @codeceptjs/configure package must be installed
* { setWindowSize } = require('@codeceptjs/configure');
* ````
*/
async resizeWindow(width, height) {
if (width === 'maximize') {
throw new Error('Playwright can\'t control windows, so it can\'t maximize it');
}
await this.page.setViewportSize({ width, height });
return this._waitForAction();
}
/**
* Set headers for all next requests
*
* ```js
* I.haveRequestHeaders({
* 'X-Sent-By': 'CodeceptJS',
* });
* ```
*
* @param {object} customHeaders headers to set
*/
async haveRequestHeaders(customHeaders) {
if (!customHeaders) {
throw new Error('Cannot send empty headers.');
}
return this.page.setExtraHTTPHeaders(customHeaders);
}
/**
* {{> moveCursorTo }}
*
*/
async moveCursorTo(locator, offsetX = 0, offsetY = 0) {
const els = await this._locate(locator);
assertElementExists(els);
// Use manual mouse.move instead of .hover() so the offset can be added to the coordinates
const { x, y } = await clickablePoint(els[0]);
await this.page.mouse.move(x + offsetX, y + offsetY);
return this._waitForAction();
}
/**
* {{> dragAndDrop }}
*/
async dragAndDrop(srcElement, destElement) {
return proceedDragAndDrop.call(this, srcElement, destElement);
}
/**
* {{> refreshPage }}
*/
async refreshPage() {
return this.page.reload({ timeout: this.options.getPageTimeout, waitUntil: this.options.waitForNavigation });
}
/**
* {{> scrollPageToTop }}
*/
scrollPageToTop() {
return this.executeScript(() => {
window.scrollTo(0, 0);
});
}
/**
* {{> scrollPageToBottom }}
*/
scrollPageToBottom() {
return this.executeScript(() => {
const body = document.body;
const html = document.documentElement;
window.scrollTo(0, Math.max(
body.scrollHeight, body.offsetHeight,
html.clientHeight, html.scrollHeight, html.offsetHeight,
));
});
}
/**
* {{> scrollTo }}
*/
async scrollTo(locator, offsetX = 0, offsetY = 0) {
if (typeof locator === 'number' && typeof offsetX === 'number') {
offsetY = offsetX;
offsetX = locator;
locator = null;
}
if (locator) {
const els = await this._locate(locator);
assertElementExists(els, locator, 'Element');
await els[0].scrollIntoViewIfNeeded();
const elementCoordinates = await clickablePoint(els[0]);
await this.executeScript((offsetX, offsetY) => window.scrollBy(offsetX, offsetY), { offsetX: elementCoordinates.x + offsetX, offsetY: elementCoordinates.y + offsetY });
} else {
await this.executeScript(({ offsetX, offsetY }) => window.scrollTo(offsetX, offsetY), { offsetX, offsetY });
}
return this._waitForAction();
}
/**
* {{> seeInTitle }}
*/
async seeInTitle(text) {
const title = await this.page.title();
stringIncludes('web page title').assert(text, title);
}
/**
* {{> grabPageScrollPosition }}
*/
async grabPageScrollPosition() {
/* eslint-disable comma-dangle */
function getScrollPosition() {
return {
x: window.pageXOffset,
y: window.pageYOffset
};
}
/* eslint-enable comma-dangle */
return this.executeScript(getScrollPosition);
}
/**
* Checks that title is equal to provided one.
*
* ```js
* I.seeTitleEquals('Test title.');
* ```
*/
async seeTitleEquals(text) {
const title = await this.page.title();
return equals('web page title').assert(title, text);
}
/**
* {{> dontSeeInTitle }}
*/
async dontSeeInTitle(text) {
const title = await this.page.title();
stringIncludes('web page title').negate(text, title);
}
/**
* {{> grabTitle }}
*/
async grabTitle() {
return this.page.title();
}
/**
* Get elements by different locator types, including strict locator
* Should be used in custom helpers:
*
* ```js
* const elements = await this.helpers['Playwright']._locate({name: 'password'});
* ```
*
*
*/
async _locate(locator) {
return findElements(await this.context, locator);
}
/**
* Find a checkbox by providing human readable text:
* NOTE: Assumes the checkable element exists
*
* ```js
* this.helpers['Playwright']._locateCheckable('I agree with terms and conditions').then // ...
* ```
*/
async _locateCheckable(locator, providedContext = null) {
const context = providedContext || await this._getContext();
const els = await findCheckable.call(this, locator, context);
assertElementExists(els[0], locator, 'Checkbox or radio');
return els[0];
}
/**
* Find a clickable element by providing human readable text:
*
* ```js
* this.helpers['Playwright']._locateClickable('Next page').then // ...
* ```
*/
async _locateClickable(locator) {
const context = await this._getContext();
return findClickable.call(this, context, locator);
}
/**
* Find field elements by providing human readable text:
*
* ```js
* this.helpers['Playwright']._locateFields('Your email').then // ...
* ```
*/
async _locateFields(locator) {
return findFields.call(this, locator);
}
/**
* Switch focus to a particular tab by its number. It waits tabs loading and then switch tab
*
* ```js
* I.switchToNextTab();
* I.switchToNextTab(2);
* ```
*
* @param {number} [num=1]
*/
async switchToNextTab(num = 1) {
const pages = await this.browserContext.pages();
const index = pages.indexOf(this.page);
this.withinLocator = null;
const page = pages[index + num];
if (!page) {
throw new Error(`There is no ability to switch to next tab with offset ${num}`);
}
await this._setPage(page);
return this._waitForAction();
}
/**
* Switch focus to a particular tab by its number. It waits tabs loading and then switch tab
*
* ```js
* I.switchToPreviousTab();
* I.switchToPreviousTab(2);
* ```
* @param {number} [num=1]
*/
async switchToPreviousTab(num = 1) {
const pages = await this.browserContext.pages();
const index = pages.indexOf(this.page);
this.withinLocator = null;
const page = pages[index - num];
if (!page) {
throw new Error(`There is no ability to switch to previous tab with offset ${num}`);
}
await this._setPage(page);
return this._waitForAction();
}
/**
* Close current tab and switches to previous.
*
* ```js
* I.closeCurrentTab();
* ```
*/
async closeCurrentTab() {
const oldPage = this.page;
await this.switchToPreviousTab();
await oldPage.close();
return this._waitForAction();
}
/**
* Close all tabs except for the current one.
*
* ```js
* I.closeOtherTabs();
* ```
*/
async closeOtherTabs() {
const pages = await this.browserContext.pages();
const otherPages = pages.filter(page => page !== this.page);
if (otherPages.length) {
this.debug(`Closing ${otherPages.length} tabs`);
return Promise.all(otherPages.map(p => p.close()));
}
return Promise.resolve();
}
/**
* Open new tab and automatically switched to new tab
*
* ```js
* I.openNewTab();
* ```
*
* You can pass in [page options](https://github.com/microsoft/playwright/blob/master/docs/api.md#browsernewpageoptions) to emulate device on this page
*
* ```js
* // enable mobile
* I.openNewTab({ isMobile: true });
* ```
*/
async openNewTab(options) {
await this._setPage(await this.browserContext.newPage(options));
return this._waitForAction();
}
/**
* {{> grabNumberOfOpenTabs }}
*/
async grabNumberOfOpenTabs() {
const pages = await this.browserContext.pages();
return pages.length;
}
/**
* {{> seeElement }}
*
*/
async seeElement(locator) {
let els = await this._locate(locator);
els = await Promise.all(els.map(el => el.boundingBox()));
return empty('visible elements').negate(els.filter(v => v).fill('ELEMENT'));
}
/**
* {{> dontSeeElement }}
*
*/
async dontSeeElement(locator) {