codeceptjs 2.4.3 → 2.6.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (76) hide show
  1. package/CHANGELOG.md +117 -0
  2. package/README.md +32 -7
  3. package/bin/codecept.js +3 -0
  4. package/docs/basics.md +11 -5
  5. package/docs/bdd.md +4 -4
  6. package/docs/build/MockRequest.js +3 -0
  7. package/docs/build/Nightmare.js +10 -2
  8. package/docs/build/Playwright.js +3187 -0
  9. package/docs/build/Protractor.js +16 -2
  10. package/docs/build/Puppeteer.js +126 -19
  11. package/docs/build/REST.js +3 -1
  12. package/docs/build/TestCafe.js +11 -3
  13. package/docs/build/WebDriver.js +361 -28
  14. package/docs/changelog.md +116 -0
  15. package/docs/configuration.md +2 -2
  16. package/docs/custom-helpers.md +55 -10
  17. package/docs/helpers/Appium.md +81 -1
  18. package/docs/helpers/MockRequest.md +281 -38
  19. package/docs/helpers/Nightmare.md +10 -2
  20. package/docs/helpers/Playwright.md +1770 -0
  21. package/docs/helpers/Protractor.md +15 -3
  22. package/docs/helpers/Puppeteer-firefox.md +32 -1
  23. package/docs/helpers/Puppeteer.md +126 -76
  24. package/docs/helpers/TestCafe.md +10 -2
  25. package/docs/helpers/WebDriver.md +208 -118
  26. package/docs/locators.md +2 -0
  27. package/docs/playwright.md +306 -0
  28. package/docs/plugins.md +103 -0
  29. package/docs/reports.md +12 -0
  30. package/docs/shadow.md +68 -0
  31. package/docs/visual.md +0 -73
  32. package/docs/webapi/forceClick.mustache +27 -0
  33. package/docs/webapi/seeInPopup.mustache +7 -0
  34. package/docs/webapi/setCookie.mustache +10 -2
  35. package/docs/webapi/type.mustache +12 -0
  36. package/docs/webdriver.md +7 -3
  37. package/lib/codecept.js +1 -1
  38. package/lib/command/definitions.js +2 -2
  39. package/lib/command/generate.js +4 -4
  40. package/lib/command/gherkin/snippets.js +4 -4
  41. package/lib/command/init.js +1 -1
  42. package/lib/command/interactive.js +3 -0
  43. package/lib/command/run-multiple.js +2 -2
  44. package/lib/command/run-rerun.js +2 -0
  45. package/lib/command/run-workers.js +22 -8
  46. package/lib/command/run.js +2 -0
  47. package/lib/command/workers/runTests.js +1 -0
  48. package/lib/container.js +1 -1
  49. package/lib/event.js +2 -0
  50. package/lib/helper/MockRequest.js +3 -0
  51. package/lib/helper/Playwright.js +2422 -0
  52. package/lib/helper/Protractor.js +1 -2
  53. package/lib/helper/Puppeteer.js +84 -19
  54. package/lib/helper/REST.js +3 -1
  55. package/lib/helper/TestCafe.js +1 -1
  56. package/lib/helper/WebDriver.js +313 -26
  57. package/lib/helper/extras/PlaywrightPropEngine.js +53 -0
  58. package/lib/helper/scripts/isElementClickable.js +54 -14
  59. package/lib/interfaces/gherkin.js +1 -1
  60. package/lib/listener/helpers.js +3 -0
  61. package/lib/locator.js +5 -0
  62. package/lib/mochaFactory.js +12 -10
  63. package/lib/plugin/allure.js +8 -1
  64. package/lib/plugin/autoDelay.js +1 -8
  65. package/lib/plugin/commentStep.js +133 -0
  66. package/lib/plugin/screenshotOnFail.js +3 -10
  67. package/lib/plugin/selenoid.js +2 -2
  68. package/lib/plugin/standardActingHelpers.js +13 -0
  69. package/lib/plugin/stepByStepReport.js +1 -8
  70. package/lib/plugin/wdio.js +10 -1
  71. package/lib/reporter/cli.js +30 -1
  72. package/lib/session.js +7 -4
  73. package/package.json +13 -10
  74. package/typings/Mocha.d.ts +567 -16
  75. package/typings/index.d.ts +9 -5
  76. package/typings/types.d.ts +1634 -74
@@ -0,0 +1,3187 @@
1
+ const requireg = require('requireg');
2
+ const path = require('path');
3
+ const fs = require('fs');
4
+ const fsExtra = require('fs-extra');
5
+
6
+ const Helper = require('../helper');
7
+ const Locator = require('../locator');
8
+ const recorder = require('../recorder');
9
+ const stringIncludes = require('../assert/include').includes;
10
+ const { urlEquals } = require('../assert/equal');
11
+ const { equals } = require('../assert/equal');
12
+ const { empty } = require('../assert/empty');
13
+ const { truth } = require('../assert/truth');
14
+ const isElementClickable = require('./scripts/isElementClickable');
15
+ const {
16
+ xpathLocator,
17
+ ucfirst,
18
+ fileExists,
19
+ chunkArray,
20
+ toCamelCase,
21
+ convertCssPropertiesToCamelCase,
22
+ screenshotOutputFolder,
23
+ getNormalizedKeyAttributeValue,
24
+ isModifierKey,
25
+ } = require('../utils');
26
+ const {
27
+ isColorProperty,
28
+ convertColorToRGBA,
29
+ } = require('../colorUtils');
30
+ const ElementNotFound = require('./errors/ElementNotFound');
31
+ const RemoteBrowserConnectionRefused = require('./errors/RemoteBrowserConnectionRefused');
32
+ const Popup = require('./extras/Popup');
33
+ const Console = require('./extras/Console');
34
+
35
+ let playwright;
36
+ let perfTiming;
37
+ let defaultSelectorEnginesInitialized = false;
38
+
39
+ const popupStore = new Popup();
40
+ const consoleLogStore = new Console();
41
+ const availableBrowsers = ['chromium', 'webkit', 'firefox'];
42
+
43
+ const { createValueEngine, createDisabledEngine } = require('./extras/PlaywrightPropEngine');
44
+ /**
45
+ * Uses [Playwright](https://github.com/microsoft/playwright) library to run tests inside:
46
+ *
47
+ * * Chromium
48
+ * * Firefox
49
+ * * Webkit (Safari)
50
+ *
51
+ * This helper works with a browser out of the box with no additional tools required to install.
52
+ *
53
+ * Requires `playwright` package version ^0.12.1 to be installed:
54
+ *
55
+ * ```
56
+ * npm i playwright@^0.12.1 --save
57
+ * ```
58
+ *
59
+ * ## Configuration
60
+ *
61
+ * This helper should be configured in codecept.json or codecept.conf.js
62
+ *
63
+ * * `url`: base url of website to be tested
64
+ * * `browser`: a browser to test on, either: `chromium`, `firefox`, `webkit`. Default: chromium.
65
+ * * `show`: (optional, default: false) - show browser window.
66
+ * * `restart`: (optional, default: true) - restart browser between tests.
67
+ * * `disableScreenshots`: (optional, default: false) - don't save screenshot on failure.
68
+ * * `emulate`: (optional, default: {}) launch browser in device emulation mode.
69
+ * * `fullPageScreenshots` (optional, default: false) - make full page screenshots on failure.
70
+ * * `uniqueScreenshotNames`: (optional, default: false) - option to prevent screenshot override if you have scenarios with the same name in different suites.
71
+ * * `keepBrowserState`: (optional, default: false) - keep browser state between tests when `restart` is set to false.
72
+ * * `keepCookies`: (optional, default: false) - keep cookies between tests when `restart` is set to false.
73
+ * * `waitForAction`: (optional) how long to wait after click, doubleClick or PressKey actions in ms. Default: 100.
74
+ * * `waitForNavigation`: (optional, default: 'load'). When to consider navigation succeeded. Possible options: `load`, `domcontentloaded`, `networkidle0`, `networkidle2`. Choose one of those options is possible. See [Playwright API](https://github.com/microsoft/playwright/blob/master/docs/api.md#pagewaitfornavigationoptions).
75
+ * * `pressKeyDelay`: (optional, default: '10'). Delay between key presses in ms. Used when calling Playwrights page.type(...) in fillField/appendField
76
+ * * `getPageTimeout` (optional, default: '0') config option to set maximum navigation time in milliseconds.
77
+ * * `waitForTimeout`: (optional) default wait* timeout in ms. Default: 1000.
78
+ * * `basicAuth`: (optional) the basic authentication to pass to base url. Example: {username: 'username', password: 'password'}
79
+ * * `windowSize`: (optional) default window size. Set a dimension like `640x480`.
80
+ * * `userAgent`: (optional) user-agent string.
81
+ * * `manualStart`: (optional, default: false) - do not start browser before a test, start it manually inside a helper with `this.helpers["Playwright"]._startBrowser()`.
82
+ * * `chromium`: (optional) pass additional chromium options
83
+ *
84
+ * #### Example #1: Wait for 0 network connections.
85
+ *
86
+ * ```js
87
+ * {
88
+ * helpers: {
89
+ * Playwright : {
90
+ * url: "http://localhost",
91
+ * restart: false,
92
+ * waitForNavigation: "networkidle0",
93
+ * waitForAction: 500
94
+ * }
95
+ * }
96
+ * }
97
+ * ```
98
+ *
99
+ * #### Example #2: Wait for DOMContentLoaded event
100
+ *
101
+ * ```js
102
+ * {
103
+ * helpers: {
104
+ * Playwright : {
105
+ * url: "http://localhost",
106
+ * restart: false,
107
+ * waitForNavigation: "domcontentloaded",
108
+ * waitForAction: 500
109
+ * }
110
+ * }
111
+ * }
112
+ * ```
113
+ *
114
+ * #### Example #3: Debug in window mode
115
+ *
116
+ * ```js
117
+ * {
118
+ * helpers: {
119
+ * Playwright : {
120
+ * url: "http://localhost",
121
+ * show: true
122
+ * }
123
+ * }
124
+ * }
125
+ * ```
126
+ *
127
+ * #### Example #4: Connect to remote browser by specifying [websocket endpoint](https://chromedevtools.github.io/devtools-protocol/#how-do-i-access-the-browser-target)
128
+ *
129
+ * ```js
130
+ * {
131
+ * helpers: {
132
+ * Playwright: {
133
+ * url: "http://localhost",
134
+ * chromium: {
135
+ * browserWSEndpoint: "ws://localhost:9222/devtools/browser/c5aa6160-b5bc-4d53-bb49-6ecb36cd2e0a"
136
+ * }
137
+ * }
138
+ * }
139
+ * }
140
+ * ```
141
+ *
142
+ * #### Example #5: Testing with Chromium extensions
143
+ *
144
+ * [official docs](https://github.com/microsoft/playwright/blob/v0.11.0/docs/api.md#working-with-chrome-extensions)
145
+ *
146
+ * ```js
147
+ * {
148
+ * helpers: {
149
+ * Playwright: {
150
+ * url: "http://localhost",
151
+ * show: true // headless mode not supported for extensions
152
+ * chromium: {
153
+ * args: [
154
+ * `--disable-extensions-except=${pathToExtension}`,
155
+ * `--load-extension=${pathToExtension}`
156
+ * ]
157
+ * }
158
+ * }
159
+ * }
160
+ * }
161
+ * ```
162
+ *
163
+ * #### Example #6: Lunach tests emulating iPhone 6
164
+ *
165
+ *
166
+ *
167
+ * ```js
168
+ * const { devices } = require('playwright');
169
+ *
170
+ * {
171
+ * helpers: {
172
+ * Playwright: {
173
+ * url: "http://localhost",
174
+ * emulate: devices['iPhone 6'],
175
+ * }
176
+ * }
177
+ * }
178
+ * ```
179
+ *
180
+ * Note: When connecting to remote browser `show` and specific `chrome` options (e.g. `headless` or `devtools`) are ignored.
181
+ *
182
+ * ## Access From Helpers
183
+ *
184
+ * Receive Playwright client from a custom helper by accessing `browser` for the Browser object or `page` for the current Page object:
185
+ *
186
+ * ```js
187
+ * const { browser } = this.helpers.Playwright;
188
+ * await browser.pages(); // List of pages in the browser
189
+ *
190
+ * // get current page
191
+ * const { page } = this.helpers.Playwright;
192
+ * await page.url(); // Get the url of the current page
193
+ *
194
+ * const { browserContext } = this.helpers.Playwright;
195
+ * await browserContext.cookies(); // get current browser context
196
+ * ```
197
+ *
198
+ * ## Methods
199
+ */
200
+ class Playwright extends Helper {
201
+ constructor(config) {
202
+ super(config);
203
+
204
+ playwright = require('playwright');
205
+
206
+ // set defaults
207
+ this.isRemoteBrowser = false;
208
+ this.isRunning = false;
209
+ this.isAuthenticated = false;
210
+ this.sessionPages = {};
211
+ this.activeSessionName = '';
212
+
213
+ // override defaults with config
214
+ this._setConfig(config);
215
+ }
216
+
217
+ _validateConfig(config) {
218
+ const defaults = {
219
+ // options to emulate context
220
+ emulate: {},
221
+
222
+ browser: 'chromium',
223
+ waitForAction: 100,
224
+ waitForTimeout: 1000,
225
+ pressKeyDelay: 10,
226
+ fullPageScreenshots: false,
227
+ disableScreenshots: false,
228
+ uniqueScreenshotNames: false,
229
+ manualStart: false,
230
+ getPageTimeout: 0,
231
+ waitForNavigation: 'load',
232
+ restart: false,
233
+ keepCookies: false,
234
+ keepBrowserState: false,
235
+ show: false,
236
+ defaultPopupAction: 'accept',
237
+ };
238
+
239
+ config = Object.assign(defaults, config);
240
+
241
+ if (availableBrowsers.indexOf(config.browser) < 0) {
242
+ throw new Error(`Invalid config. Can't use browser "${config.browser}". Accepted values: ${availableBrowsers.join(', ')}`);
243
+ }
244
+
245
+ return config;
246
+ }
247
+
248
+ _getOptionsForBrowser(config) {
249
+ return config[config.browser] || {};
250
+ }
251
+
252
+ _setConfig(config) {
253
+ this.options = this._validateConfig(config);
254
+ this.playwrightOptions = {
255
+ headless: !this.options.show,
256
+ ...this._getOptionsForBrowser(config),
257
+ };
258
+ this.isRemoteBrowser = !!this.playwrightOptions.browserWSEndpoint;
259
+ popupStore.defaultAction = this.options.defaultPopupAction;
260
+ }
261
+
262
+ static _config() {
263
+ return [
264
+ { name: 'url', message: 'Base url of site to be tested', default: 'http://localhost' },
265
+ {
266
+ name: 'show', message: 'Show browser window', default: true, type: 'confirm',
267
+ },
268
+ {
269
+ name: 'browser',
270
+ message: 'Browser in which testing will be performed. Possible options: chromium, firefox or webkit',
271
+ default: 'chromium',
272
+ },
273
+ ];
274
+ }
275
+
276
+ static _checkRequirements() {
277
+ try {
278
+ requireg('playwright');
279
+ } catch (e) {
280
+ return ['playwright@^0.12.1'];
281
+ }
282
+ }
283
+
284
+ async _init() {
285
+ // register an internal selector engine for reading value property of elements in a selector
286
+ if (defaultSelectorEnginesInitialized) return;
287
+ defaultSelectorEnginesInitialized = true;
288
+ try {
289
+ await playwright.selectors.register('__value', createValueEngine);
290
+ await playwright.selectors.register('__disabled', createDisabledEngine);
291
+ } catch (e) {
292
+ console.warn(e);
293
+ }
294
+ }
295
+
296
+ _beforeSuite() {
297
+ if (!this.options.restart && !this.options.manualStart && !this.isRunning) {
298
+ this.debugSection('Session', 'Starting singleton browser session');
299
+ return this._startBrowser();
300
+ }
301
+ }
302
+
303
+
304
+ async _before() {
305
+ recorder.retry({
306
+ retries: 5,
307
+ when: err => err.message.indexOf('context') > -1, // ignore context errors
308
+ });
309
+ if (this.options.restart && !this.options.manualStart) return this._startBrowser();
310
+ if (!this.isRunning && !this.options.manualStart) return this._startBrowser();
311
+ return this.browser;
312
+ }
313
+
314
+ async _after() {
315
+ if (!this.isRunning) return;
316
+
317
+ // close other sessions
318
+ const contexts = await this.browser.contexts();
319
+ contexts.shift();
320
+
321
+ await Promise.all(contexts.map(c => c.close()));
322
+
323
+ if (this.options.restart) {
324
+ this.isRunning = false;
325
+ return this._stopBrowser();
326
+ }
327
+
328
+ // ensure current page is in default context
329
+ if (this.page) {
330
+ const existingPages = await this.browserContext.pages();
331
+ await this._setPage(existingPages[0]);
332
+ }
333
+
334
+ if (this.options.keepBrowserState) return;
335
+
336
+ if (!this.options.keepCookies) {
337
+ this.debugSection('Session', 'cleaning cookies and localStorage');
338
+ await this.clearCookie();
339
+ }
340
+ const currentUrl = await this.grabCurrentUrl();
341
+
342
+ if (currentUrl.startsWith('http')) {
343
+ await this.executeScript('localStorage.clear();').catch((err) => {
344
+ if (!(err.message.indexOf("Storage is disabled inside 'data:' URLs.") > -1)) throw err;
345
+ });
346
+ }
347
+ // await this.closeOtherTabs();
348
+ return this.browser;
349
+ }
350
+
351
+ _afterSuite() {
352
+ }
353
+
354
+ _finishTest() {
355
+ if (!this.options.restart && this.isRunning) return this._stopBrowser();
356
+ }
357
+
358
+ _session() {
359
+ const defaultContext = this.browserContext;
360
+ return {
361
+ start: async (sessionName = '', config) => {
362
+ this.debugSection('New Context', config ? JSON.stringify(config) : 'opened');
363
+ this.activeSessionName = sessionName;
364
+
365
+ const bc = await this.browser.newContext(config);
366
+ const page = await bc.newPage();
367
+ targetCreatedHandler.call(this, page);
368
+ this._setPage(page);
369
+ // Create a new page inside context.
370
+ return bc;
371
+ },
372
+ stop: async (context) => {
373
+ // is closed by _after
374
+ },
375
+ loadVars: async (context) => {
376
+ this.browserContext = context;
377
+ const existingPages = await context.pages();
378
+ this.sessionPages[this.activeSessionName] = existingPages[0];
379
+ return this._setPage(this.sessionPages[this.activeSessionName]);
380
+ },
381
+ restoreVars: async (session) => {
382
+ this.withinLocator = null;
383
+ this.browserContext = defaultContext;
384
+
385
+ if (!session) {
386
+ this.activeSessionName = '';
387
+ } else {
388
+ this.activeSessionName = session;
389
+ }
390
+ const existingPages = await this.browserContext.pages();
391
+ await this._setPage(existingPages[0]);
392
+
393
+ return this._waitForAction();
394
+ },
395
+ };
396
+ }
397
+
398
+
399
+ /**
400
+ * Set the automatic popup response to Accept.
401
+ * This must be set before a popup is triggered.
402
+ *
403
+ * ```js
404
+ * I.amAcceptingPopups();
405
+ * I.click('#triggerPopup');
406
+ * I.acceptPopup();
407
+ * ```
408
+ */
409
+ amAcceptingPopups() {
410
+ popupStore.actionType = 'accept';
411
+ }
412
+
413
+ /**
414
+ * Accepts the active JavaScript native popup window, as created by window.alert|window.confirm|window.prompt.
415
+ * Don't confuse popups with modal windows, as created by [various
416
+ * libraries](http://jster.net/category/windows-modals-popups).
417
+ */
418
+ acceptPopup() {
419
+ popupStore.assertPopupActionType('accept');
420
+ }
421
+
422
+ /**
423
+ * Set the automatic popup response to Cancel/Dismiss.
424
+ * This must be set before a popup is triggered.
425
+ *
426
+ * ```js
427
+ * I.amCancellingPopups();
428
+ * I.click('#triggerPopup');
429
+ * I.cancelPopup();
430
+ * ```
431
+ */
432
+ amCancellingPopups() {
433
+ popupStore.actionType = 'cancel';
434
+ }
435
+
436
+ /**
437
+ * Dismisses the active JavaScript popup, as created by window.alert|window.confirm|window.prompt.
438
+ */
439
+ cancelPopup() {
440
+ popupStore.assertPopupActionType('cancel');
441
+ }
442
+
443
+ /**
444
+ * Checks that the active JavaScript popup, as created by `window.alert|window.confirm|window.prompt`, contains the
445
+ * given string.
446
+ *
447
+ * ```js
448
+ * I.seeInPopup('Popup text');
449
+ * ```
450
+ * @param {string} text value to check.
451
+ *
452
+ */
453
+ async seeInPopup(text) {
454
+ popupStore.assertPopupVisible();
455
+ const popupText = await popupStore.popup.message();
456
+ stringIncludes('text in popup').assert(text, popupText);
457
+ }
458
+
459
+ /**
460
+ * Set current page
461
+ * @param {object} page page to set
462
+ */
463
+ async _setPage(page) {
464
+ page = await page;
465
+ this._addPopupListener(page);
466
+ this.page = page;
467
+ if (!page) return;
468
+ page.setDefaultNavigationTimeout(this.options.getPageTimeout);
469
+ this.context = await this.page.$('body');
470
+ if (this.config.browser === 'chrome') {
471
+ await page.bringToFront();
472
+ }
473
+ }
474
+
475
+ /**
476
+ * Add the 'dialog' event listener to a page
477
+ * @page {playwright.Page}
478
+ *
479
+ * The popup listener handles the dialog with the predefined action when it appears on the page.
480
+ * It also saves a reference to the object which is used in seeInPopup.
481
+ */
482
+ _addPopupListener(page) {
483
+ if (!page) {
484
+ return;
485
+ }
486
+ page.on('dialog', async (dialog) => {
487
+ popupStore.popup = dialog;
488
+ const action = popupStore.actionType || this.options.defaultPopupAction;
489
+ await this._waitForAction();
490
+
491
+ switch (action) {
492
+ case 'accept':
493
+ return dialog.accept();
494
+
495
+ case 'cancel':
496
+ return dialog.dismiss();
497
+
498
+ default: {
499
+ throw new Error('Unknown popup action type. Only "accept" or "cancel" are accepted');
500
+ }
501
+ }
502
+ });
503
+ }
504
+
505
+ /**
506
+ * Gets page URL including hash.
507
+ */
508
+ async _getPageUrl() {
509
+ return this.executeScript(() => window.location.href);
510
+ }
511
+
512
+ /**
513
+ * Grab the text within the popup. If no popup is visible then it will return null
514
+ *
515
+ * ```js
516
+ * await I.grabPopupText();
517
+ * ```
518
+ * @return {Promise<string | null>}
519
+ */
520
+ async grabPopupText() {
521
+ if (popupStore.popup) {
522
+ return popupStore.popup.message();
523
+ }
524
+ return null;
525
+ }
526
+
527
+ async _startBrowser() {
528
+ if (this.isRemoteBrowser) {
529
+ try {
530
+ this.browser = await playwright[this.options.browser].connect(this.playwrightOptions);
531
+ } catch (err) {
532
+ if (err.toString().indexOf('ECONNREFUSED')) {
533
+ throw new RemoteBrowserConnectionRefused(err);
534
+ }
535
+ throw err;
536
+ }
537
+ } else {
538
+ this.browser = await playwright[this.options.browser].launch(this.playwrightOptions);
539
+ }
540
+
541
+ // works only for Chromium
542
+ this.browser.on('targetchanged', (target) => {
543
+ this.debugSection('Url', target.url());
544
+ });
545
+ this.browserContext = await this.browser.newContext({ acceptDownloads: true, ...this.options.emulate });
546
+
547
+ const existingPages = await this.browserContext.pages();
548
+
549
+ const mainPage = existingPages[0] || await this.browserContext.newPage();
550
+ targetCreatedHandler.call(this, mainPage);
551
+
552
+ await this._setPage(mainPage);
553
+ await this.closeOtherTabs();
554
+
555
+ this.isRunning = true;
556
+ }
557
+
558
+ async _stopBrowser() {
559
+ this.withinLocator = null;
560
+ this._setPage(null);
561
+ this.context = null;
562
+ popupStore.clear();
563
+
564
+ if (this.isRemoteBrowser) {
565
+ await this.browser.disconnect();
566
+ } else {
567
+ await this.browser.close();
568
+ }
569
+ }
570
+
571
+ async _evaluateHandeInContext(...args) {
572
+ const context = await this._getContext();
573
+ return context.evaluateHandle(...args);
574
+ }
575
+
576
+
577
+ async _withinBegin(locator) {
578
+ if (this.withinLocator) {
579
+ throw new Error('Can\'t start within block inside another within block');
580
+ }
581
+
582
+ const frame = isFrameLocator(locator);
583
+
584
+ if (frame) {
585
+ if (Array.isArray(frame)) {
586
+ await this.switchTo(null);
587
+ return frame.reduce((p, frameLocator) => p.then(() => this.switchTo(frameLocator)), Promise.resolve());
588
+ }
589
+ await this.switchTo(locator);
590
+ this.withinLocator = new Locator(locator);
591
+ return;
592
+ }
593
+
594
+ const els = await this._locate(locator);
595
+ assertElementExists(els, locator);
596
+ this.context = els[0];
597
+
598
+ this.withinLocator = new Locator(locator);
599
+ }
600
+
601
+ async _withinEnd() {
602
+ this.withinLocator = null;
603
+ this.context = await this.page.mainFrame().$('body');
604
+ }
605
+
606
+ _extractDataFromPerformanceTiming(timing, ...dataNames) {
607
+ const navigationStart = timing.navigationStart;
608
+
609
+ const extractedData = {};
610
+ dataNames.forEach((name) => {
611
+ extractedData[name] = timing[name] - navigationStart;
612
+ });
613
+
614
+ return extractedData;
615
+ }
616
+
617
+ /**
618
+ * Opens a web page in a browser. Requires relative or absolute url.
619
+ * If url starts with `/`, opens a web page of a site defined in `url` config parameter.
620
+ *
621
+ * ```js
622
+ * I.amOnPage('/'); // opens main page of website
623
+ * I.amOnPage('https://github.com'); // opens github
624
+ * I.amOnPage('/login'); // opens a login page
625
+ * ```
626
+ *
627
+ * @param {string} url url path or global url.
628
+ */
629
+ async amOnPage(url) {
630
+ if (!(/^\w+\:\/\//.test(url))) {
631
+ url = this.options.url + url;
632
+ }
633
+
634
+ if (this.config.basicAuth && (this.isAuthenticated !== true)) {
635
+ if (url.includes(this.options.url)) {
636
+ await this.browserContext.setHTTPCredentials(this.config.basicAuth);
637
+ this.isAuthenticated = true;
638
+ }
639
+ }
640
+
641
+ await this.page.goto(url, { waitUntil: this.options.waitForNavigation });
642
+
643
+ const performanceTiming = JSON.parse(await this.page.evaluate(() => JSON.stringify(window.performance.timing)));
644
+
645
+ perfTiming = this._extractDataFromPerformanceTiming(
646
+ performanceTiming,
647
+ 'responseEnd',
648
+ 'domInteractive',
649
+ 'domContentLoadedEventEnd',
650
+ 'loadEventEnd',
651
+ );
652
+
653
+ return this._waitForAction();
654
+ }
655
+
656
+ /**
657
+ * Resize the current window to provided width and height.
658
+ * First parameter can be set to `maximize`.
659
+ *
660
+ * @param {number} width width in pixels or `maximize`.
661
+ * @param {number} height height in pixels.
662
+ *
663
+ * Unlike other drivers Playwright changes the size of a viewport, not the window!
664
+ * Playwright does not control the window of a browser so it can't adjust its real size.
665
+ * It also can't maximize a window.
666
+ *
667
+ * Update configuration to change real window size on start:
668
+ *
669
+ * ```js
670
+ * // inside codecept.conf.js
671
+ * // @codeceptjs/configure package must be installed
672
+ * { setWindowSize } = require('@codeceptjs/configure');
673
+ * ````
674
+ */
675
+ async resizeWindow(width, height) {
676
+ if (width === 'maximize') {
677
+ throw new Error('Playwright can\'t control windows, so it can\'t maximize it');
678
+ }
679
+
680
+ await this.page.setViewportSize({ width, height });
681
+ return this._waitForAction();
682
+ }
683
+
684
+ /**
685
+ * Set headers for all next requests
686
+ *
687
+ * ```js
688
+ * I.haveRequestHeaders({
689
+ * 'X-Sent-By': 'CodeceptJS',
690
+ * });
691
+ * ```
692
+ *
693
+ * @param {object} customHeaders headers to set
694
+ */
695
+ async haveRequestHeaders(customHeaders) {
696
+ if (!customHeaders) {
697
+ throw new Error('Cannot send empty headers.');
698
+ }
699
+ return this.page.setExtraHTTPHeaders(customHeaders);
700
+ }
701
+
702
+ /**
703
+ * Moves cursor to element matched by locator.
704
+ * Extra shift can be set with offsetX and offsetY options.
705
+ *
706
+ * ```js
707
+ * I.moveCursorTo('.tooltip');
708
+ * I.moveCursorTo('#submit', 5,5);
709
+ * ```
710
+ *
711
+ * @param {CodeceptJS.LocatorOrString} locator located by CSS|XPath|strict locator.
712
+ * @param {number} [offsetX=0] (optional, `0` by default) X-axis offset.
713
+ * @param {number} [offsetY=0] (optional, `0` by default) Y-axis offset.
714
+ *
715
+ *
716
+ */
717
+ async moveCursorTo(locator, offsetX = 0, offsetY = 0) {
718
+ const els = await this._locate(locator);
719
+ assertElementExists(els);
720
+
721
+ // Use manual mouse.move instead of .hover() so the offset can be added to the coordinates
722
+ const { x, y } = await els[0]._clickablePoint();
723
+ await this.page.mouse.move(x + offsetX, y + offsetY);
724
+ return this._waitForAction();
725
+ }
726
+
727
+ /**
728
+ * Drag an item to a destination element.
729
+ *
730
+ * ```js
731
+ * I.dragAndDrop('#dragHandle', '#container');
732
+ * ```
733
+ *
734
+ * @param {string|object} srcElement located by CSS|XPath|strict locator.
735
+ * @param {string|object} destElement located by CSS|XPath|strict locator.
736
+ */
737
+ async dragAndDrop(srcElement, destElement) {
738
+ return proceedDragAndDrop.call(this, srcElement, destElement);
739
+ }
740
+
741
+ /**
742
+ * Reload the current page.
743
+ *
744
+ * ```js
745
+ * I.refreshPage();
746
+ * ```
747
+ *
748
+ */
749
+ async refreshPage() {
750
+ return this.page.reload({ timeout: this.options.getPageTimeout, waitUntil: this.options.waitForNavigation });
751
+ }
752
+
753
+ /**
754
+ * Scroll page to the top.
755
+ *
756
+ * ```js
757
+ * I.scrollPageToTop();
758
+ * ```
759
+ *
760
+ */
761
+ scrollPageToTop() {
762
+ return this.executeScript(() => {
763
+ window.scrollTo(0, 0);
764
+ });
765
+ }
766
+
767
+ /**
768
+ * Scroll page to the bottom.
769
+ *
770
+ * ```js
771
+ * I.scrollPageToBottom();
772
+ * ```
773
+ *
774
+ */
775
+ scrollPageToBottom() {
776
+ return this.executeScript(() => {
777
+ const body = document.body;
778
+ const html = document.documentElement;
779
+ window.scrollTo(0, Math.max(
780
+ body.scrollHeight, body.offsetHeight,
781
+ html.clientHeight, html.scrollHeight, html.offsetHeight,
782
+ ));
783
+ });
784
+ }
785
+
786
+ /**
787
+ * Scrolls to element matched by locator.
788
+ * Extra shift can be set with offsetX and offsetY options.
789
+ *
790
+ * ```js
791
+ * I.scrollTo('footer');
792
+ * I.scrollTo('#submit', 5, 5);
793
+ * ```
794
+ *
795
+ * @param {CodeceptJS.LocatorOrString} locator located by CSS|XPath|strict locator.
796
+ * @param {number} [offsetX=0] (optional, `0` by default) X-axis offset.
797
+ * @param {number} [offsetY=0] (optional, `0` by default) Y-axis offset.
798
+ */
799
+ async scrollTo(locator, offsetX = 0, offsetY = 0) {
800
+ if (typeof locator === 'number' && typeof offsetX === 'number') {
801
+ offsetY = offsetX;
802
+ offsetX = locator;
803
+ locator = null;
804
+ }
805
+
806
+ if (locator) {
807
+ const els = await this._locate(locator);
808
+ assertElementExists(els, locator, 'Element');
809
+ await els[0].scrollIntoViewIfNeeded();
810
+ const elementCoordinates = await els[0]._clickablePoint();
811
+ await this.executeScript((offsetX, offsetY) => window.scrollBy(offsetX, offsetY), { offsetX: elementCoordinates.x + offsetX, offsetY: elementCoordinates.y + offsetY });
812
+ } else {
813
+ await this.executeScript(({ offsetX, offsetY }) => window.scrollTo(offsetX, offsetY), { offsetX, offsetY });
814
+ }
815
+ return this._waitForAction();
816
+ }
817
+
818
+ /**
819
+ * Checks that title contains text.
820
+ *
821
+ * ```js
822
+ * I.seeInTitle('Home Page');
823
+ * ```
824
+ *
825
+ * @param {string} text text value to check.
826
+ */
827
+ async seeInTitle(text) {
828
+ const title = await this.page.title();
829
+ stringIncludes('web page title').assert(text, title);
830
+ }
831
+
832
+ /**
833
+ * Retrieves a page scroll position and returns it to test.
834
+ * Resumes test execution, so **should be used inside an async function with `await`** operator.
835
+ *
836
+ * ```js
837
+ * let { x, y } = await I.grabPageScrollPosition();
838
+ * ```
839
+ *
840
+ * @returns {Promise<Object<string, *>>} scroll position
841
+ */
842
+ async grabPageScrollPosition() {
843
+ /* eslint-disable comma-dangle */
844
+ function getScrollPosition() {
845
+ return {
846
+ x: window.pageXOffset,
847
+ y: window.pageYOffset
848
+ };
849
+ }
850
+ /* eslint-enable comma-dangle */
851
+ return this.executeScript(getScrollPosition);
852
+ }
853
+
854
+ /**
855
+ * Checks that title is equal to provided one.
856
+ *
857
+ * ```js
858
+ * I.seeTitleEquals('Test title.');
859
+ * ```
860
+ */
861
+ async seeTitleEquals(text) {
862
+ const title = await this.page.title();
863
+ return equals('web page title').assert(title, text);
864
+ }
865
+
866
+ /**
867
+ * Checks that title does not contain text.
868
+ *
869
+ * ```js
870
+ * I.dontSeeInTitle('Error');
871
+ * ```
872
+ *
873
+ * @param {string} text value to check.
874
+ */
875
+ async dontSeeInTitle(text) {
876
+ const title = await this.page.title();
877
+ stringIncludes('web page title').negate(text, title);
878
+ }
879
+
880
+ /**
881
+ * Retrieves a page title and returns it to test.
882
+ * Resumes test execution, so **should be used inside async with `await`** operator.
883
+ *
884
+ * ```js
885
+ * let title = await I.grabTitle();
886
+ * ```
887
+ *
888
+ * @returns {Promise<string>} title
889
+ */
890
+ async grabTitle() {
891
+ return this.page.title();
892
+ }
893
+
894
+ /**
895
+ * Get elements by different locator types, including strict locator
896
+ * Should be used in custom helpers:
897
+ *
898
+ * ```js
899
+ * const elements = await this.helpers['Playwright']._locate({name: 'password'});
900
+ * ```
901
+ *
902
+ *
903
+ */
904
+ async _locate(locator) {
905
+ return findElements(await this.context, locator);
906
+ }
907
+
908
+ /**
909
+ * Find a checkbox by providing human readable text:
910
+ * NOTE: Assumes the checkable element exists
911
+ *
912
+ * ```js
913
+ * this.helpers['Playwright']._locateCheckable('I agree with terms and conditions').then // ...
914
+ * ```
915
+ */
916
+ async _locateCheckable(locator, providedContext = null) {
917
+ const context = providedContext || await this._getContext();
918
+ const els = await findCheckable.call(this, locator, context);
919
+ assertElementExists(els[0], locator, 'Checkbox or radio');
920
+ return els[0];
921
+ }
922
+
923
+ /**
924
+ * Find a clickable element by providing human readable text:
925
+ *
926
+ * ```js
927
+ * this.helpers['Playwright']._locateClickable('Next page').then // ...
928
+ * ```
929
+ */
930
+ async _locateClickable(locator) {
931
+ const context = await this._getContext();
932
+ return findClickable.call(this, context, locator);
933
+ }
934
+
935
+ /**
936
+ * Find field elements by providing human readable text:
937
+ *
938
+ * ```js
939
+ * this.helpers['Playwright']._locateFields('Your email').then // ...
940
+ * ```
941
+ */
942
+ async _locateFields(locator) {
943
+ return findFields.call(this, locator);
944
+ }
945
+
946
+ /**
947
+ * Switch focus to a particular tab by its number. It waits tabs loading and then switch tab
948
+ *
949
+ * ```js
950
+ * I.switchToNextTab();
951
+ * I.switchToNextTab(2);
952
+ * ```
953
+ *
954
+ * @param {number} [num=1]
955
+ */
956
+ async switchToNextTab(num = 1) {
957
+ const pages = await this.browserContext.pages();
958
+
959
+ const index = pages.indexOf(this.page);
960
+ this.withinLocator = null;
961
+ const page = pages[index + num];
962
+
963
+ if (!page) {
964
+ throw new Error(`There is no ability to switch to next tab with offset ${num}`);
965
+ }
966
+ await this._setPage(page);
967
+ return this._waitForAction();
968
+ }
969
+
970
+ /**
971
+ * Switch focus to a particular tab by its number. It waits tabs loading and then switch tab
972
+ *
973
+ * ```js
974
+ * I.switchToPreviousTab();
975
+ * I.switchToPreviousTab(2);
976
+ * ```
977
+ * @param {number} [num=1]
978
+ */
979
+ async switchToPreviousTab(num = 1) {
980
+ const pages = await this.browserContext.pages();
981
+ const index = pages.indexOf(this.page);
982
+ this.withinLocator = null;
983
+ const page = pages[index - num];
984
+
985
+ if (!page) {
986
+ throw new Error(`There is no ability to switch to previous tab with offset ${num}`);
987
+ }
988
+
989
+ await this._setPage(page);
990
+ return this._waitForAction();
991
+ }
992
+
993
+ /**
994
+ * Close current tab and switches to previous.
995
+ *
996
+ * ```js
997
+ * I.closeCurrentTab();
998
+ * ```
999
+ */
1000
+ async closeCurrentTab() {
1001
+ const oldPage = this.page;
1002
+ await this.switchToPreviousTab();
1003
+ await oldPage.close();
1004
+ return this._waitForAction();
1005
+ }
1006
+
1007
+ /**
1008
+ * Close all tabs except for the current one.
1009
+ *
1010
+ * ```js
1011
+ * I.closeOtherTabs();
1012
+ * ```
1013
+ */
1014
+ async closeOtherTabs() {
1015
+ const pages = await this.browserContext.pages();
1016
+ const otherPages = pages.filter(page => page !== this.page);
1017
+ if (otherPages.length) {
1018
+ this.debug(`Closing ${otherPages.length} tabs`);
1019
+ return Promise.all(otherPages.map(p => p.close()));
1020
+ }
1021
+ return Promise.resolve();
1022
+ }
1023
+
1024
+ /**
1025
+ * Open new tab and switch to it
1026
+ *
1027
+ * ```js
1028
+ * I.openNewTab();
1029
+ * ```
1030
+ *
1031
+ * You can pass in [page options](https://github.com/microsoft/playwright/blob/v0.12.1/docs/api.md#browsernewpageoptions) to emulate device on this page
1032
+ *
1033
+ * ```js
1034
+ * // enable mobile
1035
+ * I.openNewTab({ isMobile: true });
1036
+ * ```
1037
+ */
1038
+ async openNewTab(options) {
1039
+ await this._setPage(await this.browserContext.newPage(options));
1040
+ return this._waitForAction();
1041
+ }
1042
+
1043
+ /**
1044
+ * Grab number of open tabs.
1045
+ *
1046
+ * ```js
1047
+ * let tabs = await I.grabNumberOfOpenTabs();
1048
+ * ```
1049
+ *
1050
+ * @returns {Promise<number>} number of open tabs
1051
+ */
1052
+ async grabNumberOfOpenTabs() {
1053
+ const pages = await this.browserContext.pages();
1054
+ return pages.length;
1055
+ }
1056
+
1057
+ /**
1058
+ * Checks that a given Element is visible
1059
+ * Element is located by CSS or XPath.
1060
+ *
1061
+ * ```js
1062
+ * I.seeElement('#modal');
1063
+ * ```
1064
+ * @param {CodeceptJS.LocatorOrString} locator located by CSS|XPath|strict locator.
1065
+ *
1066
+ */
1067
+ async seeElement(locator) {
1068
+ let els = await this._locate(locator);
1069
+ els = await Promise.all(els.map(el => el.boundingBox()));
1070
+ return empty('visible elements').negate(els.filter(v => v).fill('ELEMENT'));
1071
+ }
1072
+
1073
+ /**
1074
+ * Opposite to `seeElement`. Checks that element is not visible (or in DOM)
1075
+ *
1076
+ * ```js
1077
+ * I.dontSeeElement('.modal'); // modal is not shown
1078
+ * ```
1079
+ *
1080
+ * @param {CodeceptJS.LocatorOrString} locator located by CSS|XPath|Strict locator.
1081
+ *
1082
+ */
1083
+ async dontSeeElement(locator) {
1084
+ let els = await this._locate(locator);
1085
+ els = await Promise.all(els.map(el => el.boundingBox()));
1086
+ return empty('visible elements').assert(els.filter(v => v).fill('ELEMENT'));
1087
+ }
1088
+
1089
+ /**
1090
+ * Checks that a given Element is present in the DOM
1091
+ * Element is located by CSS or XPath.
1092
+ *
1093
+ * ```js
1094
+ * I.seeElementInDOM('#modal');
1095
+ * ```
1096
+ * @param {CodeceptJS.LocatorOrString} locator element located by CSS|XPath|strict locator.
1097
+ *
1098
+ */
1099
+ async seeElementInDOM(locator) {
1100
+ const els = await this._locate(locator);
1101
+ return empty('elements on page').negate(els.filter(v => v).fill('ELEMENT'));
1102
+ }
1103
+
1104
+ /**
1105
+ * Opposite to `seeElementInDOM`. Checks that element is not on page.
1106
+ *
1107
+ * ```js
1108
+ * I.dontSeeElementInDOM('.nav'); // checks that element is not on page visible or not
1109
+ * ```
1110
+ *
1111
+ * @param {CodeceptJS.LocatorOrString} locator located by CSS|XPath|Strict locator.
1112
+ */
1113
+ async dontSeeElementInDOM(locator) {
1114
+ const els = await this._locate(locator);
1115
+ return empty('elements on a page').assert(els.filter(v => v).fill('ELEMENT'));
1116
+ }
1117
+
1118
+ /**
1119
+ * Handles a file download.Aa file name is required to save the file on disk.
1120
+ * Files are saved to "output" directory.
1121
+ *
1122
+ * Should be used with [FileSystem helper](https://codecept.io/helpers/FileSystem) to check that file were downloaded correctly.
1123
+ *
1124
+ * ```js
1125
+ * I.handleDownloads('downloads/avatar.jpg');
1126
+ * I.click('Download Avatar');
1127
+ * I.amInPath('output/downloads');
1128
+ * I.waitForFile('downloads/avatar.jpg', 5);
1129
+ *
1130
+ * ```
1131
+ *
1132
+ * @param {string} [fileName] set filename for downloaded file
1133
+ */
1134
+ async handleDownloads(fileName = 'downloads') {
1135
+ this.page.waitForEvent('download').then(async (download) => {
1136
+ const filePath = await download.path();
1137
+ const downloadPath = path.join(global.output_dir, fileName || path.basename(filePath));
1138
+ if (!fs.existsSync(path.dirname(downloadPath))) {
1139
+ fs.mkdirSync(path.dirname(downloadPath), '0777');
1140
+ }
1141
+ fs.copyFileSync(filePath, downloadPath);
1142
+ this.debug('Download completed');
1143
+ this.debugSection('Downloaded From', await download.url());
1144
+ this.debugSection('Downloaded To', downloadPath);
1145
+ });
1146
+ }
1147
+
1148
+ /**
1149
+ * Perform a click on a link or a button, given by a locator.
1150
+ * If a fuzzy locator is given, the page will be searched for a button, link, or image matching the locator string.
1151
+ * For buttons, the "value" attribute, "name" attribute, and inner text are searched. For links, the link text is searched.
1152
+ * For images, the "alt" attribute and inner text of any parent links are searched.
1153
+ *
1154
+ * The second parameter is a context (CSS or XPath locator) to narrow the search.
1155
+ *
1156
+ * ```js
1157
+ * // simple link
1158
+ * I.click('Logout');
1159
+ * // button of form
1160
+ * I.click('Submit');
1161
+ * // CSS button
1162
+ * I.click('#form input[type=submit]');
1163
+ * // XPath
1164
+ * I.click('//form/*[@type=submit]');
1165
+ * // link in context
1166
+ * I.click('Logout', '#nav');
1167
+ * // using strict locator
1168
+ * I.click({css: 'nav a.login'});
1169
+ * ```
1170
+ *
1171
+ * @param {CodeceptJS.LocatorOrString} locator clickable link or button located by text, or any element located by CSS|XPath|strict locator.
1172
+ * @param {?CodeceptJS.LocatorOrString} [context=null] (optional, `null` by default) element to search in CSS|XPath|Strict locator.
1173
+ *
1174
+ *
1175
+ *
1176
+ */
1177
+ async click(locator, context = null) {
1178
+ return proceedClick.call(this, locator, context);
1179
+ }
1180
+
1181
+ /**
1182
+ * Clicks link and waits for navigation (deprecated)
1183
+ */
1184
+ async clickLink(locator, context = null) {
1185
+ console.log('clickLink deprecated: Playwright automatically waits for navigation to happen.');
1186
+ console.log('Replace I.clickLink with I.click');
1187
+ return this.click(locator, context);
1188
+ }
1189
+
1190
+ /**
1191
+ *
1192
+ * Force clicks an element without waiting for it to become visible and not animating.
1193
+ *
1194
+ * ```js
1195
+ * I.forceClick('#hiddenButton');
1196
+ * I.forceClick('Click me', '#hidden');
1197
+ * ```
1198
+ *
1199
+ */
1200
+ async forceClick(locator, context = null) {
1201
+ return proceedClick.call(this, locator, context, { force: true });
1202
+ }
1203
+
1204
+
1205
+ /**
1206
+ * Performs a double-click on an element matched by link|button|label|CSS or XPath.
1207
+ * Context can be specified as second parameter to narrow search.
1208
+ *
1209
+ * ```js
1210
+ * I.doubleClick('Edit');
1211
+ * I.doubleClick('Edit', '.actions');
1212
+ * I.doubleClick({css: 'button.accept'});
1213
+ * I.doubleClick('.btn.edit');
1214
+ * ```
1215
+ *
1216
+ * @param {CodeceptJS.LocatorOrString} locator clickable link or button located by text, or any element located by CSS|XPath|strict locator.
1217
+ * @param {?CodeceptJS.LocatorOrString} [context=null] (optional, `null` by default) element to search in CSS|XPath|Strict locator.
1218
+ *
1219
+ *
1220
+ *
1221
+ */
1222
+ async doubleClick(locator, context = null) {
1223
+ return proceedClick.call(this, locator, context, { clickCount: 2 });
1224
+ }
1225
+
1226
+ /**
1227
+ * Performs right click on a clickable element matched by semantic locator, CSS or XPath.
1228
+ *
1229
+ * ```js
1230
+ * // right click element with id el
1231
+ * I.rightClick('#el');
1232
+ * // right click link or button with text "Click me"
1233
+ * I.rightClick('Click me');
1234
+ * // right click button with text "Click me" inside .context
1235
+ * I.rightClick('Click me', '.context');
1236
+ * ```
1237
+ *
1238
+ * @param {CodeceptJS.LocatorOrString} locator clickable element located by CSS|XPath|strict locator.
1239
+ * @param {?CodeceptJS.LocatorOrString} [context=null] (optional, `null` by default) element located by CSS|XPath|strict locator.
1240
+ *
1241
+ *
1242
+ *
1243
+ */
1244
+ async rightClick(locator, context = null) {
1245
+ return proceedClick.call(this, locator, context, { button: 'right' });
1246
+ }
1247
+
1248
+ /**
1249
+ * Selects a checkbox or radio button.
1250
+ * Element is located by label or name or CSS or XPath.
1251
+ *
1252
+ * The second parameter is a context (CSS or XPath locator) to narrow the search.
1253
+ *
1254
+ * ```js
1255
+ * I.checkOption('#agree');
1256
+ * I.checkOption('I Agree to Terms and Conditions');
1257
+ * I.checkOption('agree', '//form');
1258
+ * ```
1259
+ * @param {CodeceptJS.LocatorOrString} field checkbox located by label | name | CSS | XPath | strict locator.
1260
+ * @param {?CodeceptJS.LocatorOrString} [context=null] (optional, `null` by default) element located by CSS | XPath | strict locator.
1261
+ */
1262
+ async checkOption(field, context = null) {
1263
+ const elm = await this._locateCheckable(field, context);
1264
+ const curentlyChecked = await elm.getProperty('checked')
1265
+ .then(checkedProperty => checkedProperty.jsonValue());
1266
+ // Only check if NOT currently checked
1267
+ if (!curentlyChecked) {
1268
+ await elm.click();
1269
+ return this._waitForAction();
1270
+ }
1271
+ }
1272
+
1273
+ /**
1274
+ * Unselects a checkbox or radio button.
1275
+ * Element is located by label or name or CSS or XPath.
1276
+ *
1277
+ * The second parameter is a context (CSS or XPath locator) to narrow the search.
1278
+ *
1279
+ * ```js
1280
+ * I.uncheckOption('#agree');
1281
+ * I.uncheckOption('I Agree to Terms and Conditions');
1282
+ * I.uncheckOption('agree', '//form');
1283
+ * ```
1284
+ * @param {CodeceptJS.LocatorOrString} field checkbox located by label | name | CSS | XPath | strict locator.
1285
+ * @param {?CodeceptJS.LocatorOrString} [context=null] (optional, `null` by default) element located by CSS | XPath | strict locator.
1286
+ */
1287
+ async uncheckOption(field, context = null) {
1288
+ const elm = await this._locateCheckable(field, context);
1289
+ const curentlyChecked = await elm.getProperty('checked')
1290
+ .then(checkedProperty => checkedProperty.jsonValue());
1291
+ // Only uncheck if currently checked
1292
+ if (curentlyChecked) {
1293
+ await elm.click();
1294
+ return this._waitForAction();
1295
+ }
1296
+ }
1297
+
1298
+ /**
1299
+ * Verifies that the specified checkbox is checked.
1300
+ *
1301
+ * ```js
1302
+ * I.seeCheckboxIsChecked('Agree');
1303
+ * I.seeCheckboxIsChecked('#agree'); // I suppose user agreed to terms
1304
+ * I.seeCheckboxIsChecked({css: '#signup_form input[type=checkbox]'});
1305
+ * ```
1306
+ *
1307
+ * @param {CodeceptJS.LocatorOrString} field located by label|name|CSS|XPath|strict locator.
1308
+ *
1309
+ */
1310
+ async seeCheckboxIsChecked(field) {
1311
+ return proceedIsChecked.call(this, 'assert', field);
1312
+ }
1313
+
1314
+ /**
1315
+ * Verifies that the specified checkbox is not checked.
1316
+ *
1317
+ * ```js
1318
+ * I.dontSeeCheckboxIsChecked('#agree'); // located by ID
1319
+ * I.dontSeeCheckboxIsChecked('I agree to terms'); // located by label
1320
+ * I.dontSeeCheckboxIsChecked('agree'); // located by name
1321
+ * ```
1322
+ *
1323
+ * @param {CodeceptJS.LocatorOrString} field located by label|name|CSS|XPath|strict locator.
1324
+ *
1325
+ */
1326
+ async dontSeeCheckboxIsChecked(field) {
1327
+ return proceedIsChecked.call(this, 'negate', field);
1328
+ }
1329
+
1330
+ /**
1331
+ * Presses a key in the browser and leaves it in a down state.
1332
+ *
1333
+ * To make combinations with modifier key and user operation (e.g. `'Control'` + [`click`](#click)).
1334
+ *
1335
+ * ```js
1336
+ * I.pressKeyDown('Control');
1337
+ * I.click('#element');
1338
+ * I.pressKeyUp('Control');
1339
+ * ```
1340
+ *
1341
+ * @param {string} key name of key to press down.
1342
+ *
1343
+ */
1344
+ async pressKeyDown(key) {
1345
+ key = getNormalizedKey.call(this, key);
1346
+ await this.page.keyboard.down(key);
1347
+ return this._waitForAction();
1348
+ }
1349
+
1350
+ /**
1351
+ * Releases a key in the browser which was previously set to a down state.
1352
+ *
1353
+ * To make combinations with modifier key and user operation (e.g. `'Control'` + [`click`](#click)).
1354
+ *
1355
+ * ```js
1356
+ * I.pressKeyDown('Control');
1357
+ * I.click('#element');
1358
+ * I.pressKeyUp('Control');
1359
+ * ```
1360
+ *
1361
+ * @param {string} key name of key to release.
1362
+ *
1363
+ */
1364
+ async pressKeyUp(key) {
1365
+ key = getNormalizedKey.call(this, key);
1366
+ await this.page.keyboard.up(key);
1367
+ return this._waitForAction();
1368
+ }
1369
+
1370
+ /**
1371
+ * Presses a key in the browser (on a focused element).
1372
+ *
1373
+ * _Hint:_ For populating text field or textarea, it is recommended to use [`fillField`](#fillfield).
1374
+ *
1375
+ * ```js
1376
+ * I.pressKey('Backspace');
1377
+ * ```
1378
+ *
1379
+ * To press a key in combination with modifier keys, pass the sequence as an array. All modifier keys (`'Alt'`, `'Control'`, `'Meta'`, `'Shift'`) will be released afterwards.
1380
+ *
1381
+ * ```js
1382
+ * I.pressKey(['Control', 'Z']);
1383
+ * ```
1384
+ *
1385
+ * For specifying operation modifier key based on operating system it is suggested to use `'CommandOrControl'`.
1386
+ * This will press `'Command'` (also known as `'Meta'`) on macOS machines and `'Control'` on non-macOS machines.
1387
+ *
1388
+ * ```js
1389
+ * I.pressKey(['CommandOrControl', 'Z']);
1390
+ * ```
1391
+ *
1392
+ * Some of the supported key names are:
1393
+ * - `'AltLeft'` or `'Alt'`
1394
+ * - `'AltRight'`
1395
+ * - `'ArrowDown'`
1396
+ * - `'ArrowLeft'`
1397
+ * - `'ArrowRight'`
1398
+ * - `'ArrowUp'`
1399
+ * - `'Backspace'`
1400
+ * - `'Clear'`
1401
+ * - `'ControlLeft'` or `'Control'`
1402
+ * - `'ControlRight'`
1403
+ * - `'Command'`
1404
+ * - `'CommandOrControl'`
1405
+ * - `'Delete'`
1406
+ * - `'End'`
1407
+ * - `'Enter'`
1408
+ * - `'Escape'`
1409
+ * - `'F1'` to `'F12'`
1410
+ * - `'Home'`
1411
+ * - `'Insert'`
1412
+ * - `'MetaLeft'` or `'Meta'`
1413
+ * - `'MetaRight'`
1414
+ * - `'Numpad0'` to `'Numpad9'`
1415
+ * - `'NumpadAdd'`
1416
+ * - `'NumpadDecimal'`
1417
+ * - `'NumpadDivide'`
1418
+ * - `'NumpadMultiply'`
1419
+ * - `'NumpadSubtract'`
1420
+ * - `'PageDown'`
1421
+ * - `'PageUp'`
1422
+ * - `'Pause'`
1423
+ * - `'Return'`
1424
+ * - `'ShiftLeft'` or `'Shift'`
1425
+ * - `'ShiftRight'`
1426
+ * - `'Space'`
1427
+ * - `'Tab'`
1428
+ *
1429
+ * @param {string|string[]} key key or array of keys to press.
1430
+ *
1431
+ *
1432
+ * _Note:_ Shortcuts like `'Meta'` + `'A'` do not work on macOS ([GoogleChrome/Playwright#1313](https://github.com/GoogleChrome/Playwright/issues/1313)).
1433
+ */
1434
+ async pressKey(key) {
1435
+ const modifiers = [];
1436
+ if (Array.isArray(key)) {
1437
+ for (let k of key) {
1438
+ k = getNormalizedKey.call(this, k);
1439
+ if (isModifierKey(k)) {
1440
+ modifiers.push(k);
1441
+ } else {
1442
+ key = k;
1443
+ break;
1444
+ }
1445
+ }
1446
+ } else {
1447
+ key = getNormalizedKey.call(this, key);
1448
+ }
1449
+ for (const modifier of modifiers) {
1450
+ await this.page.keyboard.down(modifier);
1451
+ }
1452
+ await this.page.keyboard.press(key);
1453
+ for (const modifier of modifiers) {
1454
+ await this.page.keyboard.up(modifier);
1455
+ }
1456
+ return this._waitForAction();
1457
+ }
1458
+
1459
+ /**
1460
+ * Fills a text field or textarea, after clearing its value, with the given string.
1461
+ * Field is located by name, label, CSS, or XPath.
1462
+ *
1463
+ * ```js
1464
+ * // by label
1465
+ * I.fillField('Email', 'hello@world.com');
1466
+ * // by name
1467
+ * I.fillField('password', secret('123456'));
1468
+ * // by CSS
1469
+ * I.fillField('form#login input[name=username]', 'John');
1470
+ * // or by strict locator
1471
+ * I.fillField({css: 'form#login input[name=username]'}, 'John');
1472
+ * ```
1473
+ * @param {CodeceptJS.LocatorOrString} field located by label|name|CSS|XPath|strict locator.
1474
+ * @param {string} value text value to fill.
1475
+ *
1476
+ *
1477
+ */
1478
+ async fillField(field, value) {
1479
+ const els = await findFields.call(this, field);
1480
+ assertElementExists(els, field, 'Field');
1481
+ const el = els[0];
1482
+ const tag = await el.getProperty('tagName').then(el => el.jsonValue());
1483
+ const editable = await el.getProperty('contenteditable').then(el => el.jsonValue());
1484
+ if (tag === 'INPUT' || tag === 'TEXTAREA') {
1485
+ await this._evaluateHandeInContext(el => el.value = '', el);
1486
+ } else if (editable) {
1487
+ await this._evaluateHandeInContext(el => el.innerHTML = '', el);
1488
+ }
1489
+ await el.type(value.toString(), { delay: this.options.pressKeyDelay });
1490
+ return this._waitForAction();
1491
+ }
1492
+
1493
+
1494
+ /**
1495
+ * Clears a `<textarea>` or text `<input>` element's value.
1496
+ *
1497
+ * ```js
1498
+ * I.clearField('Email');
1499
+ * I.clearField('user[email]');
1500
+ * I.clearField('#email');
1501
+ * ```
1502
+ * @param {string|object} editable field located by label|name|CSS|XPath|strict locator.
1503
+ */
1504
+ async clearField(field) {
1505
+ return this.fillField(field, '');
1506
+ }
1507
+
1508
+ /**
1509
+ * Appends text to a input field or textarea.
1510
+ * Field is located by name, label, CSS or XPath
1511
+ *
1512
+ * ```js
1513
+ * I.appendField('#myTextField', 'appended');
1514
+ * ```
1515
+ * @param {CodeceptJS.LocatorOrString} field located by label|name|CSS|XPath|strict locator
1516
+ * @param {string} value text value to append.
1517
+ *
1518
+ *
1519
+ */
1520
+ async appendField(field, value) {
1521
+ const els = await findFields.call(this, field);
1522
+ assertElementExists(els, field, 'Field');
1523
+ await els[0].press('End');
1524
+ await els[0].type(value, { delay: this.options.pressKeyDelay });
1525
+ return this._waitForAction();
1526
+ }
1527
+
1528
+ /**
1529
+ * Checks that the given input field or textarea equals to given value.
1530
+ * For fuzzy locators, fields are matched by label text, the "name" attribute, CSS, and XPath.
1531
+ *
1532
+ * ```js
1533
+ * I.seeInField('Username', 'davert');
1534
+ * I.seeInField({css: 'form textarea'},'Type your comment here');
1535
+ * I.seeInField('form input[type=hidden]','hidden_value');
1536
+ * I.seeInField('#searchform input','Search');
1537
+ * ```
1538
+ * @param {CodeceptJS.LocatorOrString} field located by label|name|CSS|XPath|strict locator.
1539
+ * @param {string} value value to check.
1540
+ *
1541
+ */
1542
+ async seeInField(field, value) {
1543
+ return proceedSeeInField.call(this, 'assert', field, value);
1544
+ }
1545
+
1546
+ /**
1547
+ * Checks that value of input field or textarea doesn't equal to given value
1548
+ * Opposite to `seeInField`.
1549
+ *
1550
+ * ```js
1551
+ * I.dontSeeInField('email', 'user@user.com'); // field by name
1552
+ * I.dontSeeInField({ css: 'form input.email' }, 'user@user.com'); // field by CSS
1553
+ * ```
1554
+ *
1555
+ * @param {CodeceptJS.LocatorOrString} field located by label|name|CSS|XPath|strict locator.
1556
+ * @param {string} value value to check.
1557
+ */
1558
+ async dontSeeInField(field, value) {
1559
+ return proceedSeeInField.call(this, 'negate', field, value);
1560
+ }
1561
+
1562
+
1563
+ /**
1564
+ * Attaches a file to element located by label, name, CSS or XPath
1565
+ * Path to file is relative current codecept directory (where codecept.json or codecept.conf.js is located).
1566
+ * File will be uploaded to remote system (if tests are running remotely).
1567
+ *
1568
+ * ```js
1569
+ * I.attachFile('Avatar', 'data/avatar.jpg');
1570
+ * I.attachFile('form input[name=avatar]', 'data/avatar.jpg');
1571
+ * ```
1572
+ *
1573
+ * @param {CodeceptJS.LocatorOrString} locator field located by label|name|CSS|XPath|strict locator.
1574
+ * @param {string} pathToFile local file path relative to codecept.json config file.
1575
+ *
1576
+ */
1577
+ async attachFile(locator, pathToFile) {
1578
+ const file = path.join(global.codecept_dir, pathToFile);
1579
+
1580
+ if (!fileExists(file)) {
1581
+ throw new Error(`File at ${file} can not be found on local system`);
1582
+ }
1583
+ const els = await findFields.call(this, locator);
1584
+ assertElementExists(els, 'Field');
1585
+ await els[0].setInputFiles(file);
1586
+ return this._waitForAction();
1587
+ }
1588
+
1589
+ /**
1590
+ * Selects an option in a drop-down select.
1591
+ * Field is searched by label | name | CSS | XPath.
1592
+ * Option is selected by visible text or by value.
1593
+ *
1594
+ * ```js
1595
+ * I.selectOption('Choose Plan', 'Monthly'); // select by label
1596
+ * I.selectOption('subscription', 'Monthly'); // match option by text
1597
+ * I.selectOption('subscription', '0'); // or by value
1598
+ * I.selectOption('//form/select[@name=account]','Premium');
1599
+ * I.selectOption('form select[name=account]', 'Premium');
1600
+ * I.selectOption({css: 'form select[name=account]'}, 'Premium');
1601
+ * ```
1602
+ *
1603
+ * Provide an array for the second argument to select multiple options.
1604
+ *
1605
+ * ```js
1606
+ * I.selectOption('Which OS do you use?', ['Android', 'iOS']);
1607
+ * ```
1608
+ * @param {CodeceptJS.LocatorOrString} select field located by label|name|CSS|XPath|strict locator.
1609
+ * @param {string|Array<*>} option visible text or value of option.
1610
+ */
1611
+ async selectOption(select, option) {
1612
+ const els = await findFields.call(this, select);
1613
+ assertElementExists(els, select, 'Selectable field');
1614
+ const el = els[0];
1615
+ if (await el.getProperty('tagName').then(t => t.jsonValue()) !== 'SELECT') {
1616
+ throw new Error('Element is not <select>');
1617
+ }
1618
+ if (!Array.isArray(option)) option = [option];
1619
+
1620
+ for (const key in option) {
1621
+ const opt = xpathLocator.literal(option[key]);
1622
+ let optEl = await findElements.call(this, el, { xpath: Locator.select.byVisibleText(opt) });
1623
+ if (optEl.length) {
1624
+ this._evaluateHandeInContext(el => el.selected = true, optEl[0]);
1625
+ continue;
1626
+ }
1627
+ optEl = await findElements.call(this, el, { xpath: Locator.select.byValue(opt) });
1628
+ if (optEl.length) {
1629
+ this._evaluateHandeInContext(el => el.selected = true, optEl[0]);
1630
+ }
1631
+ }
1632
+ await this._evaluateHandeInContext((element) => {
1633
+ element.dispatchEvent(new Event('input', { bubbles: true }));
1634
+ element.dispatchEvent(new Event('change', { bubbles: true }));
1635
+ }, el);
1636
+
1637
+ return this._waitForAction();
1638
+ }
1639
+
1640
+ /**
1641
+ * Grab number of visible elements by locator.
1642
+ *
1643
+ * ```js
1644
+ * let numOfElements = await I.grabNumberOfVisibleElements('p');
1645
+ * ```
1646
+ *
1647
+ * @param {CodeceptJS.LocatorOrString} locator located by CSS|XPath|strict locator.
1648
+ * @returns {Promise<number>} number of visible elements
1649
+ *
1650
+ */
1651
+ async grabNumberOfVisibleElements(locator) {
1652
+ let els = await this._locate(locator);
1653
+ els = await Promise.all(els.map(el => el.boundingBox()));
1654
+ return els.filter(v => v).length;
1655
+ }
1656
+
1657
+ /**
1658
+ * Checks that current url contains a provided fragment.
1659
+ *
1660
+ * ```js
1661
+ * I.seeInCurrentUrl('/register'); // we are on registration page
1662
+ * ```
1663
+ *
1664
+ * @param {string} url a fragment to check
1665
+ */
1666
+ async seeInCurrentUrl(url) {
1667
+ stringIncludes('url').assert(url, await this._getPageUrl());
1668
+ }
1669
+
1670
+ /**
1671
+ * Checks that current url does not contain a provided fragment.
1672
+ *
1673
+ * @param {string} url value to check.
1674
+ */
1675
+ async dontSeeInCurrentUrl(url) {
1676
+ stringIncludes('url').negate(url, await this._getPageUrl());
1677
+ }
1678
+
1679
+ /**
1680
+ * Checks that current url is equal to provided one.
1681
+ * If a relative url provided, a configured url will be prepended to it.
1682
+ * So both examples will work:
1683
+ *
1684
+ * ```js
1685
+ * I.seeCurrentUrlEquals('/register');
1686
+ * I.seeCurrentUrlEquals('http://my.site.com/register');
1687
+ * ```
1688
+ *
1689
+ * @param {string} url value to check.
1690
+ */
1691
+ async seeCurrentUrlEquals(url) {
1692
+ urlEquals(this.options.url).assert(url, await this._getPageUrl());
1693
+ }
1694
+
1695
+ /**
1696
+ * Checks that current url is not equal to provided one.
1697
+ * If a relative url provided, a configured url will be prepended to it.
1698
+ *
1699
+ * ```js
1700
+ * I.dontSeeCurrentUrlEquals('/login'); // relative url are ok
1701
+ * I.dontSeeCurrentUrlEquals('http://mysite.com/login'); // absolute urls are also ok
1702
+ * ```
1703
+ *
1704
+ * @param {string} url value to check.
1705
+ */
1706
+ async dontSeeCurrentUrlEquals(url) {
1707
+ urlEquals(this.options.url).negate(url, await this._getPageUrl());
1708
+ }
1709
+
1710
+ /**
1711
+ * Checks that a page contains a visible text.
1712
+ * Use context parameter to narrow down the search.
1713
+ *
1714
+ * ```js
1715
+ * I.see('Welcome'); // text welcome on a page
1716
+ * I.see('Welcome', '.content'); // text inside .content div
1717
+ * I.see('Register', {css: 'form.register'}); // use strict locator
1718
+ * ```
1719
+ * @param {string} text expected on page.
1720
+ * @param {?CodeceptJS.LocatorOrString} [context=null] (optional, `null` by default) element located by CSS|Xpath|strict locator in which to search for text.
1721
+ *
1722
+ *
1723
+ */
1724
+ async see(text, context = null) {
1725
+ return proceedSee.call(this, 'assert', text, context);
1726
+ }
1727
+
1728
+ /**
1729
+ * Checks that text is equal to provided one.
1730
+ *
1731
+ * ```js
1732
+ * I.seeTextEquals('text', 'h1');
1733
+ * ```
1734
+ *
1735
+ * @param {string} text element value to check.
1736
+ * @param {CodeceptJS.LocatorOrString?} [context=null] element located by CSS|XPath|strict locator.
1737
+ */
1738
+ async seeTextEquals(text, context = null) {
1739
+ return proceedSee.call(this, 'assert', text, context, true);
1740
+ }
1741
+
1742
+ /**
1743
+ * Opposite to `see`. Checks that a text is not present on a page.
1744
+ * Use context parameter to narrow down the search.
1745
+ *
1746
+ * ```js
1747
+ * I.dontSee('Login'); // assume we are already logged in.
1748
+ * I.dontSee('Login', '.nav'); // no login inside .nav element
1749
+ * ```
1750
+ *
1751
+ * @param {string} text which is not present.
1752
+ * @param {CodeceptJS.LocatorOrString} [context] (optional) element located by CSS|XPath|strict locator in which to perfrom search.
1753
+ *
1754
+ *
1755
+ *
1756
+ */
1757
+ async dontSee(text, context = null) {
1758
+ return proceedSee.call(this, 'negate', text, context);
1759
+ }
1760
+
1761
+ /**
1762
+ * Retrieves page source and returns it to test.
1763
+ * Resumes test execution, so should be used inside an async function.
1764
+ *
1765
+ * ```js
1766
+ * let pageSource = await I.grabSource();
1767
+ * ```
1768
+ *
1769
+ * @returns {Promise<string>} source code
1770
+ */
1771
+ async grabSource() {
1772
+ return this.page.content();
1773
+ }
1774
+
1775
+ /**
1776
+ * Get JS log from browser.
1777
+ *
1778
+ * ```js
1779
+ * let logs = await I.grabBrowserLogs();
1780
+ * console.log(JSON.stringify(logs))
1781
+ * ```
1782
+ * @return {Promise<any[]>}
1783
+ */
1784
+ async grabBrowserLogs() {
1785
+ const logs = consoleLogStore.entries;
1786
+ consoleLogStore.clear();
1787
+ return logs;
1788
+ }
1789
+
1790
+ /**
1791
+ * Get current URL from browser.
1792
+ * Resumes test execution, so should be used inside an async function.
1793
+ *
1794
+ * ```js
1795
+ * let url = await I.grabCurrentUrl();
1796
+ * console.log(`Current URL is [${url}]`);
1797
+ * ```
1798
+ *
1799
+ * @returns {Promise<string>} current URL
1800
+ */
1801
+ async grabCurrentUrl() {
1802
+ return this._getPageUrl();
1803
+ }
1804
+
1805
+ /**
1806
+ * Checks that the current page contains the given string in its raw source code.
1807
+ *
1808
+ * ```js
1809
+ * I.seeInSource('<h1>Green eggs &amp; ham</h1>');
1810
+ * ```
1811
+ * @param {string} text value to check.
1812
+ */
1813
+ async seeInSource(text) {
1814
+ const source = await this.page.content();
1815
+ stringIncludes('HTML source of a page').assert(text, source);
1816
+ }
1817
+
1818
+ /**
1819
+ * Checks that the current page does not contains the given string in its raw source code.
1820
+ *
1821
+ * ```js
1822
+ * I.dontSeeInSource('<!--'); // no comments in source
1823
+ * ```
1824
+ *
1825
+ * @param {string} value to check.
1826
+ *
1827
+ */
1828
+ async dontSeeInSource(text) {
1829
+ const source = await this.page.content();
1830
+ stringIncludes('HTML source of a page').negate(text, source);
1831
+ }
1832
+
1833
+
1834
+ /**
1835
+ * Asserts that an element appears a given number of times in the DOM.
1836
+ * Element is located by label or name or CSS or XPath.
1837
+ *
1838
+ *
1839
+ * ```js
1840
+ * I.seeNumberOfElements('#submitBtn', 1);
1841
+ * ```
1842
+ *
1843
+ * @param {CodeceptJS.LocatorOrString} locator element located by CSS|XPath|strict locator.
1844
+ * @param {number} num number of elements.
1845
+ *
1846
+ *
1847
+ *
1848
+ */
1849
+ async seeNumberOfElements(locator, num) {
1850
+ const elements = await this._locate(locator);
1851
+ return equals(`expected number of elements (${locator}) is ${num}, but found ${elements.length}`).assert(elements.length, num);
1852
+ }
1853
+
1854
+ /**
1855
+ * Asserts that an element is visible a given number of times.
1856
+ * Element is located by CSS or XPath.
1857
+ *
1858
+ * ```js
1859
+ * I.seeNumberOfVisibleElements('.buttons', 3);
1860
+ * ```
1861
+ *
1862
+ * @param {CodeceptJS.LocatorOrString} locator element located by CSS|XPath|strict locator.
1863
+ * @param {number} num number of elements.
1864
+ *
1865
+ *
1866
+ *
1867
+ */
1868
+ async seeNumberOfVisibleElements(locator, num) {
1869
+ const res = await this.grabNumberOfVisibleElements(locator);
1870
+ return equals(`expected number of visible elements (${locator}) is ${num}, but found ${res}`).assert(res, num);
1871
+ }
1872
+
1873
+ /**
1874
+ * Sets cookie(s).
1875
+ *
1876
+ * Can be a single cookie object or an array of cookies:
1877
+ *
1878
+ * ```js
1879
+ * I.setCookie({name: 'auth', value: true});
1880
+ *
1881
+ * // as array
1882
+ * I.setCookie([
1883
+ * {name: 'auth', value: true},
1884
+ * {name: 'agree', value: true}
1885
+ * ]);
1886
+ * ```
1887
+ *
1888
+ * @param {object|array} cookie a cookie object or array of cookie objects.
1889
+ */
1890
+ async setCookie(cookie) {
1891
+ if (Array.isArray(cookie)) {
1892
+ return this.browserContext.addCookies(...cookie);
1893
+ }
1894
+ return this.browserContext.addCookies([cookie]);
1895
+ }
1896
+
1897
+ /**
1898
+ * Checks that cookie with given name exists.
1899
+ *
1900
+ * ```js
1901
+ * I.seeCookie('Auth');
1902
+ * ```
1903
+ *
1904
+ * @param {string} name cookie name.
1905
+ *
1906
+ *
1907
+ */
1908
+ async seeCookie(name) {
1909
+ const cookies = await this.browserContext.cookies();
1910
+ empty(`cookie ${name} to be set`).negate(cookies.filter(c => c.name === name));
1911
+ }
1912
+
1913
+ /**
1914
+ * Checks that cookie with given name does not exist.
1915
+ *
1916
+ * ```js
1917
+ * I.dontSeeCookie('auth'); // no auth cookie
1918
+ * ```
1919
+ *
1920
+ * @param {string} name cookie name.
1921
+ */
1922
+ async dontSeeCookie(name) {
1923
+ const cookies = await this.browserContext.cookies();
1924
+ empty(`cookie ${name} to be set`).assert(cookies.filter(c => c.name === name));
1925
+ }
1926
+
1927
+ /**
1928
+ * Gets a cookie object by name.
1929
+ * If none provided gets all cookies.
1930
+ * Resumes test execution, so **should be used inside async with `await`** operator.
1931
+ *
1932
+ * ```js
1933
+ * let cookie = await I.grabCookie('auth');
1934
+ * assert(cookie.value, '123456');
1935
+ * ```
1936
+ *
1937
+ * @param {?string} [name=null] cookie name.
1938
+ * @returns {Promise<string>} attribute value
1939
+ *
1940
+ * Returns cookie in JSON format. If name not passed returns all cookies for this domain.
1941
+ */
1942
+ async grabCookie(name) {
1943
+ const cookies = await this.browserContext.cookies();
1944
+ if (!name) return cookies;
1945
+ const cookie = cookies.filter(c => c.name === name);
1946
+ if (cookie[0]) return cookie[0];
1947
+ }
1948
+
1949
+ /**
1950
+ * Clears a cookie by name,
1951
+ * if none provided clears all cookies.
1952
+ *
1953
+ * ```js
1954
+ * I.clearCookie();
1955
+ * I.clearCookie('test');
1956
+ * ```
1957
+ *
1958
+ * @param {?string} [cookie=null] (optional, `null` by default) cookie name
1959
+ */
1960
+ async clearCookie() {
1961
+ // Playwright currently doesn't support to delete a certain cookie
1962
+ // https://github.com/microsoft/playwright/blob/master/docs/api.md#class-browsercontext
1963
+ return this.browserContext.clearCookies();
1964
+ }
1965
+
1966
+ /**
1967
+ * Executes a script on the page:
1968
+ *
1969
+ * ```js
1970
+ * I.executeScript(() => window.alert('Hello world'));
1971
+ * ```
1972
+ *
1973
+ * Additional parameters of the function can be passed as an object argument:
1974
+ *
1975
+ * ```js
1976
+ * I.executeScript(({x, y}) => x + y, {x, y});
1977
+ * ```
1978
+ * You can pass only one parameter into a function
1979
+ * but you can pass in array or object.
1980
+ *
1981
+ * ```js
1982
+ * I.executeScript(([x, y]) => x + y, [x, y]);
1983
+ * ```
1984
+ * If a function returns a Promise it will wait for its resolution.
1985
+ */
1986
+ async executeScript(fn, arg) {
1987
+ let context = this.page;
1988
+ if (this.context && this.context.constructor.name === 'Frame') {
1989
+ context = this.context; // switching to iframe context
1990
+ }
1991
+ return context.evaluate.apply(context, [fn, arg]);
1992
+ }
1993
+
1994
+ /**
1995
+ * Retrieves a text from an element located by CSS or XPath and returns it to test.
1996
+ * Resumes test execution, so **should be used inside async with `await`** operator.
1997
+ *
1998
+ * ```js
1999
+ * let pin = await I.grabTextFrom('#pin');
2000
+ * ```
2001
+ * If multiple elements found returns an array of texts.
2002
+ *
2003
+ * @param {CodeceptJS.LocatorOrString} locator element located by CSS|XPath|strict locator.
2004
+ * @returns {Promise<string|string[]>} attribute value
2005
+ *
2006
+ */
2007
+ async grabTextFrom(locator) {
2008
+ const els = await this._locate(locator);
2009
+ assertElementExists(els, locator);
2010
+ const texts = [];
2011
+ for (const el of els) {
2012
+ texts.push(await (await el.getProperty('innerText')).jsonValue());
2013
+ }
2014
+ if (texts.length === 1) return texts[0];
2015
+ return texts;
2016
+ }
2017
+
2018
+ /**
2019
+ * Retrieves a value from a form element located by CSS or XPath and returns it to test.
2020
+ * Resumes test execution, so **should be used inside async function with `await`** operator.
2021
+ *
2022
+ * ```js
2023
+ * let email = await I.grabValueFrom('input[name=email]');
2024
+ * ```
2025
+ * @param {CodeceptJS.LocatorOrString} locator field located by label|name|CSS|XPath|strict locator.
2026
+ * @returns {Promise<string>} attribute value
2027
+ */
2028
+ async grabValueFrom(locator) {
2029
+ const els = await findFields.call(this, locator);
2030
+ assertElementExists(els, locator);
2031
+ return els[0].getProperty('value').then(t => t.jsonValue());
2032
+ }
2033
+
2034
+ /**
2035
+ * Retrieves the innerHTML from an element located by CSS or XPath and returns it to test.
2036
+ * Resumes test execution, so **should be used inside async function with `await`** operator.
2037
+ * If more than one element is found - an array of HTMLs returned.
2038
+ *
2039
+ * ```js
2040
+ * let postHTML = await I.grabHTMLFrom('#post');
2041
+ * ```
2042
+ *
2043
+ * @param {CodeceptJS.LocatorOrString} element located by CSS|XPath|strict locator.
2044
+ * @returns {Promise<string>} HTML code for an element
2045
+ */
2046
+ async grabHTMLFrom(locator) {
2047
+ const els = await this._locate(locator);
2048
+ assertElementExists(els, locator);
2049
+ const values = await Promise.all(els.map(el => el.$eval('xpath=.', element => element.innerHTML, el)));
2050
+ if (Array.isArray(values) && values.length === 1) {
2051
+ return values[0];
2052
+ }
2053
+ return values;
2054
+ }
2055
+
2056
+ /**
2057
+ * Grab CSS property for given locator
2058
+ * Resumes test execution, so **should be used inside an async function with `await`** operator.
2059
+ *
2060
+ * ```js
2061
+ * const value = await I.grabCssPropertyFrom('h3', 'font-weight');
2062
+ * ```
2063
+ *
2064
+ * @param {CodeceptJS.LocatorOrString} locator element located by CSS|XPath|strict locator.
2065
+ * @param {string} cssProperty CSS property name.
2066
+ * @returns {Promise<string>} CSS value
2067
+ *
2068
+ */
2069
+ async grabCssPropertyFrom(locator, cssProperty) {
2070
+ const els = await this._locate(locator);
2071
+ const res = await Promise.all(els.map(el => el.$eval('xpath=.', el => JSON.parse(JSON.stringify(getComputedStyle(el))), el)));
2072
+ const cssValues = res.map(props => props[toCamelCase(cssProperty)]);
2073
+
2074
+ if (res.length > 0) {
2075
+ return cssValues;
2076
+ }
2077
+ return cssValues[0];
2078
+ }
2079
+
2080
+ /**
2081
+ * Checks that all elements with given locator have given CSS properties.
2082
+ *
2083
+ * ```js
2084
+ * I.seeCssPropertiesOnElements('h3', { 'font-weight': "bold"});
2085
+ * ```
2086
+ *
2087
+ * @param {CodeceptJS.LocatorOrString} locator located by CSS|XPath|strict locator.
2088
+ * @param {object} cssProperties object with CSS properties and their values to check.
2089
+ *
2090
+ */
2091
+ async seeCssPropertiesOnElements(locator, cssProperties) {
2092
+ const res = await this._locate(locator);
2093
+ assertElementExists(res, locator);
2094
+
2095
+ const cssPropertiesCamelCase = convertCssPropertiesToCamelCase(cssProperties);
2096
+ const elemAmount = res.length;
2097
+ const commands = [];
2098
+ res.forEach((el) => {
2099
+ Object.keys(cssPropertiesCamelCase).forEach((prop) => {
2100
+ commands.push(el.$eval('xpath=.', (el) => {
2101
+ const style = window.getComputedStyle ? getComputedStyle(el) : el.currentStyle;
2102
+ return JSON.parse(JSON.stringify(style));
2103
+ }, el)
2104
+ .then((props) => {
2105
+ if (isColorProperty(prop)) {
2106
+ return convertColorToRGBA(props[prop]);
2107
+ }
2108
+ return props[prop];
2109
+ }));
2110
+ });
2111
+ });
2112
+ let props = await Promise.all(commands);
2113
+ const values = Object.keys(cssPropertiesCamelCase).map(key => cssPropertiesCamelCase[key]);
2114
+ if (!Array.isArray(props)) props = [props];
2115
+ let chunked = chunkArray(props, values.length);
2116
+ chunked = chunked.filter((val) => {
2117
+ for (let i = 0; i < val.length; ++i) {
2118
+ if (val[i] !== values[i]) return false;
2119
+ }
2120
+ return true;
2121
+ });
2122
+ return equals(`all elements (${locator}) to have CSS property ${JSON.stringify(cssProperties)}`).assert(chunked.length, elemAmount);
2123
+ }
2124
+
2125
+ /**
2126
+ * Checks that all elements with given locator have given attributes.
2127
+ *
2128
+ * ```js
2129
+ * I.seeAttributesOnElements('//form', { method: "post"});
2130
+ * ```
2131
+ *
2132
+ * @param {CodeceptJS.LocatorOrString} locator located by CSS|XPath|strict locator.
2133
+ * @param {object} attributes attributes and their values to check.
2134
+ *
2135
+ */
2136
+ async seeAttributesOnElements(locator, attributes) {
2137
+ const res = await this._locate(locator);
2138
+ assertElementExists(res, locator);
2139
+
2140
+ const elemAmount = res.length;
2141
+ const commands = [];
2142
+ res.forEach((el) => {
2143
+ Object.keys(attributes).forEach((prop) => {
2144
+ commands.push(el
2145
+ .$eval('xpath=.', (el, attr) => el[attr] || el.getAttribute(attr), prop));
2146
+ });
2147
+ });
2148
+ let attrs = await Promise.all(commands);
2149
+ const values = Object.keys(attributes).map(key => attributes[key]);
2150
+ if (!Array.isArray(attrs)) attrs = [attrs];
2151
+ let chunked = chunkArray(attrs, values.length);
2152
+ chunked = chunked.filter((val) => {
2153
+ for (let i = 0; i < val.length; ++i) {
2154
+ if (val[i] !== values[i]) return false;
2155
+ }
2156
+ return true;
2157
+ });
2158
+ return equals(`all elements (${locator}) to have attributes ${JSON.stringify(attributes)}`).assert(chunked.length, elemAmount);
2159
+ }
2160
+
2161
+ /**
2162
+ * Drag the scrubber of a slider to a given position
2163
+ * For fuzzy locators, fields are matched by label text, the "name" attribute, CSS, and XPath.
2164
+ *
2165
+ * ```js
2166
+ * I.dragSlider('#slider', 30);
2167
+ * I.dragSlider('#slider', -70);
2168
+ * ```
2169
+ *
2170
+ * @param {CodeceptJS.LocatorOrString} locator located by label|name|CSS|XPath|strict locator.
2171
+ * @param {number} offsetX position to drag.
2172
+ *
2173
+ */
2174
+ async dragSlider(locator, offsetX = 0) {
2175
+ const src = await this._locate(locator);
2176
+ assertElementExists(src, locator, 'Slider Element');
2177
+
2178
+ // Note: Using private api ._clickablePoint because the .BoundingBox does not take into account iframe offsets!
2179
+ const sliderSource = await src[0]._clickablePoint();
2180
+
2181
+ // Drag start point
2182
+ await this.page.mouse.move(sliderSource.x, sliderSource.y, { steps: 5 });
2183
+ await this.page.mouse.down();
2184
+
2185
+ // Drag destination
2186
+ await this.page.mouse.move(sliderSource.x + offsetX, sliderSource.y, { steps: 5 });
2187
+ await this.page.mouse.up();
2188
+
2189
+ return this._waitForAction();
2190
+ }
2191
+
2192
+ /**
2193
+ * Retrieves an attribute from an element located by CSS or XPath and returns it to test.
2194
+ * An array as a result will be returned if there are more than one matched element.
2195
+ * Resumes test execution, so **should be used inside async with `await`** operator.
2196
+ *
2197
+ * ```js
2198
+ * let hint = await I.grabAttributeFrom('#tooltip', 'title');
2199
+ * ```
2200
+ * @param {CodeceptJS.LocatorOrString} locator element located by CSS|XPath|strict locator.
2201
+ * @param {string} attr attribute name.
2202
+ * @returns {Promise<string>} attribute value
2203
+ *
2204
+ */
2205
+ async grabAttributeFrom(locator, attr) {
2206
+ const els = await this._locate(locator);
2207
+ assertElementExists(els, locator);
2208
+ const array = [];
2209
+
2210
+ for (let index = 0; index < els.length; index++) {
2211
+ const a = await this._evaluateHandeInContext(([el, attr]) => el[attr] || el.getAttribute(attr), [els[index], attr]);
2212
+ array.push(await a.jsonValue());
2213
+ }
2214
+
2215
+ return array.length === 1 ? array[0] : array;
2216
+ }
2217
+
2218
+ /**
2219
+ * Saves a screenshot to ouput folder (set in codecept.json or codecept.conf.js).
2220
+ * Filename is relative to output folder.
2221
+ * Optionally resize the window to the full available page `scrollHeight` and `scrollWidth` to capture the entire page by passing `true` in as the second argument.
2222
+ *
2223
+ * ```js
2224
+ * I.saveScreenshot('debug.png');
2225
+ * I.saveScreenshot('debug.png', true) //resizes to available scrollHeight and scrollWidth before taking screenshot
2226
+ * ```
2227
+ *
2228
+ * @param {string} fileName file name to save.
2229
+ * @param {boolean} [fullPage=false] (optional, `false` by default) flag to enable fullscreen screenshot mode.
2230
+ */
2231
+ async saveScreenshot(fileName, fullPage) {
2232
+ const fullPageOption = fullPage || this.options.fullPageScreenshots;
2233
+ const outputFile = screenshotOutputFolder(fileName);
2234
+
2235
+ this.debug(`Screenshot is saving to ${outputFile}`);
2236
+
2237
+ if (this.activeSessionName) {
2238
+ const activeSessionPage = this.sessionPages[this.activeSessionName];
2239
+
2240
+ if (activeSessionPage) {
2241
+ return activeSessionPage.screenshot({
2242
+ path: outputFile,
2243
+ fullPage: fullPageOption,
2244
+ type: 'png',
2245
+ });
2246
+ }
2247
+ }
2248
+
2249
+ return this.page.screenshot({ path: outputFile, fullPage: fullPageOption, type: 'png' });
2250
+ }
2251
+
2252
+ async _failed(test) {
2253
+ await this._withinEnd();
2254
+ }
2255
+
2256
+ /**
2257
+ * Pauses execution for a number of seconds.
2258
+ *
2259
+ * ```js
2260
+ * I.wait(2); // wait 2 secs
2261
+ * ```
2262
+ *
2263
+ * @param {number} sec number of second to wait.
2264
+ */
2265
+ async wait(sec) {
2266
+ return new Promise(((done) => {
2267
+ setTimeout(done, sec * 1000);
2268
+ }));
2269
+ }
2270
+
2271
+ /**
2272
+ * Waits for element to become enabled (by default waits for 1sec).
2273
+ * Element can be located by CSS or XPath.
2274
+ *
2275
+ * @param {CodeceptJS.LocatorOrString} locator element located by CSS|XPath|strict locator.
2276
+ * @param {number} [sec=1] (optional) time in seconds to wait, 1 by default.
2277
+ */
2278
+ async waitForEnabled(locator, sec) {
2279
+ const waitTimeout = sec ? sec * 1000 : this.options.waitForTimeout;
2280
+ locator = new Locator(locator, 'css');
2281
+ const matcher = await this.context;
2282
+ let waiter;
2283
+ const context = await this._getContext();
2284
+ if (!locator.isXPath()) {
2285
+ // playwright combined selectors
2286
+ waiter = context.waitForSelector(`${locator.isCustom() ? `${locator.type}=${locator.value}` : locator.simplify()} >> __disabled=false`, { timeout: waitTimeout });
2287
+ } else {
2288
+ const enabledFn = function ([locator, $XPath]) {
2289
+ eval($XPath); // eslint-disable-line no-eval
2290
+ return $XPath(null, locator).filter(el => !el.disabled).length > 0;
2291
+ };
2292
+ waiter = context.waitForFunction(enabledFn, [locator.value, $XPath.toString()], { timeout: waitTimeout });
2293
+ }
2294
+ return waiter.catch((err) => {
2295
+ throw new Error(`element (${locator.toString()}) still not enabled after ${waitTimeout / 1000} sec\n${err.message}`);
2296
+ });
2297
+ }
2298
+
2299
+ /**
2300
+ * Waits for the specified value to be in value attribute.
2301
+ *
2302
+ * ```js
2303
+ * I.waitForValue('//input', "GoodValue");
2304
+ * ```
2305
+ *
2306
+ * @param {string|object} field input field.
2307
+ * @param {string }value expected value.
2308
+ * @param {number} [sec=1] (optional, `1` by default) time in seconds to wait
2309
+ */
2310
+ async waitForValue(field, value, sec) {
2311
+ const waitTimeout = sec ? sec * 1000 : this.options.waitForTimeout;
2312
+ const locator = new Locator(field, 'css');
2313
+ const matcher = await this.context;
2314
+ let waiter;
2315
+ const context = await this._getContext();
2316
+ if (!locator.isXPath()) {
2317
+ // uses a custom selector engine for finding value properties on elements
2318
+ waiter = context.waitForSelector(`${locator.isCustom() ? `${locator.type}=${locator.value}` : locator.simplify()} >> __value=${value}`, { timeout: waitTimeout, waitFor: 'visible' });
2319
+ } else {
2320
+ const valueFn = function ([locator, $XPath, value]) {
2321
+ eval($XPath); // eslint-disable-line no-eval
2322
+ return $XPath(null, locator).filter(el => (el.value || '').indexOf(value) !== -1).length > 0;
2323
+ };
2324
+ waiter = context.waitForFunction(valueFn, [locator.value, $XPath.toString(), value], { timeout: waitTimeout });
2325
+ }
2326
+ return waiter.catch((err) => {
2327
+ const loc = locator.toString();
2328
+ throw new Error(`element (${loc}) is not in DOM or there is no element(${loc}) with value "${value}" after ${waitTimeout / 1000} sec\n${err.message}`);
2329
+ });
2330
+ }
2331
+
2332
+ /**
2333
+ * Waits for a specified number of elements on the page.
2334
+ *
2335
+ * ```js
2336
+ * I.waitNumberOfVisibleElements('a', 3);
2337
+ * ```
2338
+ *
2339
+ * @param {CodeceptJS.LocatorOrString} locator element located by CSS|XPath|strict locator.
2340
+ * @param {number} num number of elements.
2341
+ * @param {number} [sec=1] (optional, `1` by default) time in seconds to wait
2342
+ *
2343
+ */
2344
+ async waitNumberOfVisibleElements(locator, num, sec) {
2345
+ const waitTimeout = sec ? sec * 1000 : this.options.waitForTimeout;
2346
+ locator = new Locator(locator, 'css');
2347
+ const matcher = await this.context;
2348
+ let waiter;
2349
+ const context = await this._getContext();
2350
+ if (locator.isCSS()) {
2351
+ const visibleFn = function ([locator, num]) {
2352
+ const els = document.querySelectorAll(locator);
2353
+ if (!els || els.length === 0) {
2354
+ return false;
2355
+ }
2356
+ return Array.prototype.filter.call(els, el => el.offsetParent !== null).length === num;
2357
+ };
2358
+ waiter = context.waitForFunction(visibleFn, [locator.value, num], { timeout: waitTimeout });
2359
+ } else {
2360
+ const visibleFn = function ([locator, $XPath, num]) {
2361
+ eval($XPath); // eslint-disable-line no-eval
2362
+ return $XPath(null, locator).filter(el => el.offsetParent !== null).length === num;
2363
+ };
2364
+ waiter = context.waitForFunction(visibleFn, [locator.value, $XPath.toString(), num], { timeout: waitTimeout });
2365
+ }
2366
+ return waiter.catch((err) => {
2367
+ throw new Error(`The number of elements (${locator.toString()}) is not ${num} after ${waitTimeout / 1000} sec\n${err.message}`);
2368
+ });
2369
+ }
2370
+
2371
+ /**
2372
+ * Waits for element to be clickable (by default waits for 1sec).
2373
+ * Element can be located by CSS or XPath.
2374
+ *
2375
+ * ```js
2376
+ * I.waitForClickable('.btn.continue');
2377
+ * I.waitForClickable('.btn.continue', 5); // wait for 5 secs
2378
+ * ```
2379
+ *
2380
+ * @param {CodeceptJS.LocatorOrString} locator element located by CSS|XPath|strict locator.
2381
+ * @param {number} [sec] (optional, `1` by default) time in seconds to wait
2382
+ */
2383
+ async waitForClickable(locator, waitTimeout) {
2384
+ console.log('I.waitForClickable is DEPRECATED: This is no longer needed, Playwright automatically waits for element to be clikable');
2385
+ console.log('Remove usage of this function');
2386
+ }
2387
+
2388
+ /**
2389
+ * Waits for element to be present on page (by default waits for 1sec).
2390
+ * Element can be located by CSS or XPath.
2391
+ *
2392
+ * ```js
2393
+ * I.waitForElement('.btn.continue');
2394
+ * I.waitForElement('.btn.continue', 5); // wait for 5 secs
2395
+ * ```
2396
+ *
2397
+ * @param {CodeceptJS.LocatorOrString} locator element located by CSS|XPath|strict locator.
2398
+ * @param {number} [sec] (optional, `1` by default) time in seconds to wait
2399
+ *
2400
+ */
2401
+ async waitForElement(locator, sec) {
2402
+ const waitTimeout = sec ? sec * 1000 : this.options.waitForTimeout;
2403
+ locator = new Locator(locator, 'css');
2404
+
2405
+ const context = await this._getContext();
2406
+ const waiter = context.waitForSelector(`${locator.isCustom() ? `${locator.type}=${locator.value}` : locator.simplify()}`, { timeout: waitTimeout });
2407
+ return waiter.catch((err) => {
2408
+ throw new Error(`element (${locator.toString()}) still not present on page after ${waitTimeout / 1000} sec\n${err.message}`);
2409
+ });
2410
+ }
2411
+
2412
+ /**
2413
+ * Waits for an element to become visible on a page (by default waits for 1sec).
2414
+ * Element can be located by CSS or XPath.
2415
+ *
2416
+ * ```js
2417
+ * I.waitForVisible('#popup');
2418
+ * ```
2419
+ *
2420
+ * @param {CodeceptJS.LocatorOrString} locator element located by CSS|XPath|strict locator.
2421
+ * @param {number} [sec=1] (optional, `1` by default) time in seconds to wait
2422
+ *
2423
+ * This method accepts [React selectors](https://codecept.io/react).
2424
+ */
2425
+ async waitForVisible(locator, sec) {
2426
+ const waitTimeout = sec ? sec * 1000 : this.options.waitForTimeout;
2427
+ locator = new Locator(locator, 'css');
2428
+ const context = await this._getContext();
2429
+ const waiter = context.waitForSelector(`${locator.isCustom() ? `${locator.type}=${locator.value}` : locator.simplify()}`, { timeout: waitTimeout, waitFor: 'visible' });
2430
+ return waiter.catch((err) => {
2431
+ throw new Error(`element (${locator.toString()}) still not visible after ${waitTimeout / 1000} sec\n${err.message}`);
2432
+ });
2433
+ }
2434
+
2435
+ /**
2436
+ * Waits for an element to be removed or become invisible on a page (by default waits for 1sec).
2437
+ * Element can be located by CSS or XPath.
2438
+ *
2439
+ * ```js
2440
+ * I.waitForInvisible('#popup');
2441
+ * ```
2442
+ *
2443
+ * @param {CodeceptJS.LocatorOrString} locator element located by CSS|XPath|strict locator.
2444
+ * @param {number} [sec=1] (optional, `1` by default) time in seconds to wait
2445
+ */
2446
+ async waitForInvisible(locator, sec) {
2447
+ const waitTimeout = sec ? sec * 1000 : this.options.waitForTimeout;
2448
+ locator = new Locator(locator, 'css');
2449
+ const context = await this._getContext();
2450
+ const waiter = context.waitForSelector(`${locator.isCustom() ? `${locator.type}=${locator.value}` : locator.simplify()}`, { timeout: waitTimeout, waitFor: 'hidden' });
2451
+ return waiter.catch((err) => {
2452
+ throw new Error(`element (${locator.toString()}) still visible after ${waitTimeout / 1000} sec\n${err.message}`);
2453
+ });
2454
+ }
2455
+
2456
+ /**
2457
+ * Waits for an element to hide (by default waits for 1sec).
2458
+ * Element can be located by CSS or XPath.
2459
+ *
2460
+ * ```js
2461
+ * I.waitToHide('#popup');
2462
+ * ```
2463
+ *
2464
+ * @param {CodeceptJS.LocatorOrString} locator element located by CSS|XPath|strict locator.
2465
+ * @param {number} [sec=1] (optional, `1` by default) time in seconds to wait
2466
+ */
2467
+ async waitToHide(locator, sec) {
2468
+ const waitTimeout = sec ? sec * 1000 : this.options.waitForTimeout;
2469
+ locator = new Locator(locator, 'css');
2470
+ const context = await this._getContext();
2471
+ return context.waitForSelector(`${locator.isCustom() ? `${locator.type}=${locator.value}` : locator.simplify()}`, { timeout: waitTimeout, waitFor: 'hidden' }).catch((err) => {
2472
+ throw new Error(`element (${locator.toString()}) still not hidden after ${waitTimeout / 1000} sec\n${err.message}`);
2473
+ });
2474
+ }
2475
+
2476
+ async _getContext() {
2477
+ if (this.context && this.context.constructor.name === 'Frame') {
2478
+ return this.context;
2479
+ }
2480
+ return this.page;
2481
+ }
2482
+
2483
+ /**
2484
+ * Waiting for the part of the URL to match the expected. Useful for SPA to understand that page was changed.
2485
+ *
2486
+ * ```js
2487
+ * I.waitInUrl('/info', 2);
2488
+ * ```
2489
+ *
2490
+ * @param {string} urlPart value to check.
2491
+ * @param {number} [sec=1] (optional, `1` by default) time in seconds to wait
2492
+ */
2493
+ async waitInUrl(urlPart, sec = null) {
2494
+ const waitTimeout = sec ? sec * 1000 : this.options.waitForTimeout;
2495
+
2496
+ return this.page.waitForFunction((urlPart) => {
2497
+ const currUrl = decodeURIComponent(decodeURIComponent(decodeURIComponent(window.location.href)));
2498
+ return currUrl.indexOf(urlPart) > -1;
2499
+ }, urlPart, { timeout: waitTimeout }).catch(async (e) => {
2500
+ const currUrl = await this._getPageUrl(); // Required because the waitForFunction can't return data.
2501
+ if (/failed: timeout/i.test(e.message)) {
2502
+ throw new Error(`expected url to include ${urlPart}, but found ${currUrl}`);
2503
+ } else {
2504
+ throw e;
2505
+ }
2506
+ });
2507
+ }
2508
+
2509
+ /**
2510
+ * Waits for the entire URL to match the expected
2511
+ *
2512
+ * ```js
2513
+ * I.waitUrlEquals('/info', 2);
2514
+ * I.waitUrlEquals('http://127.0.0.1:8000/info');
2515
+ * ```
2516
+ *
2517
+ * @param {string} urlPart value to check.
2518
+ * @param {number} [sec=1] (optional, `1` by default) time in seconds to wait
2519
+ */
2520
+ async waitUrlEquals(urlPart, sec = null) {
2521
+ const waitTimeout = sec ? sec * 1000 : this.options.waitForTimeout;
2522
+
2523
+ const baseUrl = this.options.url;
2524
+ if (urlPart.indexOf('http') < 0) {
2525
+ urlPart = baseUrl + urlPart;
2526
+ }
2527
+
2528
+ return this.page.waitForFunction((urlPart) => {
2529
+ const currUrl = decodeURIComponent(decodeURIComponent(decodeURIComponent(window.location.href)));
2530
+ return currUrl.indexOf(urlPart) > -1;
2531
+ }, urlPart, { timeout: waitTimeout }).catch(async (e) => {
2532
+ const currUrl = await this._getPageUrl(); // Required because the waitForFunction can't return data.
2533
+ if (/failed: timeout/i.test(e.message)) {
2534
+ throw new Error(`expected url to be ${urlPart}, but found ${currUrl}`);
2535
+ } else {
2536
+ throw e;
2537
+ }
2538
+ });
2539
+ }
2540
+
2541
+ /**
2542
+ * Waits for a text to appear (by default waits for 1sec).
2543
+ * Element can be located by CSS or XPath.
2544
+ * Narrow down search results by providing context.
2545
+ *
2546
+ * ```js
2547
+ * I.waitForText('Thank you, form has been submitted');
2548
+ * I.waitForText('Thank you, form has been submitted', 5, '#modal');
2549
+ * ```
2550
+ *
2551
+ * @param {string }text to wait for.
2552
+ * @param {number} [sec=1] (optional, `1` by default) time in seconds to wait
2553
+ * @param {CodeceptJS.LocatorOrString} [context] (optional) element located by CSS|XPath|strict locator.
2554
+ */
2555
+ async waitForText(text, sec = null, context = null) {
2556
+ const waitTimeout = sec ? sec * 1000 : this.options.waitForTimeout;
2557
+ let waiter;
2558
+
2559
+ const contextObject = await this._getContext();
2560
+
2561
+ if (context) {
2562
+ const locator = new Locator(context, 'css');
2563
+ if (!locator.isXPath()) {
2564
+ waiter = contextObject.waitFor(`${locator.isCustom() ? `${locator.type}=${locator.value}` : locator.simplify()} >> text=${text}`, { timeout: waitTimeout, waitFor: 'visible' });
2565
+ }
2566
+
2567
+ if (locator.isXPath()) {
2568
+ waiter = contextObject.waitForFunction(([locator, text, $XPath]) => {
2569
+ eval($XPath); // eslint-disable-line no-eval
2570
+ const el = $XPath(null, locator);
2571
+ if (!el.length) return false;
2572
+ return el[0].innerText.indexOf(text) > -1;
2573
+ }, [locator.value, text, $XPath.toString()], { timeout: waitTimeout });
2574
+ }
2575
+ } else {
2576
+ waiter = contextObject.waitForFunction(text => document.body && document.body.innerText.indexOf(text) > -1, text, { timeout: waitTimeout });
2577
+ }
2578
+ return waiter.catch((err) => {
2579
+ throw new Error(`Text "${text}" was not found on page after ${waitTimeout / 1000} sec\n${err.message}`);
2580
+ });
2581
+ }
2582
+
2583
+ /**
2584
+ * Waits for a network request.
2585
+ *
2586
+ * ```js
2587
+ * I.waitForRequest('http://example.com/resource');
2588
+ * I.waitForRequest(request => request.url() === 'http://example.com' && request.method() === 'GET');
2589
+ * ```
2590
+ *
2591
+ * @param {string|function} urlOrPredicate
2592
+ * @param {?number} [sec=null] seconds to wait
2593
+ */
2594
+ async waitForRequest(urlOrPredicate, sec = null) {
2595
+ const timeout = sec ? sec * 1000 : this.options.waitForTimeout;
2596
+ return this.page.waitForRequest(urlOrPredicate, { timeout });
2597
+ }
2598
+
2599
+ /**
2600
+ * Waits for a network request.
2601
+ *
2602
+ * ```js
2603
+ * I.waitForResponse('http://example.com/resource');
2604
+ * I.waitForResponse(request => request.url() === 'http://example.com' && request.method() === 'GET');
2605
+ * ```
2606
+ *
2607
+ * @param {string|function} urlOrPredicate
2608
+ * @param {?number} [sec=null] number of seconds to wait
2609
+ */
2610
+ async waitForResponse(urlOrPredicate, sec = null) {
2611
+ const timeout = sec ? sec * 1000 : this.options.waitForTimeout;
2612
+ return this.page.waitForResponse(urlOrPredicate, { timeout });
2613
+ }
2614
+
2615
+ /**
2616
+ * Switches frame or in case of null locator reverts to parent.
2617
+ *
2618
+ * ```js
2619
+ * I.switchTo('iframe'); // switch to first iframe
2620
+ * I.switchTo(); // switch back to main page
2621
+ * ```
2622
+ *
2623
+ * @param {?CodeceptJS.LocatorOrString} [locator=null] (optional, `null` by default) element located by CSS|XPath|strict locator.
2624
+ */
2625
+ async switchTo(locator) {
2626
+ if (Number.isInteger(locator)) {
2627
+ // Select by frame index of current context
2628
+
2629
+ let childFrames = null;
2630
+ if (this.context && typeof this.context.childFrames === 'function') {
2631
+ childFrames = this.context.childFrames();
2632
+ } else {
2633
+ childFrames = this.page.mainFrame().childFrames();
2634
+ }
2635
+
2636
+ if (locator >= 0 && locator < childFrames.length) {
2637
+ this.context = childFrames[locator];
2638
+ } else {
2639
+ throw new Error('Element #invalidIframeSelector was not found by text|CSS|XPath');
2640
+ }
2641
+ return;
2642
+ }
2643
+ if (!locator) {
2644
+ this.context = await this.page.mainFrame().$('body');
2645
+ return;
2646
+ }
2647
+
2648
+ // iframe by selector
2649
+ const els = await this._locate(locator);
2650
+ assertElementExists(els, locator);
2651
+ const contentFrame = await els[0].contentFrame();
2652
+
2653
+ if (contentFrame) {
2654
+ this.context = contentFrame;
2655
+ } else {
2656
+ this.context = els[0];
2657
+ }
2658
+ }
2659
+
2660
+ /**
2661
+ * Waits for a function to return true (waits for 1 sec by default).
2662
+ * Running in browser context.
2663
+ *
2664
+ * ```js
2665
+ * I.waitForFunction(fn[, [args[, timeout]])
2666
+ * ```
2667
+ *
2668
+ * ```js
2669
+ * I.waitForFunction(() => window.requests == 0);
2670
+ * I.waitForFunction(() => window.requests == 0, 5); // waits for 5 sec
2671
+ * I.waitForFunction((count) => window.requests == count, [3], 5) // pass args and wait for 5 sec
2672
+ * ```
2673
+ *
2674
+ * @param {string|function} fn to be executed in browser context.
2675
+ * @param {any[]|number} [argsOrSec] (optional, `1` by default) arguments for function or seconds.
2676
+ * @param {number} [sec] (optional, `1` by default) time in seconds to wait
2677
+ *
2678
+ */
2679
+ async waitForFunction(fn, argsOrSec = null, sec = null) {
2680
+ let args = [];
2681
+ if (argsOrSec) {
2682
+ if (Array.isArray(argsOrSec)) {
2683
+ args = argsOrSec;
2684
+ } else if (typeof argsOrSec === 'number') {
2685
+ sec = argsOrSec;
2686
+ }
2687
+ }
2688
+ const waitTimeout = sec ? sec * 1000 : this.options.waitForTimeout;
2689
+ const context = await this._getContext();
2690
+ return context.waitForFunction(fn, args, { timeout: waitTimeout });
2691
+ }
2692
+
2693
+ /**
2694
+ * Waits for navigation to finish. By default takes configured `waitForNavigation` option.
2695
+ *
2696
+ * See [Pupeteer's reference](https://github.com/GoogleChrome/Playwright/blob/master/docs/api.md#pagewaitfornavigationoptions)
2697
+ *
2698
+ * @param {*} opts
2699
+ */
2700
+ async waitForNavigation(opts = {}) {
2701
+ opts = {
2702
+ timeout: this.options.getPageTimeout,
2703
+ waitUntil: this.options.waitForNavigation,
2704
+ ...opts,
2705
+ };
2706
+ return this.page.waitForNavigation(opts);
2707
+ }
2708
+
2709
+ /**
2710
+ * Waits for a function to return true (waits for 1sec by default).
2711
+ *
2712
+ * ```js
2713
+ * I.waitUntil(() => window.requests == 0);
2714
+ * I.waitUntil(() => window.requests == 0, 5);
2715
+ * ```
2716
+ *
2717
+ * @param {function|string} fn function which is executed in browser context.
2718
+ * @param {number} [sec=1] (optional, `1` by default) time in seconds to wait
2719
+ * @param {string} [timeoutMsg=''] message to show in case of timeout fail.
2720
+ * @param {?number} [interval=null]
2721
+ */
2722
+ async waitUntil(fn, sec = null) {
2723
+ console.log('This method will remove in CodeceptJS 1.4; use `waitForFunction` instead!');
2724
+ const waitTimeout = sec ? sec * 1000 : this.options.waitForTimeout;
2725
+ const context = await this._getContext();
2726
+ return context.waitForFunction(fn, { timeout: waitTimeout });
2727
+ }
2728
+
2729
+ async waitUntilExists(locator, sec) {
2730
+ console.log(`waitUntilExists deprecated:
2731
+ * use 'waitForElement' to wait for element to be attached
2732
+ * use 'waitForDetached to wait for element to be removed'`);
2733
+ return this.waitForDetached(locator, sec);
2734
+ }
2735
+
2736
+ /**
2737
+ * Waits for an element to become not attached to the DOM on a page (by default waits for 1sec).
2738
+ * Element can be located by CSS or XPath.
2739
+ *
2740
+ * ```js
2741
+ * I.waitForDetached('#popup');
2742
+ * ```
2743
+ *
2744
+ * @param {CodeceptJS.LocatorOrString} locator element located by CSS|XPath|strict locator.
2745
+ * @param {number} [sec=1] (optional, `1` by default) time in seconds to wait
2746
+ */
2747
+ async waitForDetached(locator, sec) {
2748
+ const waitTimeout = sec ? sec * 1000 : this.options.waitForTimeout;
2749
+ locator = new Locator(locator, 'css');
2750
+
2751
+ let waiter;
2752
+ const context = await this._getContext();
2753
+ if (!locator.isXPath()) {
2754
+ waiter = context.waitForSelector(`${locator.isCustom() ? `${locator.type}=${locator.value}` : locator.simplify()}`, { timeout: waitTimeout, waitFor: 'detached' });
2755
+ } else {
2756
+ const visibleFn = function ([locator, $XPath]) {
2757
+ eval($XPath); // eslint-disable-line no-eval
2758
+ return $XPath(null, locator).length === 0;
2759
+ };
2760
+ waiter = context.waitForFunction(visibleFn, [locator.value, $XPath.toString()], { timeout: waitTimeout });
2761
+ }
2762
+ return waiter.catch((err) => {
2763
+ throw new Error(`element (${locator.toString()}) still on page after ${waitTimeout / 1000} sec\n${err.message}`);
2764
+ });
2765
+ }
2766
+
2767
+ async _waitForAction() {
2768
+ return this.wait(this.options.waitForAction / 1000);
2769
+ }
2770
+
2771
+ /**
2772
+ * Grab the data from performance timing using Navigation Timing API.
2773
+ * The returned data will contain following things in ms:
2774
+ * - responseEnd,
2775
+ * - domInteractive,
2776
+ * - domContentLoadedEventEnd,
2777
+ * - loadEventEnd
2778
+ * Resumes test execution, so **should be used inside an async function with `await`** operator.
2779
+ *
2780
+ * ```js
2781
+ * await I.amOnPage('https://example.com');
2782
+ * let data = await I.grabDataFromPerformanceTiming();
2783
+ * //Returned data
2784
+ * { // all results are in [ms]
2785
+ * responseEnd: 23,
2786
+ * domInteractive: 44,
2787
+ * domContentLoadedEventEnd: 196,
2788
+ * loadEventEnd: 241
2789
+ * }
2790
+ * ```
2791
+ */
2792
+ async grabDataFromPerformanceTiming() {
2793
+ return perfTiming;
2794
+ }
2795
+
2796
+ /**
2797
+ * Grab the width, height, location of given locator.
2798
+ * Provide `width` or `height`as second param to get your desired prop.
2799
+ * Resumes test execution, so **should be used inside an async function with `await`** operator.
2800
+ *
2801
+ * Returns an object with `x`, `y`, `width`, `height` keys.
2802
+ *
2803
+ * ```js
2804
+ * const value = await I.grabElementBoundingRect('h3');
2805
+ * // value is like { x: 226.5, y: 89, width: 527, height: 220 }
2806
+ * ```
2807
+ *
2808
+ * To get only one metric use second parameter:
2809
+ *
2810
+ * ```js
2811
+ * const width = await I.grabElementBoundingRect('h3', 'width');
2812
+ * // width == 527
2813
+ * ```
2814
+ * @param {string|object} locator element located by CSS|XPath|strict locator.
2815
+ * @param {string} elementSize x, y, width or height of the given element.
2816
+ * @returns {object} Element bounding rectangle
2817
+ */
2818
+ async grabElementBoundingRect(locator, prop) {
2819
+ const els = await this._locate(locator);
2820
+ assertElementExists(els, locator);
2821
+ const rect = await els[0].boundingBox();
2822
+ if (prop) return rect[prop];
2823
+ return rect;
2824
+ }
2825
+ }
2826
+
2827
+ module.exports = Playwright;
2828
+
2829
+ async function findElements(matcher, locator) {
2830
+ locator = new Locator(locator, 'css');
2831
+ if (locator.isCustom()) {
2832
+ return matcher.$$(`${locator.type}=${locator.value}`);
2833
+ } if (!locator.isXPath()) {
2834
+ return matcher.$$(locator.simplify());
2835
+ }
2836
+ return matcher.$$(`xpath=${locator.value}`);
2837
+ }
2838
+
2839
+ async function proceedClick(locator, context = null, options = {}) {
2840
+ let matcher = await this.context;
2841
+ if (context) {
2842
+ const els = await this._locate(context);
2843
+ assertElementExists(els, context);
2844
+ matcher = els[0];
2845
+ }
2846
+ const els = await findClickable.call(this, matcher, locator);
2847
+ if (context) {
2848
+ assertElementExists(els, locator, 'Clickable element', `was not found inside element ${new Locator(context).toString()}`);
2849
+ } else {
2850
+ assertElementExists(els, locator, 'Clickable element');
2851
+ }
2852
+ await els[0].click(options);
2853
+ const promises = [];
2854
+ if (options.waitForNavigation) {
2855
+ promises.push(this.waitForNavigation());
2856
+ }
2857
+ promises.push(this._waitForAction());
2858
+ return Promise.all(promises);
2859
+ }
2860
+
2861
+ async function findClickable(matcher, locator) {
2862
+ locator = new Locator(locator);
2863
+ if (!locator.isFuzzy()) return findElements.call(this, matcher, locator);
2864
+
2865
+ let els;
2866
+ const literal = xpathLocator.literal(locator.value);
2867
+
2868
+ els = await findElements.call(this, matcher, Locator.clickable.narrow(literal));
2869
+ if (els.length) return els;
2870
+
2871
+ els = await findElements.call(this, matcher, Locator.clickable.wide(literal));
2872
+ if (els.length) return els;
2873
+
2874
+ try {
2875
+ els = await findElements.call(this, matcher, Locator.clickable.self(literal));
2876
+ if (els.length) return els;
2877
+ } catch (err) {
2878
+ // Do nothing
2879
+ }
2880
+
2881
+ return findElements.call(this, matcher, locator.value); // by css or xpath
2882
+ }
2883
+
2884
+ async function proceedSee(assertType, text, context, strict = false) {
2885
+ let description;
2886
+ let allText;
2887
+ if (!context) {
2888
+ let el = await this.context;
2889
+
2890
+ if (el && !el.getProperty) {
2891
+ // Fallback to body
2892
+ el = await this.context.$('body');
2893
+ }
2894
+
2895
+ allText = [await el.getProperty('innerText').then(p => p.jsonValue())];
2896
+ description = 'web application';
2897
+ } else {
2898
+ const locator = new Locator(context, 'css');
2899
+ description = `element ${locator.toString()}`;
2900
+ const els = await this._locate(locator);
2901
+ assertElementExists(els, locator.toString());
2902
+ allText = await Promise.all(els.map(el => el.getProperty('innerText').then(p => p.jsonValue())));
2903
+ }
2904
+
2905
+ if (strict) {
2906
+ return allText.map(elText => equals(description)[assertType](text, elText));
2907
+ }
2908
+ return stringIncludes(description)[assertType](text, allText.join(' | '));
2909
+ }
2910
+
2911
+ async function findCheckable(locator, context) {
2912
+ let contextEl = await this.context;
2913
+ if (typeof context === 'string') {
2914
+ contextEl = await findElements.call(this, contextEl, (new Locator(context, 'css')).simplify());
2915
+ contextEl = contextEl[0];
2916
+ }
2917
+
2918
+ const matchedLocator = new Locator(locator);
2919
+ if (!matchedLocator.isFuzzy()) {
2920
+ return findElements.call(this, contextEl, matchedLocator.simplify());
2921
+ }
2922
+
2923
+ const literal = xpathLocator.literal(locator);
2924
+ let els = await findElements.call(this, contextEl, Locator.checkable.byText(literal));
2925
+ if (els.length) {
2926
+ return els;
2927
+ }
2928
+ els = await findElements.call(this, contextEl, Locator.checkable.byName(literal));
2929
+ if (els.length) {
2930
+ return els;
2931
+ }
2932
+ return findElements.call(this, contextEl, locator);
2933
+ }
2934
+
2935
+ async function proceedIsChecked(assertType, option) {
2936
+ let els = await findCheckable.call(this, option);
2937
+ assertElementExists(els, option, 'Checkable');
2938
+ els = await Promise.all(els.map(el => el.getProperty('checked')));
2939
+ els = await Promise.all(els.map(el => el.jsonValue()));
2940
+ const selected = els.reduce((prev, cur) => prev || cur);
2941
+ return truth(`checkable ${option}`, 'to be checked')[assertType](selected);
2942
+ }
2943
+
2944
+ async function findFields(locator) {
2945
+ const matchedLocator = new Locator(locator);
2946
+ if (!matchedLocator.isFuzzy()) {
2947
+ return this._locate(matchedLocator);
2948
+ }
2949
+ const literal = xpathLocator.literal(locator);
2950
+
2951
+ let els = await this._locate({ xpath: Locator.field.labelEquals(literal) });
2952
+ if (els.length) {
2953
+ return els;
2954
+ }
2955
+
2956
+ els = await this._locate({ xpath: Locator.field.labelContains(literal) });
2957
+ if (els.length) {
2958
+ return els;
2959
+ }
2960
+ els = await this._locate({ xpath: Locator.field.byName(literal) });
2961
+ if (els.length) {
2962
+ return els;
2963
+ }
2964
+ return this._locate({ css: locator });
2965
+ }
2966
+
2967
+ async function proceedDragAndDrop(sourceLocator, destinationLocator, options = {}) {
2968
+ const src = await this._locate(sourceLocator);
2969
+ assertElementExists(src, sourceLocator, 'Source Element');
2970
+
2971
+ const dst = await this._locate(destinationLocator);
2972
+ assertElementExists(dst, destinationLocator, 'Destination Element');
2973
+
2974
+ // Note: Using private api ._clickablePoint becaues the .BoundingBox does not take into account iframe offsets!
2975
+ const dragSource = await src[0]._clickablePoint();
2976
+ const dragDestination = await dst[0]._clickablePoint();
2977
+
2978
+ // Drag start point
2979
+ await this.page.mouse.move(dragSource.x, dragSource.y, { steps: 5 });
2980
+ await this.page.mouse.down();
2981
+
2982
+ // Drag destination
2983
+ await this.page.mouse.move(dragDestination.x, dragDestination.y, { steps: 5 });
2984
+ await this.page.mouse.up();
2985
+ await this._waitForAction();
2986
+ }
2987
+
2988
+ async function proceedSeeInField(assertType, field, value) {
2989
+ const els = await findFields.call(this, field);
2990
+ assertElementExists(els, field, 'Field');
2991
+ const el = els[0];
2992
+ const tag = await el.getProperty('tagName').then(el => el.jsonValue());
2993
+ const fieldType = await el.getProperty('type').then(el => el.jsonValue());
2994
+
2995
+ const proceedMultiple = async (elements) => {
2996
+ const fields = Array.isArray(elements) ? elements : [elements];
2997
+
2998
+ const elementValues = [];
2999
+ for (const element of fields) {
3000
+ elementValues.push(await element.getProperty('value').then(el => el.jsonValue()));
3001
+ }
3002
+
3003
+ if (typeof value === 'boolean') {
3004
+ equals(`no. of items matching > 0: ${field}`)[assertType](value, !!elementValues.length);
3005
+ } else {
3006
+ if (assertType === 'assert') {
3007
+ equals(`select option by ${field}`)[assertType](true, elementValues.length > 0);
3008
+ }
3009
+ elementValues.forEach(val => stringIncludes(`fields by ${field}`)[assertType](value, val));
3010
+ }
3011
+ };
3012
+
3013
+ if (tag === 'SELECT') {
3014
+ const selectedOptions = await el.$$('option:checked');
3015
+ // locate option by values and check them
3016
+ if (value === '') {
3017
+ return proceedMultiple(selectedOptions);
3018
+ }
3019
+
3020
+ const options = await filterFieldsByValue(selectedOptions, value, true);
3021
+ return proceedMultiple(options);
3022
+ }
3023
+
3024
+ if (tag === 'INPUT') {
3025
+ if (fieldType === 'checkbox' || fieldType === 'radio') {
3026
+ if (typeof value === 'boolean') {
3027
+ // Filter by values
3028
+ const options = await filterFieldsBySelectionState(els, true);
3029
+ return proceedMultiple(options);
3030
+ }
3031
+
3032
+ const options = await filterFieldsByValue(els, value, true);
3033
+ return proceedMultiple(options);
3034
+ }
3035
+ return proceedMultiple(els[0]);
3036
+ }
3037
+ const fieldVal = await el.getProperty('value').then(el => el.jsonValue());
3038
+ return stringIncludes(`fields by ${field}`)[assertType](value, fieldVal);
3039
+ }
3040
+
3041
+ async function filterFieldsByValue(elements, value, onlySelected) {
3042
+ const matches = [];
3043
+ for (const element of elements) {
3044
+ const val = await element.getProperty('value').then(el => el.jsonValue());
3045
+ let isSelected = true;
3046
+ if (onlySelected) {
3047
+ isSelected = await elementSelected(element);
3048
+ }
3049
+ if ((value == null || val.indexOf(value) > -1) && isSelected) {
3050
+ matches.push(element);
3051
+ }
3052
+ }
3053
+ return matches;
3054
+ }
3055
+
3056
+ async function filterFieldsBySelectionState(elements, state) {
3057
+ const matches = [];
3058
+ for (const element of elements) {
3059
+ const isSelected = await elementSelected(element);
3060
+ if (isSelected === state) {
3061
+ matches.push(element);
3062
+ }
3063
+ }
3064
+ return matches;
3065
+ }
3066
+
3067
+ async function elementSelected(element) {
3068
+ const type = await element.getProperty('type').then(el => el.jsonValue());
3069
+
3070
+ if (type === 'checkbox' || type === 'radio') {
3071
+ return element.getProperty('checked').then(el => el.jsonValue());
3072
+ }
3073
+ return element.getProperty('selected').then(el => el.jsonValue());
3074
+ }
3075
+
3076
+ function isFrameLocator(locator) {
3077
+ locator = new Locator(locator);
3078
+ if (locator.isFrame()) return locator.value;
3079
+ return false;
3080
+ }
3081
+
3082
+
3083
+ function assertElementExists(res, locator, prefix, suffix) {
3084
+ if (!res || res.length === 0) {
3085
+ throw new ElementNotFound(locator, prefix, suffix);
3086
+ }
3087
+ }
3088
+
3089
+ function $XPath(element, selector) {
3090
+ const found = document.evaluate(selector, element || document.body, null, 5, null);
3091
+ const res = [];
3092
+ let current = null;
3093
+ while (current = found.iterateNext()) {
3094
+ res.push(current);
3095
+ }
3096
+ return res;
3097
+ }
3098
+
3099
+ async function targetCreatedHandler(page) {
3100
+ if (!page) return;
3101
+ this.withinLocator = null;
3102
+ page.on('load', (frame) => {
3103
+ page.$('body')
3104
+ .catch(() => null)
3105
+ .then(context => this.context = context);
3106
+ });
3107
+ page.on('console', (msg) => {
3108
+ this.debugSection(`Browser:${ucfirst(msg.type())}`, (msg._text || '') + msg.args().join(' '));
3109
+ consoleLogStore.add(msg);
3110
+ });
3111
+
3112
+ if (this.options.userAgent) {
3113
+ await page.setUserAgent(this.options.userAgent);
3114
+ }
3115
+ if (this.options.windowSize && this.options.windowSize.indexOf('x') > 0) {
3116
+ const dimensions = this.options.windowSize.split('x');
3117
+ const width = parseInt(dimensions[0], 10);
3118
+ const height = parseInt(dimensions[1], 10);
3119
+ await page.setViewportSize({ width, height });
3120
+ }
3121
+ }
3122
+
3123
+ // List of key values to key definitions
3124
+ // https://github.com/GoogleChrome/Playwright/blob/v1.20.0/lib/USKeyboardLayout.js
3125
+ const keyDefinitionMap = {
3126
+ /* eslint-disable quote-props */
3127
+ '0': 'Digit0',
3128
+ '1': 'Digit1',
3129
+ '2': 'Digit2',
3130
+ '3': 'Digit3',
3131
+ '4': 'Digit4',
3132
+ '5': 'Digit5',
3133
+ '6': 'Digit6',
3134
+ '7': 'Digit7',
3135
+ '8': 'Digit8',
3136
+ '9': 'Digit9',
3137
+ 'a': 'KeyA',
3138
+ 'b': 'KeyB',
3139
+ 'c': 'KeyC',
3140
+ 'd': 'KeyD',
3141
+ 'e': 'KeyE',
3142
+ 'f': 'KeyF',
3143
+ 'g': 'KeyG',
3144
+ 'h': 'KeyH',
3145
+ 'i': 'KeyI',
3146
+ 'j': 'KeyJ',
3147
+ 'k': 'KeyK',
3148
+ 'l': 'KeyL',
3149
+ 'm': 'KeyM',
3150
+ 'n': 'KeyN',
3151
+ 'o': 'KeyO',
3152
+ 'p': 'KeyP',
3153
+ 'q': 'KeyQ',
3154
+ 'r': 'KeyR',
3155
+ 's': 'KeyS',
3156
+ 't': 'KeyT',
3157
+ 'u': 'KeyU',
3158
+ 'v': 'KeyV',
3159
+ 'w': 'KeyW',
3160
+ 'x': 'KeyX',
3161
+ 'y': 'KeyY',
3162
+ 'z': 'KeyZ',
3163
+ ';': 'Semicolon',
3164
+ '=': 'Equal',
3165
+ ',': 'Comma',
3166
+ '-': 'Minus',
3167
+ '.': 'Period',
3168
+ '/': 'Slash',
3169
+ '`': 'Backquote',
3170
+ '[': 'BracketLeft',
3171
+ '\\': 'Backslash',
3172
+ ']': 'BracketRight',
3173
+ '\'': 'Quote',
3174
+ /* eslint-enable quote-props */
3175
+ };
3176
+
3177
+ function getNormalizedKey(key) {
3178
+ const normalizedKey = getNormalizedKeyAttributeValue(key);
3179
+ if (key !== normalizedKey) {
3180
+ this.debugSection('Input', `Mapping key '${key}' to '${normalizedKey}'`);
3181
+ }
3182
+ // Use key definition to ensure correct key is displayed when Shift modifier is active
3183
+ if (Object.prototype.hasOwnProperty.call(keyDefinitionMap, normalizedKey)) {
3184
+ return keyDefinitionMap[normalizedKey];
3185
+ }
3186
+ return normalizedKey;
3187
+ }