codeceptjs 3.6.0-beta.1.ai-healers → 3.6.1

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 (130) hide show
  1. package/README.md +2 -2
  2. package/bin/codecept.js +2 -1
  3. package/docs/webapi/dontSeeTraffic.mustache +13 -0
  4. package/docs/webapi/flushNetworkTraffics.mustache +5 -0
  5. package/docs/webapi/grabRecordedNetworkTraffics.mustache +10 -0
  6. package/docs/webapi/seeTraffic.mustache +36 -0
  7. package/docs/webapi/startRecordingTraffic.mustache +8 -0
  8. package/docs/webapi/startRecordingWebSocketMessages.mustache +8 -0
  9. package/docs/webapi/stopRecordingTraffic.mustache +5 -0
  10. package/docs/webapi/stopRecordingWebSocketMessages.mustache +7 -0
  11. package/docs/webapi/waitForCookie.mustache +9 -0
  12. package/lib/actor.js +6 -3
  13. package/lib/command/dryRun.js +44 -13
  14. package/lib/helper/Appium.js +36 -12
  15. package/lib/helper/Expect.js +11 -8
  16. package/lib/helper/JSONResponse.js +8 -8
  17. package/lib/helper/MockServer.js +221 -0
  18. package/lib/helper/Playwright.js +107 -371
  19. package/lib/helper/Puppeteer.js +404 -71
  20. package/lib/helper/REST.js +4 -1
  21. package/lib/helper/WebDriver.js +189 -13
  22. package/lib/helper/errors/ElementAssertion.js +38 -0
  23. package/lib/helper/extras/PlaywrightReactVueLocator.js +6 -1
  24. package/lib/helper/network/actions.js +123 -0
  25. package/lib/helper/network/utils.js +187 -0
  26. package/lib/locator.js +36 -5
  27. package/lib/pause.js +4 -9
  28. package/lib/plugin/coverage.js +112 -99
  29. package/lib/step.js +3 -1
  30. package/package.json +49 -38
  31. package/typings/index.d.ts +19 -2
  32. package/typings/promiseBasedTypes.d.ts +505 -41
  33. package/typings/types.d.ts +531 -43
  34. package/docs/advanced.md +0 -351
  35. package/docs/ai.md +0 -365
  36. package/docs/api.md +0 -323
  37. package/docs/basics.md +0 -979
  38. package/docs/bdd.md +0 -539
  39. package/docs/best.md +0 -237
  40. package/docs/books.md +0 -37
  41. package/docs/bootstrap.md +0 -135
  42. package/docs/build/AI.js +0 -124
  43. package/docs/build/ApiDataFactory.js +0 -410
  44. package/docs/build/Appium.js +0 -2027
  45. package/docs/build/Expect.js +0 -422
  46. package/docs/build/FileSystem.js +0 -228
  47. package/docs/build/GraphQL.js +0 -229
  48. package/docs/build/GraphQLDataFactory.js +0 -309
  49. package/docs/build/JSONResponse.js +0 -338
  50. package/docs/build/Mochawesome.js +0 -71
  51. package/docs/build/Nightmare.js +0 -2152
  52. package/docs/build/OpenAI.js +0 -126
  53. package/docs/build/Playwright.js +0 -5110
  54. package/docs/build/Protractor.js +0 -2706
  55. package/docs/build/Puppeteer.js +0 -3905
  56. package/docs/build/REST.js +0 -344
  57. package/docs/build/TestCafe.js +0 -2125
  58. package/docs/build/WebDriver.js +0 -4240
  59. package/docs/changelog.md +0 -2572
  60. package/docs/commands.md +0 -266
  61. package/docs/community-helpers.md +0 -58
  62. package/docs/configuration.md +0 -157
  63. package/docs/continuous-integration.md +0 -22
  64. package/docs/custom-helpers.md +0 -306
  65. package/docs/data.md +0 -379
  66. package/docs/detox.md +0 -235
  67. package/docs/docker.md +0 -136
  68. package/docs/email.md +0 -183
  69. package/docs/examples.md +0 -149
  70. package/docs/heal.md +0 -186
  71. package/docs/helpers/ApiDataFactory.md +0 -266
  72. package/docs/helpers/Appium.md +0 -1374
  73. package/docs/helpers/Detox.md +0 -586
  74. package/docs/helpers/Expect.md +0 -275
  75. package/docs/helpers/FileSystem.md +0 -152
  76. package/docs/helpers/GraphQL.md +0 -151
  77. package/docs/helpers/GraphQLDataFactory.md +0 -226
  78. package/docs/helpers/JSONResponse.md +0 -254
  79. package/docs/helpers/Mochawesome.md +0 -8
  80. package/docs/helpers/MockRequest.md +0 -377
  81. package/docs/helpers/Nightmare.md +0 -1305
  82. package/docs/helpers/OpenAI.md +0 -70
  83. package/docs/helpers/Playwright.md +0 -2759
  84. package/docs/helpers/Polly.md +0 -44
  85. package/docs/helpers/Protractor.md +0 -1769
  86. package/docs/helpers/Puppeteer-firefox.md +0 -86
  87. package/docs/helpers/Puppeteer.md +0 -2317
  88. package/docs/helpers/REST.md +0 -218
  89. package/docs/helpers/TestCafe.md +0 -1321
  90. package/docs/helpers/WebDriver.md +0 -2547
  91. package/docs/hooks.md +0 -340
  92. package/docs/index.md +0 -111
  93. package/docs/installation.md +0 -75
  94. package/docs/internal-api.md +0 -266
  95. package/docs/locators.md +0 -339
  96. package/docs/mobile-react-native-locators.md +0 -67
  97. package/docs/mobile.md +0 -338
  98. package/docs/pageobjects.md +0 -291
  99. package/docs/parallel.md +0 -400
  100. package/docs/playwright.md +0 -632
  101. package/docs/plugins.md +0 -1247
  102. package/docs/puppeteer.md +0 -316
  103. package/docs/quickstart.md +0 -162
  104. package/docs/react.md +0 -70
  105. package/docs/reports.md +0 -392
  106. package/docs/secrets.md +0 -36
  107. package/docs/shadow.md +0 -68
  108. package/docs/shared/keys.mustache +0 -31
  109. package/docs/shared/react.mustache +0 -1
  110. package/docs/testcafe.md +0 -174
  111. package/docs/translation.md +0 -247
  112. package/docs/tutorial.md +0 -271
  113. package/docs/typescript.md +0 -180
  114. package/docs/ui.md +0 -59
  115. package/docs/videos.md +0 -28
  116. package/docs/visual.md +0 -202
  117. package/docs/vue.md +0 -143
  118. package/docs/webdriver.md +0 -701
  119. package/docs/wiki/Books-&-Posts.md +0 -27
  120. package/docs/wiki/Community-Helpers-&-Plugins.md +0 -53
  121. package/docs/wiki/Converting-Playwright-to-Istanbul-Coverage.md +0 -61
  122. package/docs/wiki/Examples.md +0 -145
  123. package/docs/wiki/Google-Summer-of-Code-(GSoC)-2020.md +0 -68
  124. package/docs/wiki/Home.md +0 -16
  125. package/docs/wiki/Migration-to-Appium-v2---CodeceptJS.md +0 -83
  126. package/docs/wiki/Release-Process.md +0 -24
  127. package/docs/wiki/Roadmap.md +0 -23
  128. package/docs/wiki/Tests.md +0 -1393
  129. package/docs/wiki/Upgrading-to-CodeceptJS-3.md +0 -153
  130. package/docs/wiki/Videos.md +0 -19
@@ -1,3905 +0,0 @@
1
- const axios = require('axios');
2
- const fs = require('fs');
3
- const fsExtra = require('fs-extra');
4
- const path = require('path');
5
-
6
- const Helper = require('@codeceptjs/helper');
7
- const { v4: uuidv4 } = require('uuid');
8
- const Locator = require('../locator');
9
- const recorder = require('../recorder');
10
- const store = require('../store');
11
- const stringIncludes = require('../assert/include').includes;
12
- const { urlEquals } = require('../assert/equal');
13
- const { equals } = require('../assert/equal');
14
- const { empty } = require('../assert/empty');
15
- const { truth } = require('../assert/truth');
16
- const isElementClickable = require('./scripts/isElementClickable');
17
- const {
18
- xpathLocator,
19
- ucfirst,
20
- fileExists,
21
- chunkArray,
22
- toCamelCase,
23
- clearString,
24
- convertCssPropertiesToCamelCase,
25
- screenshotOutputFolder,
26
- getNormalizedKeyAttributeValue,
27
- isModifierKey,
28
- requireWithFallback, normalizeSpacesInString,
29
- } = require('../utils');
30
- const {
31
- isColorProperty,
32
- convertColorToRGBA,
33
- } = require('../colorUtils');
34
- const ElementNotFound = require('./errors/ElementNotFound');
35
- const RemoteBrowserConnectionRefused = require('./errors/RemoteBrowserConnectionRefused');
36
- const Popup = require('./extras/Popup');
37
- const Console = require('./extras/Console');
38
- const findReact = require('./extras/React');
39
- const { highlightElement } = require('./scripts/highlightElement');
40
- const { blurElement } = require('./scripts/blurElement');
41
- const { focusElement } = require('./scripts/focusElement');
42
-
43
- let puppeteer;
44
- let perfTiming;
45
- const popupStore = new Popup();
46
- const consoleLogStore = new Console();
47
-
48
- /**
49
- * ## Configuration
50
- *
51
- * This helper should be configured in codecept.conf.js
52
- *
53
- * @typedef PuppeteerConfig
54
- * @type {object}
55
- * @prop {string} url - base url of website to be tested
56
- * @prop {object} [basicAuth] (optional) the basic authentication to pass to base url. Example: {username: 'username', password: 'password'}
57
- * @prop {boolean} [show] - show Google Chrome window for debug.
58
- * @prop {boolean} [restart=true] - restart browser between tests.
59
- * @prop {boolean} [disableScreenshots=false] - don't save screenshot on failure.
60
- * @prop {boolean} [fullPageScreenshots=false] - make full page screenshots on failure.
61
- * @prop {boolean} [uniqueScreenshotNames=false] - option to prevent screenshot override if you have scenarios with the same name in different suites.
62
- * @prop {boolean} [trace=false] - record [tracing information](https://pptr.dev/api/puppeteer.tracing) with screenshots.
63
- * @prop {boolean} [keepTraceForPassedTests=false] - save trace for passed tests.
64
- * @prop {boolean} [keepBrowserState=false] - keep browser state between tests when `restart` is set to false.
65
- * @prop {boolean} [keepCookies=false] - keep cookies between tests when `restart` is set to false.
66
- * @prop {number} [waitForAction=100] - how long to wait after click, doubleClick or PressKey actions in ms. Default: 100.
67
- * @prop {string} [waitForNavigation=load] - when to consider navigation succeeded. Possible options: `load`, `domcontentloaded`, `networkidle0`, `networkidle2`. See [Puppeteer API](https://github.com/GoogleChrome/puppeteer/blob/master/docs/api.md#pagewaitfornavigationoptions). Array values are accepted as well.
68
- * @prop {number} [pressKeyDelay=10] - delay between key presses in ms. Used when calling Puppeteers page.type(...) in fillField/appendField
69
- * @prop {number} [getPageTimeout=30000] - config option to set maximum navigation time in milliseconds. If the timeout is set to 0, then timeout will be disabled.
70
- * @prop {number} [waitForTimeout=1000] - default wait* timeout in ms.
71
- * @prop {string} [windowSize] - default window size. Set a dimension in format WIDTHxHEIGHT like `640x480`.
72
- * @prop {string} [userAgent] - user-agent string.
73
- * @prop {boolean} [manualStart=false] - do not start browser before a test, start it manually inside a helper with `this.helpers["Puppeteer"]._startBrowser()`.
74
- * @prop {string} [browser=chrome] - can be changed to `firefox` when using [puppeteer-firefox](https://codecept.io/helpers/Puppeteer-firefox).
75
- * @prop {object} [chrome] - pass additional [Puppeteer run options](https://github.com/GoogleChrome/puppeteer/blob/master/docs/api.md#puppeteerlaunchoptions).
76
- * @prop {boolean} [highlightElement] - highlight the interacting elements. Default: false. Note: only activate under verbose mode (--verbose).
77
- */
78
- const config = {};
79
-
80
- /**
81
- * Uses [Google Chrome's Puppeteer](https://github.com/GoogleChrome/puppeteer) library to run tests inside headless Chrome.
82
- * Browser control is executed via DevTools Protocol (instead of Selenium).
83
- * This helper works with a browser out of the box with no additional tools required to install.
84
- *
85
- * Requires `puppeteer` or `puppeteer-core` package to be installed.
86
- * ```
87
- * npm i puppeteer --save
88
- * ```
89
- * or
90
- * ```
91
- * npm i puppeteer-core --save
92
- * ```
93
- * Using `puppeteer-core` package, will prevent the download of browser binaries and allow connecting to an existing browser installation or for connecting to a remote one.
94
- *
95
- * > Experimental Firefox support [can be activated](https://codecept.io/helpers/Puppeteer-firefox).
96
- *
97
- * <!-- configuration -->
98
- *
99
- * #### Trace Recording Customization
100
- *
101
- * Trace recording provides complete information on test execution and includes screenshots, and network requests logged during run.
102
- * Traces will be saved to `output/trace`
103
- *
104
- * * `trace`: enables trace recording for failed tests; trace are saved into `output/trace` folder
105
- * * `keepTraceForPassedTests`: - save trace for passed tests
106
- *
107
- * #### Example #1: Wait for 0 network connections.
108
- *
109
- * ```js
110
- * {
111
- * helpers: {
112
- * Puppeteer : {
113
- * url: "http://localhost",
114
- * restart: false,
115
- * waitForNavigation: "networkidle0",
116
- * waitForAction: 500
117
- * }
118
- * }
119
- * }
120
- * ```
121
- *
122
- * #### Example #2: Wait for DOMContentLoaded event and 0 network connections
123
- *
124
- * ```js
125
- * {
126
- * helpers: {
127
- * Puppeteer : {
128
- * url: "http://localhost",
129
- * restart: false,
130
- * waitForNavigation: [ "domcontentloaded", "networkidle0" ],
131
- * waitForAction: 500
132
- * }
133
- * }
134
- * }
135
- * ```
136
- *
137
- * #### Example #3: Debug in window mode
138
- *
139
- * ```js
140
- * {
141
- * helpers: {
142
- * Puppeteer : {
143
- * url: "http://localhost",
144
- * show: true
145
- * }
146
- * }
147
- * }
148
- * ```
149
- *
150
- * #### Example #4: Connect to remote browser by specifying [websocket endpoint](https://chromedevtools.github.io/devtools-protocol/#how-do-i-access-the-browser-target)
151
- *
152
- * ```js
153
- * {
154
- * helpers: {
155
- * Puppeteer: {
156
- * url: "http://localhost",
157
- * chrome: {
158
- * browserWSEndpoint: "ws://localhost:9222/devtools/browser/c5aa6160-b5bc-4d53-bb49-6ecb36cd2e0a"
159
- * }
160
- * }
161
- * }
162
- * }
163
- * ```
164
- * > Note: When connecting to remote browser `show` and specific `chrome` options (e.g. `headless` or `devtools`) are ignored.
165
- *
166
- * #### Example #5: Target URL with provided basic authentication
167
- *
168
- * ```js
169
- * {
170
- * helpers: {
171
- * Puppeteer : {
172
- * url: 'http://localhost',
173
- * basicAuth: {username: 'username', password: 'password'},
174
- * show: true
175
- * }
176
- * }
177
- * }
178
- * ```
179
- * #### Troubleshooting
180
- *
181
- * Error Message: `No usable sandbox!`
182
- *
183
- * When running Puppeteer on CI try to disable sandbox if you see that message
184
- *
185
- * ```
186
- * helpers: {
187
- * Puppeteer: {
188
- * url: 'http://localhost',
189
- * show: false,
190
- * chrome: {
191
- * args: ['--no-sandbox', '--disable-setuid-sandbox']
192
- * }
193
- * },
194
- * }
195
- * ```
196
- *
197
- *
198
- *
199
- * ## Access From Helpers
200
- *
201
- * Receive Puppeteer client from a custom helper by accessing `browser` for the Browser object or `page` for the current Page object:
202
- *
203
- * ```js
204
- * const { browser } = this.helpers.Puppeteer;
205
- * await browser.pages(); // List of pages in the browser
206
- *
207
- * const { page } = this.helpers.Puppeteer;
208
- * await page.url(); // Get the url of the current page
209
- * ```
210
- *
211
- * ## Methods
212
- */
213
- class Puppeteer extends Helper {
214
- constructor(config) {
215
- super(config);
216
-
217
- puppeteer = requireWithFallback('puppeteer', 'puppeteer-core');
218
- // set defaults
219
- this.isRemoteBrowser = false;
220
- this.isRunning = false;
221
- this.isAuthenticated = false;
222
- this.sessionPages = {};
223
- this.activeSessionName = '';
224
-
225
- // override defaults with config
226
- this._setConfig(config);
227
- }
228
-
229
- _validateConfig(config) {
230
- const defaults = {
231
- browser: 'chrome',
232
- waitForAction: 100,
233
- waitForTimeout: 1000,
234
- pressKeyDelay: 10,
235
- fullPageScreenshots: false,
236
- disableScreenshots: false,
237
- uniqueScreenshotNames: false,
238
- manualStart: false,
239
- getPageTimeout: 30000,
240
- waitForNavigation: 'load',
241
- restart: true,
242
- keepCookies: false,
243
- keepBrowserState: false,
244
- show: false,
245
- defaultPopupAction: 'accept',
246
- highlightElement: false,
247
- };
248
-
249
- return Object.assign(defaults, config);
250
- }
251
-
252
- _getOptions(config) {
253
- return config.browser === 'firefox' ? Object.assign(this.options.firefox, { product: 'firefox' }) : this.options.chrome;
254
- }
255
-
256
- _setConfig(config) {
257
- this.options = this._validateConfig(config);
258
- this.puppeteerOptions = {
259
- headless: !this.options.show,
260
- ...this._getOptions(config),
261
- };
262
- if (this.puppeteerOptions.headless) this.puppeteerOptions.headless = 'new';
263
- this.isRemoteBrowser = !!this.puppeteerOptions.browserWSEndpoint;
264
- popupStore.defaultAction = this.options.defaultPopupAction;
265
- }
266
-
267
- static _config() {
268
- return [
269
- { name: 'url', message: 'Base url of site to be tested', default: 'http://localhost' },
270
- {
271
- name: 'show', message: 'Show browser window', default: true, type: 'confirm',
272
- },
273
- {
274
- name: 'windowSize', message: 'Browser viewport size', default: '1200x900',
275
- },
276
- ];
277
- }
278
-
279
- static _checkRequirements() {
280
- try {
281
- requireWithFallback('puppeteer', 'puppeteer-core');
282
- } catch (e) {
283
- return ['puppeteer'];
284
- }
285
- }
286
-
287
- _init() {
288
- }
289
-
290
- _beforeSuite() {
291
- if (!this.options.restart && !this.options.manualStart && !this.isRunning) {
292
- this.debugSection('Session', 'Starting singleton browser session');
293
- return this._startBrowser();
294
- }
295
- }
296
-
297
- async _before(test) {
298
- this.sessionPages = {};
299
- this.currentRunningTest = test;
300
- recorder.retry({
301
- retries: process.env.FAILED_STEP_RETRIES || 3,
302
- when: err => {
303
- if (!err || typeof (err.message) !== 'string') {
304
- return false;
305
- }
306
- // ignore context errors
307
- return err.message.includes('context');
308
- },
309
- });
310
- if (this.options.restart && !this.options.manualStart) return this._startBrowser();
311
- if (!this.isRunning && !this.options.manualStart) return this._startBrowser();
312
- return this.browser;
313
- }
314
-
315
- async _after() {
316
- if (!this.isRunning) return;
317
-
318
- // close other sessions
319
- const contexts = this.browser.browserContexts();
320
- const defaultCtx = contexts.shift();
321
-
322
- await Promise.all(contexts.map(c => c.close()));
323
-
324
- if (this.options.restart) {
325
- this.isRunning = false;
326
- return this._stopBrowser();
327
- }
328
-
329
- // ensure this.page is from default context
330
- if (this.page) {
331
- const existingPages = defaultCtx.targets().filter(t => t.type() === 'page');
332
- await this._setPage(await existingPages[0].page());
333
- }
334
-
335
- if (this.options.keepBrowserState) return;
336
-
337
- if (!this.options.keepCookies) {
338
- this.debugSection('Session', 'cleaning cookies and localStorage');
339
- await this.clearCookie();
340
- }
341
- const currentUrl = await this.grabCurrentUrl();
342
-
343
- if (currentUrl.startsWith('http')) {
344
- await this.executeScript('localStorage.clear();').catch((err) => {
345
- if (!(err.message.indexOf("Storage is disabled inside 'data:' URLs.") > -1)) throw err;
346
- });
347
- await this.executeScript('sessionStorage.clear();').catch((err) => {
348
- if (!(err.message.indexOf("Storage is disabled inside 'data:' URLs.") > -1)) throw err;
349
- });
350
- }
351
- await this.closeOtherTabs();
352
- return this.browser;
353
- }
354
-
355
- _afterSuite() {
356
- }
357
-
358
- _finishTest() {
359
- if (!this.options.restart && this.isRunning) return this._stopBrowser();
360
- }
361
-
362
- _session() {
363
- return {
364
- start: async (name = '') => {
365
- this.debugSection('Incognito Tab', 'opened');
366
- this.activeSessionName = name;
367
-
368
- const bc = await this.browser.createIncognitoBrowserContext();
369
- await bc.newPage();
370
-
371
- // Create a new page inside context.
372
- return bc;
373
- },
374
- stop: async () => {
375
- // is closed by _after
376
- },
377
- loadVars: async (context) => {
378
- const existingPages = context.targets().filter(t => t.type() === 'page');
379
- this.sessionPages[this.activeSessionName] = await existingPages[0].page();
380
- return this._setPage(this.sessionPages[this.activeSessionName]);
381
- },
382
- restoreVars: async (session) => {
383
- this.withinLocator = null;
384
-
385
- if (!session) {
386
- this.activeSessionName = '';
387
- } else {
388
- this.activeSessionName = session;
389
- }
390
- const defaultCtx = this.browser.defaultBrowserContext();
391
- const existingPages = defaultCtx.targets().filter(t => t.type() === 'page');
392
- await this._setPage(await existingPages[0].page());
393
-
394
- return this._waitForAction();
395
- },
396
- };
397
- }
398
-
399
- /**
400
- * Use Puppeteer API inside a test.
401
- *
402
- * First argument is a description of an action.
403
- * Second argument is async function that gets this helper as parameter.
404
- *
405
- * { [`page`](https://github.com/puppeteer/puppeteer/blob/master/docs/api.md#class-page), [`browser`](https://github.com/puppeteer/puppeteer/blob/master/docs/api.md#class-browser) } from Puppeteer API are available.
406
- *
407
- * ```js
408
- * I.usePuppeteerTo('emulate offline mode', async ({ page }) {
409
- * await page.setOfflineMode(true);
410
- * });
411
- * ```
412
- *
413
- * @param {string} description used to show in logs.
414
- * @param {function} fn async function that is executed with Puppeteer as argument
415
- */
416
- usePuppeteerTo(description, fn) {
417
- return this._useTo(...arguments);
418
- }
419
-
420
- /**
421
- * Set the automatic popup response to Accept.
422
- * This must be set before a popup is triggered.
423
- *
424
- * ```js
425
- * I.amAcceptingPopups();
426
- * I.click('#triggerPopup');
427
- * I.acceptPopup();
428
- * ```
429
- */
430
- amAcceptingPopups() {
431
- popupStore.actionType = 'accept';
432
- }
433
-
434
- /**
435
- * Accepts the active JavaScript native popup window, as created by window.alert|window.confirm|window.prompt.
436
- * Don't confuse popups with modal windows, as created by [various
437
- * libraries](http://jster.net/category/windows-modals-popups).
438
- */
439
- acceptPopup() {
440
- popupStore.assertPopupActionType('accept');
441
- }
442
-
443
- /**
444
- * Set the automatic popup response to Cancel/Dismiss.
445
- * This must be set before a popup is triggered.
446
- *
447
- * ```js
448
- * I.amCancellingPopups();
449
- * I.click('#triggerPopup');
450
- * I.cancelPopup();
451
- * ```
452
- */
453
- amCancellingPopups() {
454
- popupStore.actionType = 'cancel';
455
- }
456
-
457
- /**
458
- * Dismisses the active JavaScript popup, as created by window.alert|window.confirm|window.prompt.
459
- */
460
- cancelPopup() {
461
- popupStore.assertPopupActionType('cancel');
462
- }
463
-
464
- /**
465
- * Checks that the active JavaScript popup, as created by `window.alert|window.confirm|window.prompt`, contains the
466
- * given string.
467
- *
468
- * ```js
469
- * I.seeInPopup('Popup text');
470
- * ```
471
- * @param {string} text value to check.
472
- * @returns {void} automatically synchronized promise through #recorder
473
- *
474
- */
475
- async seeInPopup(text) {
476
- popupStore.assertPopupVisible();
477
- const popupText = await popupStore.popup.message();
478
- stringIncludes('text in popup').assert(text, popupText);
479
- }
480
-
481
- /**
482
- * Set current page
483
- * @param {object} page page to set
484
- */
485
- async _setPage(page) {
486
- page = await page;
487
- this._addPopupListener(page);
488
- this._addErrorListener(page);
489
- this.page = page;
490
- if (!page) return;
491
- page.setDefaultNavigationTimeout(this.options.getPageTimeout);
492
- this.context = await this.page.$('body');
493
- if (this.config.browser === 'chrome') {
494
- await page.bringToFront();
495
- }
496
- }
497
-
498
- async _addErrorListener(page) {
499
- if (!page) {
500
- return;
501
- }
502
- page.on('error', async (error) => {
503
- console.error('Puppeteer page error', error);
504
- });
505
- }
506
-
507
- /**
508
- * Add the 'dialog' event listener to a page
509
- * @page {Puppeteer.Page}
510
- *
511
- * The popup listener handles the dialog with the predefined action when it appears on the page.
512
- * It also saves a reference to the object which is used in seeInPopup.
513
- */
514
- _addPopupListener(page) {
515
- if (!page) {
516
- return;
517
- }
518
- page.on('dialog', async (dialog) => {
519
- popupStore.popup = dialog;
520
- const action = popupStore.actionType || this.options.defaultPopupAction;
521
- await this._waitForAction();
522
-
523
- switch (action) {
524
- case 'accept':
525
- return dialog.accept();
526
-
527
- case 'cancel':
528
- return dialog.dismiss();
529
-
530
- default: {
531
- throw new Error('Unknown popup action type. Only "accept" or "cancel" are accepted');
532
- }
533
- }
534
- });
535
- }
536
-
537
- /**
538
- * Gets page URL including hash.
539
- */
540
- async _getPageUrl() {
541
- return this.executeScript(() => window.location.href);
542
- }
543
-
544
- /**
545
- * Grab the text within the popup. If no popup is visible then it will return null
546
- *
547
- * ```js
548
- * await I.grabPopupText();
549
- * ```
550
- * @return {Promise<string | null>}
551
- */
552
- async grabPopupText() {
553
- if (popupStore.popup) {
554
- return popupStore.popup.message();
555
- }
556
- return null;
557
- }
558
-
559
- async _startBrowser() {
560
- if (this.isRemoteBrowser) {
561
- try {
562
- this.browser = await puppeteer.connect(this.puppeteerOptions);
563
- } catch (err) {
564
- if (err.toString().indexOf('ECONNREFUSED')) {
565
- throw new RemoteBrowserConnectionRefused(err);
566
- }
567
- throw err;
568
- }
569
- } else {
570
- this.browser = await puppeteer.launch(this.puppeteerOptions);
571
- }
572
-
573
- this.browser.on('targetcreated', target => target.page().then(page => targetCreatedHandler.call(this, page)).catch((e) => {
574
- console.error('Puppeteer page error', e);
575
- }));
576
- this.browser.on('targetchanged', (target) => {
577
- this.debugSection('Url', target.url());
578
- });
579
-
580
- const existingPages = await this.browser.pages();
581
- const mainPage = existingPages[0] || await this.browser.newPage();
582
-
583
- if (existingPages.length) {
584
- // Run the handler as it will not be triggered if the page already exists
585
- targetCreatedHandler.call(this, mainPage);
586
- }
587
- await this._setPage(mainPage);
588
- await this.closeOtherTabs();
589
-
590
- this.isRunning = true;
591
- }
592
-
593
- async _stopBrowser() {
594
- this.withinLocator = null;
595
- this._setPage(null);
596
- this.context = null;
597
- popupStore.clear();
598
- this.isAuthenticated = false;
599
- await this.browser.close();
600
- if (this.isRemoteBrowser) {
601
- await this.browser.disconnect();
602
- }
603
- }
604
-
605
- async _evaluateHandeInContext(...args) {
606
- let context = await this._getContext();
607
-
608
- if (context.constructor.name === 'Frame') {
609
- // Currently there is no evalateHandle for the Frame object
610
- // https://github.com/GoogleChrome/puppeteer/issues/1051
611
- context = await context.executionContext();
612
- }
613
-
614
- return context.evaluateHandle(...args);
615
- }
616
-
617
- async _withinBegin(locator) {
618
- if (this.withinLocator) {
619
- throw new Error('Can\'t start within block inside another within block');
620
- }
621
-
622
- const frame = isFrameLocator(locator);
623
-
624
- if (frame) {
625
- if (Array.isArray(frame)) {
626
- return this.switchTo(null)
627
- .then(() => frame.reduce((p, frameLocator) => p.then(() => this.switchTo(frameLocator)), Promise.resolve()));
628
- }
629
- await this.switchTo(frame);
630
- this.withinLocator = new Locator(frame);
631
- return;
632
- }
633
-
634
- const els = await this._locate(locator);
635
- assertElementExists(els, locator);
636
- this.context = els[0];
637
-
638
- this.withinLocator = new Locator(locator);
639
- }
640
-
641
- async _withinEnd() {
642
- this.withinLocator = null;
643
- this.context = await this.page.mainFrame().$('body');
644
- }
645
-
646
- _extractDataFromPerformanceTiming(timing, ...dataNames) {
647
- const navigationStart = timing.navigationStart;
648
-
649
- const extractedData = {};
650
- dataNames.forEach((name) => {
651
- extractedData[name] = timing[name] - navigationStart;
652
- });
653
-
654
- return extractedData;
655
- }
656
-
657
- /**
658
- * Opens a web page in a browser. Requires relative or absolute url.
659
- * If url starts with `/`, opens a web page of a site defined in `url` config parameter.
660
- *
661
- * ```js
662
- * I.amOnPage('/'); // opens main page of website
663
- * I.amOnPage('https://github.com'); // opens github
664
- * I.amOnPage('/login'); // opens a login page
665
- * ```
666
- *
667
- * @param {string} url url path or global url.
668
- * @returns {void} automatically synchronized promise through #recorder
669
- *
670
- */
671
- async amOnPage(url) {
672
- if (!(/^\w+\:\/\//.test(url))) {
673
- url = this.options.url + url;
674
- }
675
-
676
- if (this.config.basicAuth && (this.isAuthenticated !== true)) {
677
- if (url.includes(this.options.url)) {
678
- await this.page.authenticate(this.config.basicAuth);
679
- this.isAuthenticated = true;
680
- }
681
- }
682
-
683
- if (this.options.trace) {
684
- const fileName = `${`${global.output_dir}${path.sep}trace${path.sep}${uuidv4()}_${clearString(this.currentRunningTest.title)}`.slice(0, 245)}.json`;
685
- const dir = path.dirname(fileName);
686
- if (!fileExists(dir)) fs.mkdirSync(dir);
687
- await this.page.tracing.start({ screenshots: true, path: fileName });
688
- this.currentRunningTest.artifacts.trace = fileName;
689
- }
690
-
691
- await this.page.goto(url, { waitUntil: this.options.waitForNavigation });
692
-
693
- const performanceTiming = JSON.parse(await this.page.evaluate(() => JSON.stringify(window.performance.timing)));
694
-
695
- perfTiming = this._extractDataFromPerformanceTiming(
696
- performanceTiming,
697
- 'responseEnd',
698
- 'domInteractive',
699
- 'domContentLoadedEventEnd',
700
- 'loadEventEnd',
701
- );
702
-
703
- return this._waitForAction();
704
- }
705
-
706
- /**
707
- *
708
- * Unlike other drivers Puppeteer changes the size of a viewport, not the window!
709
- * Puppeteer does not control the window of a browser, so it can't adjust its real size.
710
- * It also can't maximize a window.
711
- *
712
- * Resize the current window to provided width and height.
713
- * First parameter can be set to `maximize`.
714
- *
715
- * @param {number} width width in pixels or `maximize`.
716
- * @param {number} height height in pixels.
717
- * @returns {void} automatically synchronized promise through #recorder
718
- *
719
- *
720
- */
721
- async resizeWindow(width, height) {
722
- if (width === 'maximize') {
723
- throw new Error('Puppeteer can\'t control windows, so it can\'t maximize it');
724
- }
725
-
726
- await this.page.setViewport({ width, height });
727
- return this._waitForAction();
728
- }
729
-
730
- /**
731
- * Set headers for all next requests
732
- *
733
- * ```js
734
- * I.setPuppeteerRequestHeaders({
735
- * 'X-Sent-By': 'CodeceptJS',
736
- * });
737
- * ```
738
- *
739
- * @param {object} customHeaders headers to set
740
- */
741
- async setPuppeteerRequestHeaders(customHeaders) {
742
- if (!customHeaders) {
743
- throw new Error('Cannot send empty headers.');
744
- }
745
- return this.page.setExtraHTTPHeaders(customHeaders);
746
- }
747
-
748
- /**
749
- * Moves cursor to element matched by locator.
750
- * Extra shift can be set with offsetX and offsetY options.
751
- *
752
- * ```js
753
- * I.moveCursorTo('.tooltip');
754
- * I.moveCursorTo('#submit', 5,5);
755
- * ```
756
- *
757
- * @param {CodeceptJS.LocatorOrString} locator located by CSS|XPath|strict locator.
758
- * @param {number} [offsetX=0] (optional, `0` by default) X-axis offset.
759
- * @param {number} [offsetY=0] (optional, `0` by default) Y-axis offset.
760
- * @returns {void} automatically synchronized promise through #recorder
761
- *
762
- * {{ react }}
763
- */
764
- async moveCursorTo(locator, offsetX = 0, offsetY = 0) {
765
- const els = await this._locate(locator);
766
- assertElementExists(els, locator);
767
-
768
- // Use manual mouse.move instead of .hover() so the offset can be added to the coordinates
769
- const { x, y } = await getClickablePoint(els[0]);
770
- await this.page.mouse.move(x + offsetX, y + offsetY);
771
- return this._waitForAction();
772
- }
773
-
774
- /**
775
- * Calls [focus](https://developer.mozilla.org/en-US/docs/Web/API/HTMLElement/focus) on the matching element.
776
- *
777
- * Examples:
778
- *
779
- * ```js
780
- * I.dontSee('#add-to-cart-btn');
781
- * I.focus('#product-tile')
782
- * I.see('#add-to-cart-bnt');
783
- * ```
784
- *
785
- * @param {CodeceptJS.LocatorOrString} locator field located by label|name|CSS|XPath|strict locator.
786
- * @param {any} [options] Playwright only: [Additional options](https://playwright.dev/docs/api/class-locator#locator-focus) for available options object as 2nd argument.
787
- * @returns {void} automatically synchronized promise through #recorder
788
- *
789
- *
790
- */
791
- async focus(locator) {
792
- const els = await this._locate(locator);
793
- assertElementExists(els, locator, 'Element to focus');
794
- const el = els[0];
795
-
796
- await el.click();
797
- await el.focus();
798
- return this._waitForAction();
799
- }
800
-
801
- /**
802
- * Remove focus from a text input, button, etc.
803
- * Calls [blur](https://developer.mozilla.org/en-US/docs/Web/API/HTMLElement/focus) on the element.
804
- *
805
- * Examples:
806
- *
807
- * ```js
808
- * I.blur('.text-area')
809
- * ```
810
- * ```js
811
- * //element `#product-tile` is focused
812
- * I.see('#add-to-cart-btn');
813
- * I.blur('#product-tile')
814
- * I.dontSee('#add-to-cart-btn');
815
- * ```
816
- *
817
- * @param {CodeceptJS.LocatorOrString} locator field located by label|name|CSS|XPath|strict locator.
818
- * @param {any} [options] Playwright only: [Additional options](https://playwright.dev/docs/api/class-locator#locator-blur) for available options object as 2nd argument.
819
- * @returns {void} automatically synchronized promise through #recorder
820
- *
821
- *
822
- */
823
- async blur(locator) {
824
- const els = await this._locate(locator);
825
- assertElementExists(els, locator, 'Element to blur');
826
-
827
- await blurElement(els[0], this.page);
828
- return this._waitForAction();
829
- }
830
-
831
- /**
832
- * Drag an item to a destination element.
833
- *
834
- * ```js
835
- * I.dragAndDrop('#dragHandle', '#container');
836
- * ```
837
- *
838
- * @param {LocatorOrString} srcElement located by CSS|XPath|strict locator.
839
- * @param {LocatorOrString} destElement located by CSS|XPath|strict locator.
840
- * @returns {void} automatically synchronized promise through #recorder
841
- *
842
- */
843
- async dragAndDrop(srcElement, destElement) {
844
- return proceedDragAndDrop.call(this, srcElement, destElement);
845
- }
846
-
847
- /**
848
- * Reload the current page.
849
- *
850
- * ```js
851
- * I.refreshPage();
852
- * ```
853
- * @returns {void} automatically synchronized promise through #recorder
854
- *
855
- */
856
- async refreshPage() {
857
- return this.page.reload({ timeout: this.options.getPageTimeout, waitUntil: this.options.waitForNavigation });
858
- }
859
-
860
- /**
861
- * Scroll page to the top.
862
- *
863
- * ```js
864
- * I.scrollPageToTop();
865
- * ```
866
- * @returns {void} automatically synchronized promise through #recorder
867
- *
868
- */
869
- scrollPageToTop() {
870
- return this.executeScript(() => {
871
- window.scrollTo(0, 0);
872
- });
873
- }
874
-
875
- /**
876
- * Scroll page to the bottom.
877
- *
878
- * ```js
879
- * I.scrollPageToBottom();
880
- * ```
881
- * @returns {void} automatically synchronized promise through #recorder
882
- *
883
- */
884
- scrollPageToBottom() {
885
- return this.executeScript(() => {
886
- const body = document.body;
887
- const html = document.documentElement;
888
- window.scrollTo(0, Math.max(
889
- body.scrollHeight,
890
- body.offsetHeight,
891
- html.clientHeight,
892
- html.scrollHeight,
893
- html.offsetHeight,
894
- ));
895
- });
896
- }
897
-
898
- /**
899
- * Scrolls to element matched by locator.
900
- * Extra shift can be set with offsetX and offsetY options.
901
- *
902
- * ```js
903
- * I.scrollTo('footer');
904
- * I.scrollTo('#submit', 5, 5);
905
- * ```
906
- *
907
- * @param {CodeceptJS.LocatorOrString} locator located by CSS|XPath|strict locator.
908
- * @param {number} [offsetX=0] (optional, `0` by default) X-axis offset.
909
- * @param {number} [offsetY=0] (optional, `0` by default) Y-axis offset.
910
- * @returns {void} automatically synchronized promise through #recorder
911
- *
912
- */
913
- async scrollTo(locator, offsetX = 0, offsetY = 0) {
914
- if (typeof locator === 'number' && typeof offsetX === 'number') {
915
- offsetY = offsetX;
916
- offsetX = locator;
917
- locator = null;
918
- }
919
-
920
- if (locator) {
921
- const els = await this._locate(locator);
922
- assertElementExists(els, locator, 'Element');
923
- const el = els[0];
924
- await el.evaluate((el) => el.scrollIntoView());
925
- const elementCoordinates = await getClickablePoint(els[0]);
926
- await this.executeScript((x, y) => window.scrollBy(x, y), elementCoordinates.x + offsetX, elementCoordinates.y + offsetY);
927
- } else {
928
- await this.executeScript((x, y) => window.scrollTo(x, y), offsetX, offsetY);
929
- }
930
- return this._waitForAction();
931
- }
932
-
933
- /**
934
- * Checks that title contains text.
935
- *
936
- * ```js
937
- * I.seeInTitle('Home Page');
938
- * ```
939
- *
940
- * @param {string} text text value to check.
941
- * @returns {void} automatically synchronized promise through #recorder
942
- *
943
- */
944
- async seeInTitle(text) {
945
- const title = await this.page.title();
946
- stringIncludes('web page title').assert(text, title);
947
- }
948
-
949
- /**
950
- * Retrieves a page scroll position and returns it to test.
951
- * Resumes test execution, so **should be used inside an async function with `await`** operator.
952
- *
953
- * ```js
954
- * let { x, y } = await I.grabPageScrollPosition();
955
- * ```
956
- *
957
- * @returns {Promise<PageScrollPosition>} scroll position
958
- *
959
- */
960
- async grabPageScrollPosition() {
961
- /* eslint-disable comma-dangle */
962
- function getScrollPosition() {
963
- return {
964
- x: window.pageXOffset,
965
- y: window.pageYOffset
966
- };
967
- }
968
- /* eslint-enable comma-dangle */
969
- return this.executeScript(getScrollPosition);
970
- }
971
-
972
- /**
973
- * Checks that title is equal to provided one.
974
- *
975
- * ```js
976
- * I.seeTitleEquals('Test title.');
977
- * ```
978
- *
979
- * @param {string} text value to check.
980
- * @returns {void} automatically synchronized promise through #recorder
981
- *
982
- */
983
- async seeTitleEquals(text) {
984
- const title = await this.page.title();
985
- return equals('web page title').assert(title, text);
986
- }
987
-
988
- /**
989
- * Checks that title does not contain text.
990
- *
991
- * ```js
992
- * I.dontSeeInTitle('Error');
993
- * ```
994
- *
995
- * @param {string} text value to check.
996
- * @returns {void} automatically synchronized promise through #recorder
997
- *
998
- */
999
- async dontSeeInTitle(text) {
1000
- const title = await this.page.title();
1001
- stringIncludes('web page title').negate(text, title);
1002
- }
1003
-
1004
- /**
1005
- * Retrieves a page title and returns it to test.
1006
- * Resumes test execution, so **should be used inside async with `await`** operator.
1007
- *
1008
- * ```js
1009
- * let title = await I.grabTitle();
1010
- * ```
1011
- *
1012
- * @returns {Promise<string>} title
1013
- */
1014
- async grabTitle() {
1015
- return this.page.title();
1016
- }
1017
-
1018
- /**
1019
- * Get elements by different locator types, including strict locator
1020
- * Should be used in custom helpers:
1021
- *
1022
- * ```js
1023
- * const elements = await this.helpers['Puppeteer']._locate({name: 'password'});
1024
- * ```
1025
- *
1026
- * {{ react }}
1027
- */
1028
- async _locate(locator) {
1029
- return findElements(await this.context, locator);
1030
- }
1031
-
1032
- /**
1033
- * Find a checkbox by providing human-readable text:
1034
- * NOTE: Assumes the checkable element exists
1035
- *
1036
- * ```js
1037
- * this.helpers['Puppeteer']._locateCheckable('I agree with terms and conditions').then // ...
1038
- * ```
1039
- */
1040
- async _locateCheckable(locator, providedContext = null) {
1041
- const context = providedContext || await this._getContext();
1042
- const els = await findCheckable.call(this, locator, context);
1043
- assertElementExists(els[0], locator, 'Checkbox or radio');
1044
- return els[0];
1045
- }
1046
-
1047
- /**
1048
- * Find a clickable element by providing human-readable text:
1049
- *
1050
- * ```js
1051
- * this.helpers['Puppeteer']._locateClickable('Next page').then // ...
1052
- * ```
1053
- */
1054
- async _locateClickable(locator) {
1055
- const context = await this._getContext();
1056
- return findClickable.call(this, context, locator);
1057
- }
1058
-
1059
- /**
1060
- * Find field elements by providing human-readable text:
1061
- *
1062
- * ```js
1063
- * this.helpers['Puppeteer']._locateFields('Your email').then // ...
1064
- * ```
1065
- */
1066
- async _locateFields(locator) {
1067
- return findFields.call(this, locator);
1068
- }
1069
-
1070
- /**
1071
- * Grab WebElements for given locator
1072
- * Resumes test execution, so **should be used inside an async function with `await`** operator.
1073
- *
1074
- * ```js
1075
- * const webElements = await I.grabWebElements('#button');
1076
- * ```
1077
- *
1078
- * @param {CodeceptJS.LocatorOrString} locator element located by CSS|XPath|strict locator.
1079
- * @returns {Promise<*>} WebElement of being used Web helper
1080
- *
1081
- *
1082
- */
1083
- async grabWebElements(locator) {
1084
- return this._locate(locator);
1085
- }
1086
-
1087
- /**
1088
- * Switch focus to a particular tab by its number. It waits tabs loading and then switch tab
1089
- *
1090
- * ```js
1091
- * I.switchToNextTab();
1092
- * I.switchToNextTab(2);
1093
- * ```
1094
- *
1095
- * @param {number} [num=1]
1096
- */
1097
- async switchToNextTab(num = 1) {
1098
- const pages = await this.browser.pages();
1099
- const index = pages.indexOf(this.page);
1100
- this.withinLocator = null;
1101
- const page = pages[index + num];
1102
-
1103
- if (!page) {
1104
- throw new Error(`There is no ability to switch to next tab with offset ${num}`);
1105
- }
1106
-
1107
- await this._setPage(page);
1108
- return this._waitForAction();
1109
- }
1110
-
1111
- /**
1112
- * Switch focus to a particular tab by its number. It waits tabs loading and then switch tab
1113
- *
1114
- * ```js
1115
- * I.switchToPreviousTab();
1116
- * I.switchToPreviousTab(2);
1117
- * ```
1118
- * @param {number} [num=1]
1119
- */
1120
- async switchToPreviousTab(num = 1) {
1121
- const pages = await this.browser.pages();
1122
- const index = pages.indexOf(this.page);
1123
- this.withinLocator = null;
1124
- const page = pages[index - num];
1125
-
1126
- if (!page) {
1127
- throw new Error(`There is no ability to switch to previous tab with offset ${num}`);
1128
- }
1129
-
1130
- await this._setPage(page);
1131
- return this._waitForAction();
1132
- }
1133
-
1134
- /**
1135
- * Close current tab and switches to previous.
1136
- *
1137
- * ```js
1138
- * I.closeCurrentTab();
1139
- * ```
1140
- */
1141
- async closeCurrentTab() {
1142
- const oldPage = this.page;
1143
- await this.switchToPreviousTab();
1144
- await oldPage.close();
1145
- return this._waitForAction();
1146
- }
1147
-
1148
- /**
1149
- * Close all tabs except for the current one.
1150
- *
1151
- * ```js
1152
- * I.closeOtherTabs();
1153
- * ```
1154
- */
1155
- async closeOtherTabs() {
1156
- const pages = await this.browser.pages();
1157
- const otherPages = pages.filter(page => page !== this.page);
1158
-
1159
- let p = Promise.resolve();
1160
- otherPages.forEach((page) => {
1161
- p = p.then(() => page.close());
1162
- });
1163
- await p;
1164
- return this._waitForAction();
1165
- }
1166
-
1167
- /**
1168
- * Open new tab and switch to it
1169
- *
1170
- * ```js
1171
- * I.openNewTab();
1172
- * ```
1173
- */
1174
- async openNewTab() {
1175
- await this._setPage(await this.browser.newPage());
1176
- return this._waitForAction();
1177
- }
1178
-
1179
- /**
1180
- * Grab number of open tabs.
1181
- * Resumes test execution, so **should be used inside async function with `await`** operator.
1182
- *
1183
- * ```js
1184
- * let tabs = await I.grabNumberOfOpenTabs();
1185
- * ```
1186
- *
1187
- * @returns {Promise<number>} number of open tabs
1188
- *
1189
- */
1190
- async grabNumberOfOpenTabs() {
1191
- const pages = await this.browser.pages();
1192
- return pages.length;
1193
- }
1194
-
1195
- /**
1196
- * Checks that a given Element is visible
1197
- * Element is located by CSS or XPath.
1198
- *
1199
- * ```js
1200
- * I.seeElement('#modal');
1201
- * ```
1202
- * @param {CodeceptJS.LocatorOrString} locator located by CSS|XPath|strict locator.
1203
- * @returns {void} automatically synchronized promise through #recorder
1204
- *
1205
- * {{ react }}
1206
- */
1207
- async seeElement(locator) {
1208
- let els = await this._locate(locator);
1209
- els = (await Promise.all(els.map(el => el.boundingBox() && el))).filter(v => v);
1210
- // Puppeteer visibility was ignored? | Remove when Puppeteer is fixed
1211
- els = await Promise.all(els.map(async el => (await el.evaluate(node => window.getComputedStyle(node).visibility !== 'hidden' && window.getComputedStyle(node).display !== 'none')) && el));
1212
-
1213
- return empty('visible elements').negate(els.filter(v => v).fill('ELEMENT'));
1214
- }
1215
-
1216
- /**
1217
- * Opposite to `seeElement`. Checks that element is not visible (or in DOM)
1218
- *
1219
- * ```js
1220
- * I.dontSeeElement('.modal'); // modal is not shown
1221
- * ```
1222
- *
1223
- * @param {CodeceptJS.LocatorOrString} locator located by CSS|XPath|Strict locator.
1224
- * @returns {void} automatically synchronized promise through #recorder
1225
- *
1226
- * {{ react }}
1227
- */
1228
- async dontSeeElement(locator) {
1229
- let els = await this._locate(locator);
1230
- els = (await Promise.all(els.map(el => el.boundingBox() && el))).filter(v => v);
1231
- // Puppeteer visibility was ignored? | Remove when Puppeteer is fixed
1232
- els = await Promise.all(els.map(async el => (await el.evaluate(node => window.getComputedStyle(node).visibility !== 'hidden' && window.getComputedStyle(node).display !== 'none')) && el));
1233
-
1234
- return empty('visible elements').assert(els.filter(v => v).fill('ELEMENT'));
1235
- }
1236
-
1237
- /**
1238
- * Checks that a given Element is present in the DOM
1239
- * Element is located by CSS or XPath.
1240
- *
1241
- * ```js
1242
- * I.seeElementInDOM('#modal');
1243
- * ```
1244
- * @param {CodeceptJS.LocatorOrString} locator element located by CSS|XPath|strict locator.
1245
- * @returns {void} automatically synchronized promise through #recorder
1246
- *
1247
- */
1248
- async seeElementInDOM(locator) {
1249
- const els = await this._locate(locator);
1250
- return empty('elements on page').negate(els.filter(v => v).fill('ELEMENT'));
1251
- }
1252
-
1253
- /**
1254
- * Opposite to `seeElementInDOM`. Checks that element is not on page.
1255
- *
1256
- * ```js
1257
- * I.dontSeeElementInDOM('.nav'); // checks that element is not on page visible or not
1258
- * ```
1259
- *
1260
- * @param {CodeceptJS.LocatorOrString} locator located by CSS|XPath|Strict locator.
1261
- * @returns {void} automatically synchronized promise through #recorder
1262
- *
1263
- */
1264
- async dontSeeElementInDOM(locator) {
1265
- const els = await this._locate(locator);
1266
- return empty('elements on a page').assert(els.filter(v => v).fill('ELEMENT'));
1267
- }
1268
-
1269
- /**
1270
- * Perform a click on a link or a button, given by a locator.
1271
- * If a fuzzy locator is given, the page will be searched for a button, link, or image matching the locator string.
1272
- * For buttons, the "value" attribute, "name" attribute, and inner text are searched. For links, the link text is searched.
1273
- * For images, the "alt" attribute and inner text of any parent links are searched.
1274
- *
1275
- * The second parameter is a context (CSS or XPath locator) to narrow the search.
1276
- *
1277
- * ```js
1278
- * // simple link
1279
- * I.click('Logout');
1280
- * // button of form
1281
- * I.click('Submit');
1282
- * // CSS button
1283
- * I.click('#form input[type=submit]');
1284
- * // XPath
1285
- * I.click('//form/*[@type=submit]');
1286
- * // link in context
1287
- * I.click('Logout', '#nav');
1288
- * // using strict locator
1289
- * I.click({css: 'nav a.login'});
1290
- * ```
1291
- *
1292
- * @param {CodeceptJS.LocatorOrString} locator clickable link or button located by text, or any element located by CSS|XPath|strict locator.
1293
- * @param {?CodeceptJS.LocatorOrString | null} [context=null] (optional, `null` by default) element to search in CSS|XPath|Strict locator.
1294
- * @returns {void} automatically synchronized promise through #recorder
1295
- *
1296
- *
1297
- * {{ react }}
1298
- */
1299
- async click(locator, context = null) {
1300
- return proceedClick.call(this, locator, context);
1301
- }
1302
-
1303
- /**
1304
- * Perform an emulated click on a link or a button, given by a locator.
1305
- * Unlike normal click instead of sending native event, emulates a click with JavaScript.
1306
- * This works on hidden, animated or inactive elements as well.
1307
- *
1308
- * If a fuzzy locator is given, the page will be searched for a button, link, or image matching the locator string.
1309
- * For buttons, the "value" attribute, "name" attribute, and inner text are searched. For links, the link text is searched.
1310
- * For images, the "alt" attribute and inner text of any parent links are searched.
1311
- *
1312
- * The second parameter is a context (CSS or XPath locator) to narrow the search.
1313
- *
1314
- * ```js
1315
- * // simple link
1316
- * I.forceClick('Logout');
1317
- * // button of form
1318
- * I.forceClick('Submit');
1319
- * // CSS button
1320
- * I.forceClick('#form input[type=submit]');
1321
- * // XPath
1322
- * I.forceClick('//form/*[@type=submit]');
1323
- * // link in context
1324
- * I.forceClick('Logout', '#nav');
1325
- * // using strict locator
1326
- * I.forceClick({css: 'nav a.login'});
1327
- * ```
1328
- *
1329
- * @param {CodeceptJS.LocatorOrString} locator clickable link or button located by text, or any element located by CSS|XPath|strict locator.
1330
- * @param {?CodeceptJS.LocatorOrString} [context=null] (optional, `null` by default) element to search in CSS|XPath|Strict locator.
1331
- * @returns {void} automatically synchronized promise through #recorder
1332
- *
1333
- *
1334
- * {{ react }}
1335
- */
1336
- async forceClick(locator, context = null) {
1337
- let matcher = await this.context;
1338
- if (context) {
1339
- const els = await this._locate(context);
1340
- assertElementExists(els, context);
1341
- matcher = els[0];
1342
- }
1343
-
1344
- const els = await findClickable.call(this, matcher, locator);
1345
- if (context) {
1346
- assertElementExists(els, locator, 'Clickable element', `was not found inside element ${new Locator(context).toString()}`);
1347
- } else {
1348
- assertElementExists(els, locator, 'Clickable element');
1349
- }
1350
- const elem = els[0];
1351
- return this.executeScript((el) => {
1352
- if (document.activeElement instanceof HTMLElement) {
1353
- document.activeElement.blur();
1354
- }
1355
- const event = document.createEvent('MouseEvent');
1356
- event.initEvent('click', true, true);
1357
- return el.dispatchEvent(event);
1358
- }, elem);
1359
- }
1360
-
1361
- /**
1362
- * Performs a click on a link and waits for navigation before moving on.
1363
- *
1364
- * ```js
1365
- * I.clickLink('Logout', '#nav');
1366
- * ```
1367
- * @param {CodeceptJS.LocatorOrString} locator clickable link or button located by text, or any element located by CSS|XPath|strict locator
1368
- * @param {?CodeceptJS.LocatorOrString} [context=null] (optional, `null` by default) element to search in CSS|XPath|Strict locator
1369
- * @returns {void} automatically synchronized promise through #recorder
1370
- *
1371
- *
1372
- * {{ react }}
1373
- */
1374
- async clickLink(locator, context = null) {
1375
- return proceedClick.call(this, locator, context, { waitForNavigation: true });
1376
- }
1377
-
1378
- /**
1379
- * Sets a directory to where save files. Allows to test file downloads.
1380
- * Should be used with [FileSystem helper](https://codecept.io/helpers/FileSystem) to check that file were downloaded correctly.
1381
- *
1382
- * By default, files are saved to `output/downloads`.
1383
- * This directory is cleaned on every `handleDownloads` call, to ensure no old files are kept.
1384
- *
1385
- * ```js
1386
- * I.handleDownloads();
1387
- * I.click('Download Avatar');
1388
- * I.amInPath('output/downloads');
1389
- * I.seeFile('avatar.jpg');
1390
- *
1391
- * ```
1392
- *
1393
- * @param {string} [downloadPath='downloads'] change this parameter to set another directory for saving
1394
- */
1395
- async handleDownloads(downloadPath = 'downloads') {
1396
- downloadPath = path.join(global.output_dir, downloadPath);
1397
- if (!fs.existsSync(downloadPath)) {
1398
- fs.mkdirSync(downloadPath, '0777');
1399
- }
1400
- fsExtra.emptyDirSync(downloadPath);
1401
-
1402
- try {
1403
- return this.page._client.send('Page.setDownloadBehavior', { behavior: 'allow', downloadPath });
1404
- } catch (e) {
1405
- return this.page._client().send('Page.setDownloadBehavior', { behavior: 'allow', downloadPath });
1406
- }
1407
- }
1408
-
1409
- /**
1410
- * This method is **deprecated**.
1411
- *
1412
- * Please use `handleDownloads()` instead.
1413
- */
1414
- async downloadFile(locator, customName) {
1415
- let fileName;
1416
- await this.page.setRequestInterception(true);
1417
-
1418
- const xRequest = await new Promise((resolve) => {
1419
- this.page.on('request', (request) => {
1420
- console.log('rq', request, customName);
1421
- const grabbedFileName = request.url().split('/')[request.url().split('/').length - 1];
1422
- const fileExtension = request.url().split('/')[request.url().split('/').length - 1].split('.')[1];
1423
- console.log('nm', customName, fileExtension);
1424
- if (customName && path.extname(customName) !== fileExtension) {
1425
- console.log('bypassing a request');
1426
- request.continue();
1427
- return;
1428
- }
1429
- customName ? fileName = `${customName}.${fileExtension}` : fileName = grabbedFileName;
1430
- request.abort();
1431
- resolve(request);
1432
- });
1433
- });
1434
-
1435
- await this.click(locator);
1436
-
1437
- const options = {
1438
- encoding: null,
1439
- method: xRequest._method,
1440
- uri: xRequest._url,
1441
- body: xRequest._postData,
1442
- headers: xRequest._headers,
1443
- };
1444
-
1445
- const cookies = await this.page.cookies();
1446
- options.headers.Cookie = cookies.map(ck => `${ck.name}=${ck.value}`).join(';');
1447
-
1448
- const response = await axios({
1449
- method: options.method,
1450
- url: options.uri,
1451
- headers: options.headers,
1452
- responseType: 'arraybuffer',
1453
- onDownloadProgress(e) {
1454
- console.log('+', e);
1455
- },
1456
- });
1457
-
1458
- const outputFile = path.join(`${global.output_dir}/${fileName}`);
1459
-
1460
- try {
1461
- await new Promise((resolve, reject) => {
1462
- const wstream = fs.createWriteStream(outputFile);
1463
- console.log(response);
1464
- wstream.write(response.data);
1465
- wstream.end();
1466
- this.debug(`File is downloaded in ${outputFile}`);
1467
- wstream.on('finish', () => { resolve(fileName); });
1468
- wstream.on('error', reject);
1469
- });
1470
- } catch (error) {
1471
- throw new Error(`There is something wrong with downloaded file. ${error}`);
1472
- }
1473
- }
1474
-
1475
- /**
1476
- * Performs a double-click on an element matched by link|button|label|CSS or XPath.
1477
- * Context can be specified as second parameter to narrow search.
1478
- *
1479
- * ```js
1480
- * I.doubleClick('Edit');
1481
- * I.doubleClick('Edit', '.actions');
1482
- * I.doubleClick({css: 'button.accept'});
1483
- * I.doubleClick('.btn.edit');
1484
- * ```
1485
- *
1486
- * @param {CodeceptJS.LocatorOrString} locator clickable link or button located by text, or any element located by CSS|XPath|strict locator.
1487
- * @param {?CodeceptJS.LocatorOrString} [context=null] (optional, `null` by default) element to search in CSS|XPath|Strict locator.
1488
- * @returns {void} automatically synchronized promise through #recorder
1489
- *
1490
- *
1491
- * {{ react }}
1492
- */
1493
- async doubleClick(locator, context = null) {
1494
- return proceedClick.call(this, locator, context, { clickCount: 2 });
1495
- }
1496
-
1497
- /**
1498
- * Performs right click on a clickable element matched by semantic locator, CSS or XPath.
1499
- *
1500
- * ```js
1501
- * // right click element with id el
1502
- * I.rightClick('#el');
1503
- * // right click link or button with text "Click me"
1504
- * I.rightClick('Click me');
1505
- * // right click button with text "Click me" inside .context
1506
- * I.rightClick('Click me', '.context');
1507
- * ```
1508
- *
1509
- * @param {CodeceptJS.LocatorOrString} locator clickable element located by CSS|XPath|strict locator.
1510
- * @param {?CodeceptJS.LocatorOrString} [context=null] (optional, `null` by default) element located by CSS|XPath|strict locator.
1511
- * @returns {void} automatically synchronized promise through #recorder
1512
- *
1513
- *
1514
- * {{ react }}
1515
- */
1516
- async rightClick(locator, context = null) {
1517
- return proceedClick.call(this, locator, context, { button: 'right' });
1518
- }
1519
-
1520
- /**
1521
- * Selects a checkbox or radio button.
1522
- * Element is located by label or name or CSS or XPath.
1523
- *
1524
- * The second parameter is a context (CSS or XPath locator) to narrow the search.
1525
- *
1526
- * ```js
1527
- * I.checkOption('#agree');
1528
- * I.checkOption('I Agree to Terms and Conditions');
1529
- * I.checkOption('agree', '//form');
1530
- * ```
1531
- * @param {CodeceptJS.LocatorOrString} field checkbox located by label | name | CSS | XPath | strict locator.
1532
- * @param {?CodeceptJS.LocatorOrString} [context=null] (optional, `null` by default) element located by CSS | XPath | strict locator.
1533
- * @returns {void} automatically synchronized promise through #recorder
1534
- *
1535
- */
1536
- async checkOption(field, context = null) {
1537
- const elm = await this._locateCheckable(field, context);
1538
- const curentlyChecked = await elm.getProperty('checked')
1539
- .then(checkedProperty => checkedProperty.jsonValue());
1540
- // Only check if NOT currently checked
1541
- if (!curentlyChecked) {
1542
- await elm.click();
1543
- return this._waitForAction();
1544
- }
1545
- }
1546
-
1547
- /**
1548
- * Unselects a checkbox or radio button.
1549
- * Element is located by label or name or CSS or XPath.
1550
- *
1551
- * The second parameter is a context (CSS or XPath locator) to narrow the search.
1552
- *
1553
- * ```js
1554
- * I.uncheckOption('#agree');
1555
- * I.uncheckOption('I Agree to Terms and Conditions');
1556
- * I.uncheckOption('agree', '//form');
1557
- * ```
1558
- * @param {CodeceptJS.LocatorOrString} field checkbox located by label | name | CSS | XPath | strict locator.
1559
- * @param {?CodeceptJS.LocatorOrString} [context=null] (optional, `null` by default) element located by CSS | XPath | strict locator.
1560
- * @returns {void} automatically synchronized promise through #recorder
1561
- *
1562
- */
1563
- async uncheckOption(field, context = null) {
1564
- const elm = await this._locateCheckable(field, context);
1565
- const curentlyChecked = await elm.getProperty('checked')
1566
- .then(checkedProperty => checkedProperty.jsonValue());
1567
- // Only uncheck if currently checked
1568
- if (curentlyChecked) {
1569
- await elm.click();
1570
- return this._waitForAction();
1571
- }
1572
- }
1573
-
1574
- /**
1575
- * Verifies that the specified checkbox is checked.
1576
- *
1577
- * ```js
1578
- * I.seeCheckboxIsChecked('Agree');
1579
- * I.seeCheckboxIsChecked('#agree'); // I suppose user agreed to terms
1580
- * I.seeCheckboxIsChecked({css: '#signup_form input[type=checkbox]'});
1581
- * ```
1582
- *
1583
- * @param {CodeceptJS.LocatorOrString} field located by label|name|CSS|XPath|strict locator.
1584
- * @returns {void} automatically synchronized promise through #recorder
1585
- *
1586
- */
1587
- async seeCheckboxIsChecked(field) {
1588
- return proceedIsChecked.call(this, 'assert', field);
1589
- }
1590
-
1591
- /**
1592
- * Verifies that the specified checkbox is not checked.
1593
- *
1594
- * ```js
1595
- * I.dontSeeCheckboxIsChecked('#agree'); // located by ID
1596
- * I.dontSeeCheckboxIsChecked('I agree to terms'); // located by label
1597
- * I.dontSeeCheckboxIsChecked('agree'); // located by name
1598
- * ```
1599
- *
1600
- * @param {CodeceptJS.LocatorOrString} field located by label|name|CSS|XPath|strict locator.
1601
- * @returns {void} automatically synchronized promise through #recorder
1602
- *
1603
- */
1604
- async dontSeeCheckboxIsChecked(field) {
1605
- return proceedIsChecked.call(this, 'negate', field);
1606
- }
1607
-
1608
- /**
1609
- * Presses a key in the browser and leaves it in a down state.
1610
- *
1611
- * To make combinations with modifier key and user operation (e.g. `'Control'` + [`click`](#click)).
1612
- *
1613
- * ```js
1614
- * I.pressKeyDown('Control');
1615
- * I.click('#element');
1616
- * I.pressKeyUp('Control');
1617
- * ```
1618
- *
1619
- * @param {string} key name of key to press down.
1620
- * @returns {void} automatically synchronized promise through #recorder
1621
- *
1622
- */
1623
- async pressKeyDown(key) {
1624
- key = getNormalizedKey.call(this, key);
1625
- await this.page.keyboard.down(key);
1626
- return this._waitForAction();
1627
- }
1628
-
1629
- /**
1630
- * Releases a key in the browser which was previously set to a down state.
1631
- *
1632
- * To make combinations with modifier key and user operation (e.g. `'Control'` + [`click`](#click)).
1633
- *
1634
- * ```js
1635
- * I.pressKeyDown('Control');
1636
- * I.click('#element');
1637
- * I.pressKeyUp('Control');
1638
- * ```
1639
- *
1640
- * @param {string} key name of key to release.
1641
- * @returns {void} automatically synchronized promise through #recorder
1642
- *
1643
- */
1644
- async pressKeyUp(key) {
1645
- key = getNormalizedKey.call(this, key);
1646
- await this.page.keyboard.up(key);
1647
- return this._waitForAction();
1648
- }
1649
-
1650
- /**
1651
- * _Note:_ Shortcuts like `'Meta'` + `'A'` do not work on macOS ([GoogleChrome/puppeteer#1313](https://github.com/GoogleChrome/puppeteer/issues/1313)).
1652
- *
1653
- * Presses a key in the browser (on a focused element).
1654
- *
1655
- * _Hint:_ For populating text field or textarea, it is recommended to use [`fillField`](#fillfield).
1656
- *
1657
- * ```js
1658
- * I.pressKey('Backspace');
1659
- * ```
1660
- *
1661
- * 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.
1662
- *
1663
- * ```js
1664
- * I.pressKey(['Control', 'Z']);
1665
- * ```
1666
- *
1667
- * For specifying operation modifier key based on operating system it is suggested to use `'CommandOrControl'`.
1668
- * This will press `'Command'` (also known as `'Meta'`) on macOS machines and `'Control'` on non-macOS machines.
1669
- *
1670
- * ```js
1671
- * I.pressKey(['CommandOrControl', 'Z']);
1672
- * ```
1673
- *
1674
- * Some of the supported key names are:
1675
- * - `'AltLeft'` or `'Alt'`
1676
- * - `'AltRight'`
1677
- * - `'ArrowDown'`
1678
- * - `'ArrowLeft'`
1679
- * - `'ArrowRight'`
1680
- * - `'ArrowUp'`
1681
- * - `'Backspace'`
1682
- * - `'Clear'`
1683
- * - `'ControlLeft'` or `'Control'`
1684
- * - `'ControlRight'`
1685
- * - `'Command'`
1686
- * - `'CommandOrControl'`
1687
- * - `'Delete'`
1688
- * - `'End'`
1689
- * - `'Enter'`
1690
- * - `'Escape'`
1691
- * - `'F1'` to `'F12'`
1692
- * - `'Home'`
1693
- * - `'Insert'`
1694
- * - `'MetaLeft'` or `'Meta'`
1695
- * - `'MetaRight'`
1696
- * - `'Numpad0'` to `'Numpad9'`
1697
- * - `'NumpadAdd'`
1698
- * - `'NumpadDecimal'`
1699
- * - `'NumpadDivide'`
1700
- * - `'NumpadMultiply'`
1701
- * - `'NumpadSubtract'`
1702
- * - `'PageDown'`
1703
- * - `'PageUp'`
1704
- * - `'Pause'`
1705
- * - `'Return'`
1706
- * - `'ShiftLeft'` or `'Shift'`
1707
- * - `'ShiftRight'`
1708
- * - `'Space'`
1709
- * - `'Tab'`
1710
- *
1711
- * @param {string|string[]} key key or array of keys to press.
1712
- * @returns {void} automatically synchronized promise through #recorder
1713
- *
1714
- */
1715
- async pressKey(key) {
1716
- const modifiers = [];
1717
- if (Array.isArray(key)) {
1718
- for (let k of key) {
1719
- k = getNormalizedKey.call(this, k);
1720
- if (isModifierKey(k)) {
1721
- modifiers.push(k);
1722
- } else {
1723
- key = k;
1724
- break;
1725
- }
1726
- }
1727
- } else {
1728
- key = getNormalizedKey.call(this, key);
1729
- }
1730
- for (const modifier of modifiers) {
1731
- await this.page.keyboard.down(modifier);
1732
- }
1733
- await this.page.keyboard.press(key);
1734
- for (const modifier of modifiers) {
1735
- await this.page.keyboard.up(modifier);
1736
- }
1737
- return this._waitForAction();
1738
- }
1739
-
1740
- /**
1741
- * Types out the given text into an active field.
1742
- * To slow down typing use a second parameter, to set interval between key presses.
1743
- * _Note:_ Should be used when [`fillField`](#fillfield) is not an option.
1744
- *
1745
- * ```js
1746
- * // passing in a string
1747
- * I.type('Type this out.');
1748
- *
1749
- * // typing values with a 100ms interval
1750
- * I.type('4141555311111111', 100);
1751
- *
1752
- * // passing in an array
1753
- * I.type(['T', 'E', 'X', 'T']);
1754
- *
1755
- * // passing a secret
1756
- * I.type(secret('123456'));
1757
- * ```
1758
- *
1759
- * @param {string|string[]} key or array of keys to type.
1760
- * @param {?number} [delay=null] (optional) delay in ms between key presses
1761
- * @returns {void} automatically synchronized promise through #recorder
1762
- *
1763
- */
1764
- async type(keys, delay = null) {
1765
- if (!Array.isArray(keys)) {
1766
- keys = keys.toString();
1767
- keys = keys.split('');
1768
- }
1769
-
1770
- for (const key of keys) {
1771
- await this.page.keyboard.press(key);
1772
- if (delay) await this.wait(delay / 1000);
1773
- }
1774
- }
1775
-
1776
- /**
1777
- * Fills a text field or textarea, after clearing its value, with the given string.
1778
- * Field is located by name, label, CSS, or XPath.
1779
- *
1780
- * ```js
1781
- * // by label
1782
- * I.fillField('Email', 'hello@world.com');
1783
- * // by name
1784
- * I.fillField('password', secret('123456'));
1785
- * // by CSS
1786
- * I.fillField('form#login input[name=username]', 'John');
1787
- * // or by strict locator
1788
- * I.fillField({css: 'form#login input[name=username]'}, 'John');
1789
- * ```
1790
- * @param {CodeceptJS.LocatorOrString} field located by label|name|CSS|XPath|strict locator.
1791
- * @param {CodeceptJS.StringOrSecret} value text value to fill.
1792
- * @returns {void} automatically synchronized promise through #recorder
1793
- *
1794
- * {{ react }}
1795
- */
1796
- async fillField(field, value) {
1797
- const els = await findVisibleFields.call(this, field);
1798
- assertElementExists(els, field, 'Field');
1799
- const el = els[0];
1800
- const tag = await el.getProperty('tagName').then(el => el.jsonValue());
1801
- const editable = await el.getProperty('contenteditable').then(el => el.jsonValue());
1802
- if (tag === 'INPUT' || tag === 'TEXTAREA') {
1803
- await this._evaluateHandeInContext(el => el.value = '', el);
1804
- } else if (editable) {
1805
- await this._evaluateHandeInContext(el => el.innerHTML = '', el);
1806
- }
1807
-
1808
- highlightActiveElement.call(this, el, await this._getContext());
1809
- await el.type(value.toString(), { delay: this.options.pressKeyDelay });
1810
-
1811
- return this._waitForAction();
1812
- }
1813
-
1814
- /**
1815
- * Clears a `<textarea>` or text `<input>` element's value.
1816
- *
1817
- * ```js
1818
- * I.clearField('Email');
1819
- * I.clearField('user[email]');
1820
- * I.clearField('#email');
1821
- * ```
1822
- * @param {LocatorOrString} editable field located by label|name|CSS|XPath|strict locator.
1823
- * @returns {void} automatically synchronized promise through #recorder.
1824
- *
1825
- */
1826
- async clearField(field) {
1827
- return this.fillField(field, '');
1828
- }
1829
-
1830
- /**
1831
- * Appends text to a input field or textarea.
1832
- * Field is located by name, label, CSS or XPath
1833
- *
1834
- * ```js
1835
- * I.appendField('#myTextField', 'appended');
1836
- * // typing secret
1837
- * I.appendField('password', secret('123456'));
1838
- * ```
1839
- * @param {CodeceptJS.LocatorOrString} field located by label|name|CSS|XPath|strict locator
1840
- * @param {string} value text value to append.
1841
- * @returns {void} automatically synchronized promise through #recorder
1842
- *
1843
- *
1844
- * {{ react }}
1845
- */
1846
- async appendField(field, value) {
1847
- const els = await findVisibleFields.call(this, field);
1848
- assertElementExists(els, field, 'Field');
1849
- highlightActiveElement.call(this, els[0], await this._getContext());
1850
- await els[0].press('End');
1851
- await els[0].type(value.toString(), { delay: this.options.pressKeyDelay });
1852
- return this._waitForAction();
1853
- }
1854
-
1855
- /**
1856
- * Checks that the given input field or textarea equals to given value.
1857
- * For fuzzy locators, fields are matched by label text, the "name" attribute, CSS, and XPath.
1858
- *
1859
- * ```js
1860
- * I.seeInField('Username', 'davert');
1861
- * I.seeInField({css: 'form textarea'},'Type your comment here');
1862
- * I.seeInField('form input[type=hidden]','hidden_value');
1863
- * I.seeInField('#searchform input','Search');
1864
- * ```
1865
- * @param {CodeceptJS.LocatorOrString} field located by label|name|CSS|XPath|strict locator.
1866
- * @param {CodeceptJS.StringOrSecret} value value to check.
1867
- * @returns {void} automatically synchronized promise through #recorder
1868
- *
1869
- */
1870
- async seeInField(field, value) {
1871
- const _value = (typeof value === 'boolean') ? value : value.toString();
1872
- return proceedSeeInField.call(this, 'assert', field, _value);
1873
- }
1874
-
1875
- /**
1876
- * Checks that value of input field or textarea doesn't equal to given value
1877
- * Opposite to `seeInField`.
1878
- *
1879
- * ```js
1880
- * I.dontSeeInField('email', 'user@user.com'); // field by name
1881
- * I.dontSeeInField({ css: 'form input.email' }, 'user@user.com'); // field by CSS
1882
- * ```
1883
- *
1884
- * @param {CodeceptJS.LocatorOrString} field located by label|name|CSS|XPath|strict locator.
1885
- * @param {CodeceptJS.StringOrSecret} value value to check.
1886
- * @returns {void} automatically synchronized promise through #recorder
1887
- *
1888
- */
1889
- async dontSeeInField(field, value) {
1890
- const _value = (typeof value === 'boolean') ? value : value.toString();
1891
- return proceedSeeInField.call(this, 'negate', field, _value);
1892
- }
1893
-
1894
- /**
1895
- * > ⚠ There is an [issue with file upload in Puppeteer 2.1.0 & 2.1.1](https://github.com/puppeteer/puppeteer/issues/5420), downgrade to 2.0.0 if you face it.
1896
- *
1897
- * Attaches a file to element located by label, name, CSS or XPath
1898
- * Path to file is relative current codecept directory (where codecept.conf.ts or codecept.conf.js is located).
1899
- * File will be uploaded to remote system (if tests are running remotely).
1900
- *
1901
- * ```js
1902
- * I.attachFile('Avatar', 'data/avatar.jpg');
1903
- * I.attachFile('form input[name=avatar]', 'data/avatar.jpg');
1904
- * ```
1905
- *
1906
- * @param {CodeceptJS.LocatorOrString} locator field located by label|name|CSS|XPath|strict locator.
1907
- * @param {string} pathToFile local file path relative to codecept.conf.ts or codecept.conf.js config file.
1908
- * @returns {void} automatically synchronized promise through #recorder
1909
- *
1910
- */
1911
- async attachFile(locator, pathToFile) {
1912
- const file = path.join(global.codecept_dir, pathToFile);
1913
-
1914
- if (!fileExists(file)) {
1915
- throw new Error(`File at ${file} can not be found on local system`);
1916
- }
1917
- const els = await findFields.call(this, locator);
1918
- assertElementExists(els, locator, 'Field');
1919
- await els[0].uploadFile(file);
1920
- return this._waitForAction();
1921
- }
1922
-
1923
- /**
1924
- * Selects an option in a drop-down select.
1925
- * Field is searched by label | name | CSS | XPath.
1926
- * Option is selected by visible text or by value.
1927
- *
1928
- * ```js
1929
- * I.selectOption('Choose Plan', 'Monthly'); // select by label
1930
- * I.selectOption('subscription', 'Monthly'); // match option by text
1931
- * I.selectOption('subscription', '0'); // or by value
1932
- * I.selectOption('//form/select[@name=account]','Premium');
1933
- * I.selectOption('form select[name=account]', 'Premium');
1934
- * I.selectOption({css: 'form select[name=account]'}, 'Premium');
1935
- * ```
1936
- *
1937
- * Provide an array for the second argument to select multiple options.
1938
- *
1939
- * ```js
1940
- * I.selectOption('Which OS do you use?', ['Android', 'iOS']);
1941
- * ```
1942
- * @param {LocatorOrString} select field located by label|name|CSS|XPath|strict locator.
1943
- * @param {string|Array<*>} option visible text or value of option.
1944
- * @returns {void} automatically synchronized promise through #recorder
1945
- *
1946
- */
1947
- async selectOption(select, option) {
1948
- const els = await findVisibleFields.call(this, select);
1949
- assertElementExists(els, select, 'Selectable field');
1950
- const el = els[0];
1951
- if (await el.getProperty('tagName').then(t => t.jsonValue()) !== 'SELECT') {
1952
- throw new Error('Element is not <select>');
1953
- }
1954
- highlightActiveElement.call(this, els[0], await this._getContext());
1955
- if (!Array.isArray(option)) option = [option];
1956
-
1957
- for (const key in option) {
1958
- const opt = xpathLocator.literal(option[key]);
1959
- let optEl = await findElements.call(this, el, { xpath: Locator.select.byVisibleText(opt) });
1960
- if (optEl.length) {
1961
- this._evaluateHandeInContext(el => el.selected = true, optEl[0]);
1962
- continue;
1963
- }
1964
- optEl = await findElements.call(this, el, { xpath: Locator.select.byValue(opt) });
1965
- if (optEl.length) {
1966
- this._evaluateHandeInContext(el => el.selected = true, optEl[0]);
1967
- }
1968
- }
1969
- await this._evaluateHandeInContext((element) => {
1970
- element.dispatchEvent(new Event('input', { bubbles: true }));
1971
- element.dispatchEvent(new Event('change', { bubbles: true }));
1972
- }, el);
1973
-
1974
- return this._waitForAction();
1975
- }
1976
-
1977
- /**
1978
- * Grab number of visible elements by locator.
1979
- * Resumes test execution, so **should be used inside async function with `await`** operator.
1980
- *
1981
- * ```js
1982
- * let numOfElements = await I.grabNumberOfVisibleElements('p');
1983
- * ```
1984
- *
1985
- * @param {CodeceptJS.LocatorOrString} locator located by CSS|XPath|strict locator.
1986
- * @returns {Promise<number>} number of visible elements
1987
- * {{ react }}
1988
- */
1989
- async grabNumberOfVisibleElements(locator) {
1990
- let els = await this._locate(locator);
1991
- els = (await Promise.all(els.map(el => el.boundingBox() && el))).filter(v => v);
1992
- // Puppeteer visibility was ignored? | Remove when Puppeteer is fixed
1993
- els = await Promise.all(els.map(async el => (await el.evaluate(node => window.getComputedStyle(node).visibility !== 'hidden' && window.getComputedStyle(node).display !== 'none')) && el));
1994
-
1995
- return els.filter(v => v).length;
1996
- }
1997
-
1998
- /**
1999
- * Checks that current url contains a provided fragment.
2000
- *
2001
- * ```js
2002
- * I.seeInCurrentUrl('/register'); // we are on registration page
2003
- * ```
2004
- *
2005
- * @param {string} url a fragment to check
2006
- * @returns {void} automatically synchronized promise through #recorder
2007
- *
2008
- */
2009
- async seeInCurrentUrl(url) {
2010
- stringIncludes('url').assert(url, await this._getPageUrl());
2011
- }
2012
-
2013
- /**
2014
- * Checks that current url does not contain a provided fragment.
2015
- *
2016
- * @param {string} url value to check.
2017
- * @returns {void} automatically synchronized promise through #recorder
2018
- *
2019
- */
2020
- async dontSeeInCurrentUrl(url) {
2021
- stringIncludes('url').negate(url, await this._getPageUrl());
2022
- }
2023
-
2024
- /**
2025
- * Checks that current url is equal to provided one.
2026
- * If a relative url provided, a configured url will be prepended to it.
2027
- * So both examples will work:
2028
- *
2029
- * ```js
2030
- * I.seeCurrentUrlEquals('/register');
2031
- * I.seeCurrentUrlEquals('http://my.site.com/register');
2032
- * ```
2033
- *
2034
- * @param {string} url value to check.
2035
- * @returns {void} automatically synchronized promise through #recorder
2036
- *
2037
- */
2038
- async seeCurrentUrlEquals(url) {
2039
- urlEquals(this.options.url).assert(url, await this._getPageUrl());
2040
- }
2041
-
2042
- /**
2043
- * Checks that current url is not equal to provided one.
2044
- * If a relative url provided, a configured url will be prepended to it.
2045
- *
2046
- * ```js
2047
- * I.dontSeeCurrentUrlEquals('/login'); // relative url are ok
2048
- * I.dontSeeCurrentUrlEquals('http://mysite.com/login'); // absolute urls are also ok
2049
- * ```
2050
- *
2051
- * @param {string} url value to check.
2052
- * @returns {void} automatically synchronized promise through #recorder
2053
- *
2054
- */
2055
- async dontSeeCurrentUrlEquals(url) {
2056
- urlEquals(this.options.url).negate(url, await this._getPageUrl());
2057
- }
2058
-
2059
- /**
2060
- * Checks that a page contains a visible text.
2061
- * Use context parameter to narrow down the search.
2062
- *
2063
- * ```js
2064
- * I.see('Welcome'); // text welcome on a page
2065
- * I.see('Welcome', '.content'); // text inside .content div
2066
- * I.see('Register', {css: 'form.register'}); // use strict locator
2067
- * ```
2068
- * @param {string} text expected on page.
2069
- * @param {?CodeceptJS.LocatorOrString} [context=null] (optional, `null` by default) element located by CSS|Xpath|strict locator in which to search for text.
2070
- * @returns {void} automatically synchronized promise through #recorder
2071
- *
2072
- *
2073
- * {{ react }}
2074
- */
2075
- async see(text, context = null) {
2076
- return proceedSee.call(this, 'assert', text, context);
2077
- }
2078
-
2079
- /**
2080
- * Checks that text is equal to provided one.
2081
- *
2082
- * ```js
2083
- * I.seeTextEquals('text', 'h1');
2084
- * ```
2085
- *
2086
- * @param {string} text element value to check.
2087
- * @param {CodeceptJS.LocatorOrString?} [context=null] element located by CSS|XPath|strict locator.
2088
- * @returns {void} automatically synchronized promise through #recorder
2089
- *
2090
- */
2091
- async seeTextEquals(text, context = null) {
2092
- return proceedSee.call(this, 'assert', text, context, true);
2093
- }
2094
-
2095
- /**
2096
- * Opposite to `see`. Checks that a text is not present on a page.
2097
- * Use context parameter to narrow down the search.
2098
- *
2099
- * ```js
2100
- * I.dontSee('Login'); // assume we are already logged in.
2101
- * I.dontSee('Login', '.nav'); // no login inside .nav element
2102
- * ```
2103
- *
2104
- * @param {string} text which is not present.
2105
- * @param {CodeceptJS.LocatorOrString} [context] (optional) element located by CSS|XPath|strict locator in which to perfrom search.
2106
- * @returns {void} automatically synchronized promise through #recorder
2107
- *
2108
- *
2109
- * {{ react }}
2110
- */
2111
- async dontSee(text, context = null) {
2112
- return proceedSee.call(this, 'negate', text, context);
2113
- }
2114
-
2115
- /**
2116
- * Retrieves page source and returns it to test.
2117
- * Resumes test execution, so **should be used inside async function with `await`** operator.
2118
- *
2119
- * ```js
2120
- * let pageSource = await I.grabSource();
2121
- * ```
2122
- *
2123
- * @returns {Promise<string>} source code
2124
- */
2125
- async grabSource() {
2126
- return this.page.content();
2127
- }
2128
-
2129
- /**
2130
- * Get JS log from browser.
2131
- *
2132
- * ```js
2133
- * let logs = await I.grabBrowserLogs();
2134
- * console.log(JSON.stringify(logs))
2135
- * ```
2136
- * @return {Promise<any[]>}
2137
- */
2138
- async grabBrowserLogs() {
2139
- const logs = consoleLogStore.entries;
2140
- consoleLogStore.clear();
2141
- return logs;
2142
- }
2143
-
2144
- /**
2145
- * Get current URL from browser.
2146
- * Resumes test execution, so should be used inside an async function.
2147
- *
2148
- * ```js
2149
- * let url = await I.grabCurrentUrl();
2150
- * console.log(`Current URL is [${url}]`);
2151
- * ```
2152
- *
2153
- * @returns {Promise<string>} current URL
2154
- */
2155
- async grabCurrentUrl() {
2156
- return this._getPageUrl();
2157
- }
2158
-
2159
- /**
2160
- * Checks that the current page contains the given string in its raw source code.
2161
- *
2162
- * ```js
2163
- * I.seeInSource('<h1>Green eggs &amp; ham</h1>');
2164
- * ```
2165
- * @param {string} text value to check.
2166
- * @returns {void} automatically synchronized promise through #recorder
2167
- *
2168
- */
2169
- async seeInSource(text) {
2170
- const source = await this.page.content();
2171
- stringIncludes('HTML source of a page').assert(text, source);
2172
- }
2173
-
2174
- /**
2175
- * Checks that the current page does not contains the given string in its raw source code.
2176
- *
2177
- * ```js
2178
- * I.dontSeeInSource('<!--'); // no comments in source
2179
- * ```
2180
- *
2181
- * @param {string} value to check.
2182
- * @returns {void} automatically synchronized promise through #recorder
2183
- *
2184
- */
2185
- async dontSeeInSource(text) {
2186
- const source = await this.page.content();
2187
- stringIncludes('HTML source of a page').negate(text, source);
2188
- }
2189
-
2190
- /**
2191
- * Asserts that an element appears a given number of times in the DOM.
2192
- * Element is located by label or name or CSS or XPath.
2193
- *
2194
- *
2195
- * ```js
2196
- * I.seeNumberOfElements('#submitBtn', 1);
2197
- * ```
2198
- *
2199
- * @param {CodeceptJS.LocatorOrString} locator element located by CSS|XPath|strict locator.
2200
- * @param {number} num number of elements.
2201
- * @returns {void} automatically synchronized promise through #recorder
2202
- *
2203
- *
2204
- * {{ react }}
2205
- */
2206
- async seeNumberOfElements(locator, num) {
2207
- const elements = await this._locate(locator);
2208
- return equals(`expected number of elements (${(new Locator(locator))}) is ${num}, but found ${elements.length}`).assert(elements.length, num);
2209
- }
2210
-
2211
- /**
2212
- * Asserts that an element is visible a given number of times.
2213
- * Element is located by CSS or XPath.
2214
- *
2215
- * ```js
2216
- * I.seeNumberOfVisibleElements('.buttons', 3);
2217
- * ```
2218
- *
2219
- * @param {CodeceptJS.LocatorOrString} locator element located by CSS|XPath|strict locator.
2220
- * @param {number} num number of elements.
2221
- * @returns {void} automatically synchronized promise through #recorder
2222
- *
2223
- *
2224
- * {{ react }}
2225
- */
2226
- async seeNumberOfVisibleElements(locator, num) {
2227
- const res = await this.grabNumberOfVisibleElements(locator);
2228
- return equals(`expected number of visible elements (${(new Locator(locator))}) is ${num}, but found ${res}`).assert(res, num);
2229
- }
2230
-
2231
- /**
2232
- * Sets cookie(s).
2233
- *
2234
- * Can be a single cookie object or an array of cookies:
2235
- *
2236
- * ```js
2237
- * I.setCookie({name: 'auth', value: true});
2238
- *
2239
- * // as array
2240
- * I.setCookie([
2241
- * {name: 'auth', value: true},
2242
- * {name: 'agree', value: true}
2243
- * ]);
2244
- * ```
2245
- *
2246
- * @param {Cookie|Array<Cookie>} cookie a cookie object or array of cookie objects.
2247
- * @returns {void} automatically synchronized promise through #recorder
2248
- *
2249
- */
2250
- async setCookie(cookie) {
2251
- if (Array.isArray(cookie)) {
2252
- return this.page.setCookie(...cookie);
2253
- }
2254
- return this.page.setCookie(cookie);
2255
- }
2256
-
2257
- /**
2258
- * Checks that cookie with given name exists.
2259
- *
2260
- * ```js
2261
- * I.seeCookie('Auth');
2262
- * ```
2263
- *
2264
- * @param {string} name cookie name.
2265
- * @returns {void} automatically synchronized promise through #recorder
2266
- *
2267
- *
2268
- */
2269
- async seeCookie(name) {
2270
- const cookies = await this.page.cookies();
2271
- empty(`cookie ${name} to be set`).negate(cookies.filter(c => c.name === name));
2272
- }
2273
-
2274
- /**
2275
- * Checks that cookie with given name does not exist.
2276
- *
2277
- * ```js
2278
- * I.dontSeeCookie('auth'); // no auth cookie
2279
- * ```
2280
- *
2281
- * @param {string} name cookie name.
2282
- * @returns {void} automatically synchronized promise through #recorder
2283
- *
2284
- */
2285
- async dontSeeCookie(name) {
2286
- const cookies = await this.page.cookies();
2287
- empty(`cookie ${name} to be set`).assert(cookies.filter(c => c.name === name));
2288
- }
2289
-
2290
- /**
2291
- * Gets a cookie object by name.
2292
- * If none provided gets all cookies.
2293
- * Resumes test execution, so **should be used inside async function with `await`** operator.
2294
- *
2295
- * ```js
2296
- * let cookie = await I.grabCookie('auth');
2297
- * assert(cookie.value, '123456');
2298
- * ```
2299
- *
2300
- * @param {?string} [name=null] cookie name.
2301
- * @returns {any} attribute value
2302
- *
2303
- *
2304
- * Returns cookie in JSON format. If name not passed returns all cookies for this domain.
2305
- */
2306
- async grabCookie(name) {
2307
- const cookies = await this.page.cookies();
2308
- if (!name) return cookies;
2309
- const cookie = cookies.filter(c => c.name === name);
2310
- if (cookie[0]) return cookie[0];
2311
- }
2312
-
2313
- /**
2314
- * Clears a cookie by name,
2315
- * if none provided clears all cookies.
2316
- *
2317
- * ```js
2318
- * I.clearCookie();
2319
- * I.clearCookie('test'); // Playwright currently doesn't support clear a particular cookie name
2320
- * ```
2321
- *
2322
- * @param {?string} [cookie=null] (optional, `null` by default) cookie name
2323
- *
2324
- */
2325
- async clearCookie(name) {
2326
- const cookies = await this.page.cookies();
2327
- if (!name) {
2328
- return this.page.deleteCookie.apply(this.page, cookies);
2329
- }
2330
- const cookie = cookies.filter(c => c.name === name);
2331
- if (!cookie[0]) return;
2332
- return this.page.deleteCookie(cookie[0]);
2333
- }
2334
-
2335
- /**
2336
- * If a function returns a Promise, tt will wait for its resolution.
2337
- *
2338
- * Executes sync script on a page.
2339
- * Pass arguments to function as additional parameters.
2340
- * Will return execution result to a test.
2341
- * In this case you should use async function and await to receive results.
2342
- *
2343
- * Example with jQuery DatePicker:
2344
- *
2345
- * ```js
2346
- * // change date of jQuery DatePicker
2347
- * I.executeScript(function() {
2348
- * // now we are inside browser context
2349
- * $('date').datetimepicker('setDate', new Date());
2350
- * });
2351
- * ```
2352
- * Can return values. Don't forget to use `await` to get them.
2353
- *
2354
- * ```js
2355
- * let date = await I.executeScript(function(el) {
2356
- * // only basic types can be returned
2357
- * return $(el).datetimepicker('getDate').toString();
2358
- * }, '#date'); // passing jquery selector
2359
- * ```
2360
- *
2361
- * @param {string|function} fn function to be executed in browser context.
2362
- * @param {...any} args to be passed to function.
2363
- * @returns {Promise<any>} script return value
2364
- *
2365
- */
2366
- async executeScript(...args) {
2367
- let context = this.page;
2368
- if (this.context && this.context.constructor.name === 'Frame') {
2369
- context = this.context; // switching to iframe context
2370
- }
2371
- return context.evaluate.apply(context, args);
2372
- }
2373
-
2374
- /**
2375
- * Asynchronous scripts can also be executed with `executeScript` if a function returns a Promise.
2376
- * Executes async script on page.
2377
- * Provided function should execute a passed callback (as first argument) to signal it is finished.
2378
- *
2379
- * Example: In Vue.js to make components completely rendered we are waiting for [nextTick](https://vuejs.org/v2/api/#Vue-nextTick).
2380
- *
2381
- * ```js
2382
- * I.executeAsyncScript(function(done) {
2383
- * Vue.nextTick(done); // waiting for next tick
2384
- * });
2385
- * ```
2386
- *
2387
- * By passing value to `done()` function you can return values.
2388
- * Additional arguments can be passed as well, while `done` function is always last parameter in arguments list.
2389
- *
2390
- * ```js
2391
- * let val = await I.executeAsyncScript(function(url, done) {
2392
- * // in browser context
2393
- * $.ajax(url, { success: (data) => done(data); }
2394
- * }, 'http://ajax.callback.url/');
2395
- * ```
2396
- *
2397
- * @param {string|function} fn function to be executed in browser context.
2398
- * @param {...any} args to be passed to function.
2399
- * @returns {Promise<any>} script return value
2400
- *
2401
- */
2402
- async executeAsyncScript(...args) {
2403
- const asyncFn = function () {
2404
- const args = Array.from(arguments);
2405
- const fn = eval(`(${args.shift()})`); // eslint-disable-line no-eval
2406
- return new Promise((done) => {
2407
- args.push(done);
2408
- fn.apply(null, args);
2409
- });
2410
- };
2411
- args[0] = args[0].toString();
2412
- args.unshift(asyncFn);
2413
- return this.page.evaluate.apply(this.page, args);
2414
- }
2415
-
2416
- /**
2417
- * Retrieves all texts from an element located by CSS or XPath and returns it to test.
2418
- * Resumes test execution, so **should be used inside async with `await`** operator.
2419
- *
2420
- * ```js
2421
- * let pins = await I.grabTextFromAll('#pin li');
2422
- * ```
2423
- *
2424
- * @param {CodeceptJS.LocatorOrString} locator element located by CSS|XPath|strict locator.
2425
- * @returns {Promise<string[]>} attribute value
2426
- *
2427
- * {{ react }}
2428
- */
2429
- async grabTextFromAll(locator) {
2430
- const els = await this._locate(locator);
2431
- const texts = [];
2432
- for (const el of els) {
2433
- texts.push(await (await el.getProperty('innerText')).jsonValue());
2434
- }
2435
- return texts;
2436
- }
2437
-
2438
- /**
2439
- * Retrieves a text from an element located by CSS or XPath and returns it to test.
2440
- * Resumes test execution, so **should be used inside async with `await`** operator.
2441
- *
2442
- * ```js
2443
- * let pin = await I.grabTextFrom('#pin');
2444
- * ```
2445
- * If multiple elements found returns first element.
2446
- *
2447
- * @param {CodeceptJS.LocatorOrString} locator element located by CSS|XPath|strict locator.
2448
- * @returns {Promise<string>} attribute value
2449
- *
2450
- * {{ react }}
2451
- */
2452
- async grabTextFrom(locator) {
2453
- const texts = await this.grabTextFromAll(locator);
2454
- assertElementExists(texts, locator);
2455
- if (texts.length > 1) {
2456
- this.debugSection('GrabText', `Using first element out of ${texts.length}`);
2457
- }
2458
-
2459
- return texts[0];
2460
- }
2461
-
2462
- /**
2463
- * Retrieves an array of value from a form located by CSS or XPath and returns it to test.
2464
- * Resumes test execution, so **should be used inside async function with `await`** operator.
2465
- *
2466
- * ```js
2467
- * let inputs = await I.grabValueFromAll('//form/input');
2468
- * ```
2469
- * @param {CodeceptJS.LocatorOrString} locator field located by label|name|CSS|XPath|strict locator.
2470
- * @returns {Promise<string[]>} attribute value
2471
- *
2472
- */
2473
- async grabValueFromAll(locator) {
2474
- const els = await findFields.call(this, locator);
2475
- const values = [];
2476
- for (const el of els) {
2477
- values.push(await (await el.getProperty('value')).jsonValue());
2478
- }
2479
- return values;
2480
- }
2481
-
2482
- /**
2483
- * Retrieves a value from a form element located by CSS or XPath and returns it to test.
2484
- * Resumes test execution, so **should be used inside async function with `await`** operator.
2485
- * If more than one element is found - value of first element is returned.
2486
- *
2487
- * ```js
2488
- * let email = await I.grabValueFrom('input[name=email]');
2489
- * ```
2490
- * @param {CodeceptJS.LocatorOrString} locator field located by label|name|CSS|XPath|strict locator.
2491
- * @returns {Promise<string>} attribute value
2492
- *
2493
- */
2494
- async grabValueFrom(locator) {
2495
- const values = await this.grabValueFromAll(locator);
2496
- assertElementExists(values, locator);
2497
- if (values.length > 1) {
2498
- this.debugSection('GrabValue', `Using first element out of ${values.length}`);
2499
- }
2500
-
2501
- return values[0];
2502
- }
2503
-
2504
- /**
2505
- * Retrieves all the innerHTML from elements located by CSS or XPath and returns it to test.
2506
- * Resumes test execution, so **should be used inside async function with `await`** operator.
2507
- *
2508
- * ```js
2509
- * let postHTMLs = await I.grabHTMLFromAll('.post');
2510
- * ```
2511
- *
2512
- * @param {CodeceptJS.LocatorOrString} element located by CSS|XPath|strict locator.
2513
- * @returns {Promise<string[]>} HTML code for an element
2514
- *
2515
- */
2516
- async grabHTMLFromAll(locator) {
2517
- const els = await this._locate(locator);
2518
- const values = await Promise.all(els.map(el => el.executionContext().evaluate(element => element.innerHTML, el)));
2519
- return values;
2520
- }
2521
-
2522
- /**
2523
- * Retrieves the innerHTML from an element located by CSS or XPath and returns it to test.
2524
- * Resumes test execution, so **should be used inside async function with `await`** operator.
2525
- * If more than one element is found - HTML of first element is returned.
2526
- *
2527
- * ```js
2528
- * let postHTML = await I.grabHTMLFrom('#post');
2529
- * ```
2530
- *
2531
- * @param {CodeceptJS.LocatorOrString} element located by CSS|XPath|strict locator.
2532
- * @returns {Promise<string>} HTML code for an element
2533
- *
2534
- */
2535
- async grabHTMLFrom(locator) {
2536
- const html = await this.grabHTMLFromAll(locator);
2537
- assertElementExists(html, locator);
2538
- if (html.length > 1) {
2539
- this.debugSection('GrabHTML', `Using first element out of ${html.length}`);
2540
- }
2541
-
2542
- return html[0];
2543
- }
2544
-
2545
- /**
2546
- * Grab array of CSS properties for given locator
2547
- * Resumes test execution, so **should be used inside an async function with `await`** operator.
2548
- *
2549
- * ```js
2550
- * const values = await I.grabCssPropertyFromAll('h3', 'font-weight');
2551
- * ```
2552
- *
2553
- * @param {CodeceptJS.LocatorOrString} locator element located by CSS|XPath|strict locator.
2554
- * @param {string} cssProperty CSS property name.
2555
- * @returns {Promise<string[]>} CSS value
2556
- *
2557
- * {{ react }}
2558
- */
2559
- async grabCssPropertyFromAll(locator, cssProperty) {
2560
- const els = await this._locate(locator);
2561
- const res = await Promise.all(els.map(el => el.executionContext().evaluate(el => JSON.parse(JSON.stringify(getComputedStyle(el))), el)));
2562
- const cssValues = res.map(props => props[toCamelCase(cssProperty)]);
2563
-
2564
- return cssValues;
2565
- }
2566
-
2567
- /**
2568
- * Grab CSS property for given locator
2569
- * Resumes test execution, so **should be used inside an async function with `await`** operator.
2570
- * If more than one element is found - value of first element is returned.
2571
- *
2572
- * ```js
2573
- * const value = await I.grabCssPropertyFrom('h3', 'font-weight');
2574
- * ```
2575
- *
2576
- * @param {CodeceptJS.LocatorOrString} locator element located by CSS|XPath|strict locator.
2577
- * @param {string} cssProperty CSS property name.
2578
- * @returns {Promise<string>} CSS value
2579
- *
2580
- * {{ react }}
2581
- */
2582
- async grabCssPropertyFrom(locator, cssProperty) {
2583
- const cssValues = await this.grabCssPropertyFromAll(locator, cssProperty);
2584
- assertElementExists(cssValues, locator);
2585
-
2586
- if (cssValues.length > 1) {
2587
- this.debugSection('GrabCSS', `Using first element out of ${cssValues.length}`);
2588
- }
2589
-
2590
- return cssValues[0];
2591
- }
2592
-
2593
- /**
2594
- * Checks that all elements with given locator have given CSS properties.
2595
- *
2596
- * ```js
2597
- * I.seeCssPropertiesOnElements('h3', { 'font-weight': "bold"});
2598
- * ```
2599
- *
2600
- * @param {CodeceptJS.LocatorOrString} locator located by CSS|XPath|strict locator.
2601
- * @param {object} cssProperties object with CSS properties and their values to check.
2602
- * @returns {void} automatically synchronized promise through #recorder
2603
- *
2604
- * {{ react }}
2605
- */
2606
- async seeCssPropertiesOnElements(locator, cssProperties) {
2607
- const res = await this._locate(locator);
2608
- assertElementExists(res, locator);
2609
-
2610
- const cssPropertiesCamelCase = convertCssPropertiesToCamelCase(cssProperties);
2611
- const elemAmount = res.length;
2612
- let props = [];
2613
-
2614
- for (const element of res) {
2615
- for (const prop of Object.keys(cssProperties)) {
2616
- const cssProp = await this.grabCssPropertyFrom(locator, prop);
2617
- if (isColorProperty(prop)) {
2618
- props.push(convertColorToRGBA(cssProp));
2619
- } else {
2620
- props.push(cssProp);
2621
- }
2622
- }
2623
- }
2624
-
2625
- const values = Object.keys(cssPropertiesCamelCase).map(key => cssPropertiesCamelCase[key]);
2626
- if (!Array.isArray(props)) props = [props];
2627
- let chunked = chunkArray(props, values.length);
2628
- chunked = chunked.filter((val) => {
2629
- for (let i = 0; i < val.length; ++i) {
2630
- // eslint-disable-next-line eqeqeq
2631
- if (val[i] != values[i]) return false;
2632
- }
2633
- return true;
2634
- });
2635
- return equals(`all elements (${(new Locator(locator))}) to have CSS property ${JSON.stringify(cssProperties)}`).assert(chunked.length, elemAmount);
2636
- }
2637
-
2638
- /**
2639
- * Checks that all elements with given locator have given attributes.
2640
- *
2641
- * ```js
2642
- * I.seeAttributesOnElements('//form', { method: "post"});
2643
- * ```
2644
- *
2645
- * @param {CodeceptJS.LocatorOrString} locator located by CSS|XPath|strict locator.
2646
- * @param {object} attributes attributes and their values to check.
2647
- * @returns {void} automatically synchronized promise through #recorder
2648
- *
2649
- * {{ react }}
2650
- */
2651
- async seeAttributesOnElements(locator, attributes) {
2652
- const res = await this._locate(locator);
2653
- assertElementExists(res, locator);
2654
-
2655
- const elemAmount = res.length;
2656
- const commands = [];
2657
- res.forEach((el) => {
2658
- Object.keys(attributes).forEach((prop) => {
2659
- commands.push(el
2660
- .executionContext()
2661
- .evaluateHandle((el, attr) => el[attr] || el.getAttribute(attr), el, prop)
2662
- .then(el => el.jsonValue()));
2663
- });
2664
- });
2665
- let attrs = await Promise.all(commands);
2666
- const values = Object.keys(attributes).map(key => attributes[key]);
2667
- if (!Array.isArray(attrs)) attrs = [attrs];
2668
- let chunked = chunkArray(attrs, values.length);
2669
- chunked = chunked.filter((val) => {
2670
- for (let i = 0; i < val.length; ++i) {
2671
- const _actual = Number.isNaN(val[i]) || (typeof values[i]) === 'string' ? val[i] : Number.parseInt(values[i], 10);
2672
- const _expected = Number.isNaN(values[i]) || (typeof values[i]) === 'string' ? values[i] : Number.parseInt(values[i], 10);
2673
- // if the attribute doesn't exist, returns false as well
2674
- if (!_actual || !_actual.includes(_expected)) return false;
2675
- }
2676
- return true;
2677
- });
2678
- return equals(`all elements (${(new Locator(locator))}) to have attributes ${JSON.stringify(attributes)}`).assert(chunked.length, elemAmount);
2679
- }
2680
-
2681
- /**
2682
- * Drag the scrubber of a slider to a given position
2683
- * For fuzzy locators, fields are matched by label text, the "name" attribute, CSS, and XPath.
2684
- *
2685
- * ```js
2686
- * I.dragSlider('#slider', 30);
2687
- * I.dragSlider('#slider', -70);
2688
- * ```
2689
- *
2690
- * @param {CodeceptJS.LocatorOrString} locator located by label|name|CSS|XPath|strict locator.
2691
- * @param {number} offsetX position to drag.
2692
- * @returns {void} automatically synchronized promise through #recorder
2693
- *
2694
- * {{ react }}
2695
- */
2696
- async dragSlider(locator, offsetX = 0) {
2697
- const src = await this._locate(locator);
2698
- assertElementExists(src, locator, 'Slider Element');
2699
-
2700
- // Note: Using public api .getClickablePoint because the .BoundingBox does not take into account iframe offsets
2701
- const sliderSource = await getClickablePoint(src[0]);
2702
-
2703
- // Drag start point
2704
- await this.page.mouse.move(sliderSource.x, sliderSource.y, { steps: 5 });
2705
- await this.page.mouse.down();
2706
-
2707
- // Drag destination
2708
- await this.page.mouse.move(sliderSource.x + offsetX, sliderSource.y, { steps: 5 });
2709
- await this.page.mouse.up();
2710
-
2711
- await this._waitForAction();
2712
- }
2713
-
2714
- /**
2715
- * Retrieves an array of attributes from elements located by CSS or XPath and returns it to test.
2716
- * Resumes test execution, so **should be used inside async with `await`** operator.
2717
- *
2718
- * ```js
2719
- * let hints = await I.grabAttributeFromAll('.tooltip', 'title');
2720
- * ```
2721
- * @param {CodeceptJS.LocatorOrString} locator element located by CSS|XPath|strict locator.
2722
- * @param {string} attr attribute name.
2723
- * @returns {Promise<string[]>} attribute value
2724
- *
2725
- * {{ react }}
2726
- */
2727
- async grabAttributeFromAll(locator, attr) {
2728
- const els = await this._locate(locator);
2729
- const array = [];
2730
- for (let index = 0; index < els.length; index++) {
2731
- const a = await this._evaluateHandeInContext((el, attr) => el[attr] || el.getAttribute(attr), els[index], attr);
2732
- array.push(await a.jsonValue());
2733
- }
2734
- return array;
2735
- }
2736
-
2737
- /**
2738
- * Retrieves an attribute from an element located by CSS or XPath and returns it to test.
2739
- * Resumes test execution, so **should be used inside async with `await`** operator.
2740
- * If more than one element is found - attribute of first element is returned.
2741
- *
2742
- * ```js
2743
- * let hint = await I.grabAttributeFrom('#tooltip', 'title');
2744
- * ```
2745
- * @param {CodeceptJS.LocatorOrString} locator element located by CSS|XPath|strict locator.
2746
- * @param {string} attr attribute name.
2747
- * @returns {Promise<string>} attribute value
2748
- *
2749
- * {{ react }}
2750
- */
2751
- async grabAttributeFrom(locator, attr) {
2752
- const attrs = await this.grabAttributeFromAll(locator, attr);
2753
- assertElementExists(attrs, locator);
2754
- if (attrs.length > 1) {
2755
- this.debugSection('GrabAttribute', `Using first element out of ${attrs.length}`);
2756
- }
2757
-
2758
- return attrs[0];
2759
- }
2760
-
2761
- /**
2762
- * Saves screenshot of the specified locator to ouput folder (set in codecept.conf.ts or codecept.conf.js).
2763
- * Filename is relative to output folder.
2764
- *
2765
- * ```js
2766
- * I.saveElementScreenshot(`#submit`,'debug.png');
2767
- * ```
2768
- *
2769
- * @param {CodeceptJS.LocatorOrString} locator element located by CSS|XPath|strict locator.
2770
- * @param {string} fileName file name to save.
2771
- * @returns {void} automatically synchronized promise through #recorder
2772
- *
2773
- */
2774
- async saveElementScreenshot(locator, fileName) {
2775
- const outputFile = screenshotOutputFolder(fileName);
2776
-
2777
- const res = await this._locate(locator);
2778
- assertElementExists(res, locator);
2779
- if (res.length > 1) this.debug(`[Elements] Using first element out of ${res.length}`);
2780
- const elem = res[0];
2781
- this.debug(`Screenshot of ${(new Locator(locator))} element has been saved to ${outputFile}`);
2782
- return elem.screenshot({ path: outputFile, type: 'png' });
2783
- }
2784
-
2785
- /**
2786
- * Saves a screenshot to ouput folder (set in codecept.conf.ts or codecept.conf.js).
2787
- * Filename is relative to output folder.
2788
- * 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.
2789
- *
2790
- * ```js
2791
- * I.saveScreenshot('debug.png');
2792
- * I.saveScreenshot('debug.png', true) //resizes to available scrollHeight and scrollWidth before taking screenshot
2793
- * ```
2794
- *
2795
- * @param {string} fileName file name to save.
2796
- * @param {boolean} [fullPage=false] (optional, `false` by default) flag to enable fullscreen screenshot mode.
2797
- * @returns {void} automatically synchronized promise through #recorder
2798
- *
2799
- */
2800
- async saveScreenshot(fileName, fullPage) {
2801
- const fullPageOption = fullPage || this.options.fullPageScreenshots;
2802
- let outputFile = screenshotOutputFolder(fileName);
2803
-
2804
- this.debug(`Screenshot is saving to ${outputFile}`);
2805
-
2806
- await this.page.screenshot({
2807
- path: outputFile,
2808
- fullPage: fullPageOption,
2809
- type: 'png',
2810
- });
2811
-
2812
- if (this.activeSessionName) {
2813
- for (const sessionName in this.sessionPages) {
2814
- const activeSessionPage = this.sessionPages[sessionName];
2815
- outputFile = screenshotOutputFolder(`${sessionName}_${fileName}`);
2816
-
2817
- this.debug(`${sessionName} - Screenshot is saving to ${outputFile}`);
2818
-
2819
- if (activeSessionPage) {
2820
- await activeSessionPage.screenshot({
2821
- path: outputFile,
2822
- fullPage: fullPageOption,
2823
- type: 'png',
2824
- });
2825
- }
2826
- }
2827
- }
2828
- }
2829
-
2830
- async _failed(test) {
2831
- await this._withinEnd();
2832
-
2833
- if (this.options.trace) {
2834
- await this.page.tracing.stop();
2835
- const _traceName = this.currentRunningTest.artifacts.trace.replace('.json', '.failed.json');
2836
- fs.renameSync(this.currentRunningTest.artifacts.trace, _traceName);
2837
- test.artifacts.trace = _traceName;
2838
- }
2839
- }
2840
-
2841
- async _passed(test) {
2842
- await this._withinEnd();
2843
-
2844
- if (this.options.trace) {
2845
- await this.page.tracing.stop();
2846
- if (this.options.keepTraceForPassedTests) {
2847
- const _traceName = this.currentRunningTest.artifacts.trace.replace('.json', '.passed.json');
2848
- fs.renameSync(this.currentRunningTest.artifacts.trace, _traceName);
2849
- test.artifacts.trace = _traceName;
2850
- } else {
2851
- fs.unlinkSync(this.currentRunningTest.artifacts.trace);
2852
- }
2853
- }
2854
- }
2855
-
2856
- /**
2857
- * Pauses execution for a number of seconds.
2858
- *
2859
- * ```js
2860
- * I.wait(2); // wait 2 secs
2861
- * ```
2862
- *
2863
- * @param {number} sec number of second to wait.
2864
- * @returns {void} automatically synchronized promise through #recorder
2865
- *
2866
- */
2867
- async wait(sec) {
2868
- return new Promise(((done) => {
2869
- setTimeout(done, sec * 1000);
2870
- }));
2871
- }
2872
-
2873
- /**
2874
- * Waits for element to become enabled (by default waits for 1sec).
2875
- * Element can be located by CSS or XPath.
2876
- *
2877
- * @param {CodeceptJS.LocatorOrString} locator element located by CSS|XPath|strict locator.
2878
- * @param {number} [sec=1] (optional) time in seconds to wait, 1 by default.
2879
- * @returns {void} automatically synchronized promise through #recorder
2880
- *
2881
- */
2882
- async waitForEnabled(locator, sec) {
2883
- const waitTimeout = sec ? sec * 1000 : this.options.waitForTimeout;
2884
- locator = new Locator(locator, 'css');
2885
- await this.context;
2886
- let waiter;
2887
- const context = await this._getContext();
2888
- if (locator.isCSS()) {
2889
- const enabledFn = function (locator) {
2890
- const els = document.querySelectorAll(locator);
2891
- if (!els || els.length === 0) {
2892
- return false;
2893
- }
2894
- return Array.prototype.filter.call(els, el => !el.disabled).length > 0;
2895
- };
2896
- waiter = context.waitForFunction(enabledFn, { timeout: waitTimeout }, locator.value);
2897
- } else {
2898
- const enabledFn = function (locator, $XPath) {
2899
- eval($XPath); // eslint-disable-line no-eval
2900
- return $XPath(null, locator).filter(el => !el.disabled).length > 0;
2901
- };
2902
- waiter = context.waitForFunction(enabledFn, { timeout: waitTimeout }, locator.value, $XPath.toString());
2903
- }
2904
- return waiter.catch((err) => {
2905
- throw new Error(`element (${locator.toString()}) still not enabled after ${waitTimeout / 1000} sec\n${err.message}`);
2906
- });
2907
- }
2908
-
2909
- /**
2910
- * Waits for the specified value to be in value attribute.
2911
- *
2912
- * ```js
2913
- * I.waitForValue('//input', "GoodValue");
2914
- * ```
2915
- *
2916
- * @param {LocatorOrString} field input field.
2917
- * @param {string }value expected value.
2918
- * @param {number} [sec=1] (optional, `1` by default) time in seconds to wait
2919
- * @returns {void} automatically synchronized promise through #recorder
2920
- *
2921
- */
2922
- async waitForValue(field, value, sec) {
2923
- const waitTimeout = sec ? sec * 1000 : this.options.waitForTimeout;
2924
- const locator = new Locator(field, 'css');
2925
- await this.context;
2926
- let waiter;
2927
- const context = await this._getContext();
2928
- if (locator.isCSS()) {
2929
- const valueFn = function (locator, value) {
2930
- const els = document.querySelectorAll(locator);
2931
- if (!els || els.length === 0) {
2932
- return false;
2933
- }
2934
- return Array.prototype.filter.call(els, el => (el.value.toString() || '').indexOf(value) !== -1).length > 0;
2935
- };
2936
- waiter = context.waitForFunction(valueFn, { timeout: waitTimeout }, locator.value, value);
2937
- } else {
2938
- const valueFn = function (locator, $XPath, value) {
2939
- eval($XPath); // eslint-disable-line no-eval
2940
- return $XPath(null, locator).filter(el => (el.value || '').indexOf(value) !== -1).length > 0;
2941
- };
2942
- waiter = context.waitForFunction(valueFn, { timeout: waitTimeout }, locator.value, $XPath.toString(), value);
2943
- }
2944
- return waiter.catch((err) => {
2945
- const loc = locator.toString();
2946
- 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}`);
2947
- });
2948
- }
2949
-
2950
- /**
2951
- * Waits for a specified number of elements on the page.
2952
- *
2953
- * ```js
2954
- * I.waitNumberOfVisibleElements('a', 3);
2955
- * ```
2956
- *
2957
- * @param {CodeceptJS.LocatorOrString} locator element located by CSS|XPath|strict locator.
2958
- * @param {number} num number of elements.
2959
- * @param {number} [sec=1] (optional, `1` by default) time in seconds to wait
2960
- * @returns {void} automatically synchronized promise through #recorder
2961
- *
2962
- * {{ react }}
2963
- */
2964
- async waitNumberOfVisibleElements(locator, num, sec) {
2965
- const waitTimeout = sec ? sec * 1000 : this.options.waitForTimeout;
2966
- locator = new Locator(locator, 'css');
2967
- await this.context;
2968
- let waiter;
2969
- const context = await this._getContext();
2970
- if (locator.isCSS()) {
2971
- const visibleFn = function (locator, num) {
2972
- const els = document.querySelectorAll(locator);
2973
- if (!els || els.length === 0) {
2974
- return false;
2975
- }
2976
- return Array.prototype.filter.call(els, el => el.offsetParent !== null).length === num;
2977
- };
2978
- waiter = context.waitForFunction(visibleFn, { timeout: waitTimeout }, locator.value, num);
2979
- } else {
2980
- const visibleFn = function (locator, $XPath, num) {
2981
- eval($XPath); // eslint-disable-line no-eval
2982
- return $XPath(null, locator).filter(el => el.offsetParent !== null).length === num;
2983
- };
2984
- waiter = context.waitForFunction(visibleFn, { timeout: waitTimeout }, locator.value, $XPath.toString(), num);
2985
- }
2986
- return waiter.catch((err) => {
2987
- throw new Error(`The number of elements (${locator.toString()}) is not ${num} after ${waitTimeout / 1000} sec\n${err.message}`);
2988
- });
2989
- }
2990
-
2991
- /**
2992
- * Waits for element to be clickable (by default waits for 1sec).
2993
- * Element can be located by CSS or XPath.
2994
- *
2995
- * ```js
2996
- * I.waitForClickable('.btn.continue');
2997
- * I.waitForClickable('.btn.continue', 5); // wait for 5 secs
2998
- * ```
2999
- *
3000
- * @param {CodeceptJS.LocatorOrString} locator element located by CSS|XPath|strict locator.
3001
- * @param {number} [sec] (optional, `1` by default) time in seconds to wait
3002
- * @returns {void} automatically synchronized promise through #recorder
3003
- *
3004
- */
3005
- async waitForClickable(locator, waitTimeout) {
3006
- const els = await this._locate(locator);
3007
- assertElementExists(els, locator);
3008
-
3009
- return this.waitForFunction(isElementClickable, [els[0]], waitTimeout).catch(async (e) => {
3010
- if (/Waiting failed/i.test(e.message) || /failed: timeout/i.test(e.message)) {
3011
- throw new Error(`element ${new Locator(locator).toString()} still not clickable after ${waitTimeout || this.options.waitForTimeout / 1000} sec`);
3012
- } else {
3013
- throw e;
3014
- }
3015
- });
3016
- }
3017
-
3018
- /**
3019
- * Waits for element to be present on page (by default waits for 1sec).
3020
- * Element can be located by CSS or XPath.
3021
- *
3022
- * ```js
3023
- * I.waitForElement('.btn.continue');
3024
- * I.waitForElement('.btn.continue', 5); // wait for 5 secs
3025
- * ```
3026
- *
3027
- * @param {CodeceptJS.LocatorOrString} locator element located by CSS|XPath|strict locator.
3028
- * @param {number} [sec] (optional, `1` by default) time in seconds to wait
3029
- * @returns {void} automatically synchronized promise through #recorder
3030
- *
3031
- * {{ react }}
3032
- */
3033
- async waitForElement(locator, sec) {
3034
- const waitTimeout = sec ? sec * 1000 : this.options.waitForTimeout;
3035
- locator = new Locator(locator, 'css');
3036
-
3037
- let waiter;
3038
- const context = await this._getContext();
3039
- if (locator.isCSS()) {
3040
- waiter = context.waitForSelector(locator.simplify(), { timeout: waitTimeout });
3041
- } else {
3042
- waiter = context.waitForXPath(locator.value, { timeout: waitTimeout });
3043
- }
3044
- return waiter.catch((err) => {
3045
- throw new Error(`element (${locator.toString()}) still not present on page after ${waitTimeout / 1000} sec\n${err.message}`);
3046
- });
3047
- }
3048
-
3049
- /**
3050
- * Waits for an element to become visible on a page (by default waits for 1sec).
3051
- * Element can be located by CSS or XPath.
3052
- *
3053
- * ```js
3054
- * I.waitForVisible('#popup');
3055
- * ```
3056
- *
3057
- * @param {CodeceptJS.LocatorOrString} locator element located by CSS|XPath|strict locator.
3058
- * @param {number} [sec=1] (optional, `1` by default) time in seconds to wait
3059
- * @returns {void} automatically synchronized promise through #recorder
3060
- *
3061
- *
3062
- * {{ react }}
3063
- */
3064
- async waitForVisible(locator, sec) {
3065
- const waitTimeout = sec ? sec * 1000 : this.options.waitForTimeout;
3066
- locator = new Locator(locator, 'css');
3067
- await this.context;
3068
- let waiter;
3069
- const context = await this._getContext();
3070
- if (locator.isCSS()) {
3071
- waiter = context.waitForSelector(locator.simplify(), { timeout: waitTimeout, visible: true });
3072
- } else {
3073
- waiter = context.waitForXPath(locator.value, { timeout: waitTimeout, visible: true });
3074
- }
3075
- return waiter.catch((err) => {
3076
- throw new Error(`element (${locator.toString()}) still not visible after ${waitTimeout / 1000} sec\n${err.message}`);
3077
- });
3078
- }
3079
-
3080
- /**
3081
- * Waits for an element to be removed or become invisible on a page (by default waits for 1sec).
3082
- * Element can be located by CSS or XPath.
3083
- *
3084
- * ```js
3085
- * I.waitForInvisible('#popup');
3086
- * ```
3087
- *
3088
- * @param {CodeceptJS.LocatorOrString} locator element located by CSS|XPath|strict locator.
3089
- * @param {number} [sec=1] (optional, `1` by default) time in seconds to wait
3090
- * @returns {void} automatically synchronized promise through #recorder
3091
- *
3092
- */
3093
- async waitForInvisible(locator, sec) {
3094
- const waitTimeout = sec ? sec * 1000 : this.options.waitForTimeout;
3095
- locator = new Locator(locator, 'css');
3096
- await this.context;
3097
- let waiter;
3098
- const context = await this._getContext();
3099
- if (locator.isCSS()) {
3100
- waiter = context.waitForSelector(locator.simplify(), { timeout: waitTimeout, hidden: true });
3101
- } else {
3102
- waiter = context.waitForXPath(locator.value, { timeout: waitTimeout, hidden: true });
3103
- }
3104
- return waiter.catch((err) => {
3105
- throw new Error(`element (${locator.toString()}) still visible after ${waitTimeout / 1000} sec\n${err.message}`);
3106
- });
3107
- }
3108
-
3109
- /**
3110
- * Waits for an element to hide (by default waits for 1sec).
3111
- * Element can be located by CSS or XPath.
3112
- *
3113
- * ```js
3114
- * I.waitToHide('#popup');
3115
- * ```
3116
- *
3117
- * @param {CodeceptJS.LocatorOrString} locator element located by CSS|XPath|strict locator.
3118
- * @param {number} [sec=1] (optional, `1` by default) time in seconds to wait
3119
- * @returns {void} automatically synchronized promise through #recorder
3120
- *
3121
- */
3122
- async waitToHide(locator, sec) {
3123
- const waitTimeout = sec ? sec * 1000 : this.options.waitForTimeout;
3124
- locator = new Locator(locator, 'css');
3125
- let waiter;
3126
- const context = await this._getContext();
3127
- if (locator.isCSS()) {
3128
- waiter = context.waitForSelector(locator.simplify(), { timeout: waitTimeout, hidden: true });
3129
- } else {
3130
- waiter = context.waitForXPath(locator.value, { timeout: waitTimeout, hidden: true });
3131
- }
3132
- return waiter.catch((err) => {
3133
- throw new Error(`element (${locator.toString()}) still not hidden after ${waitTimeout / 1000} sec\n${err.message}`);
3134
- });
3135
- }
3136
-
3137
- /**
3138
- * Waits for number of tabs.
3139
- *
3140
- * ```js
3141
- * I.waitForNumberOfTabs(2);
3142
- * ```
3143
- *
3144
- * @param {number} expectedTabs expecting the number of tabs.
3145
- * @param {number} sec number of secs to wait.
3146
- * @returns {void} automatically synchronized promise through #recorder
3147
- *
3148
- */
3149
- async waitForNumberOfTabs(expectedTabs, sec) {
3150
- const waitTimeout = sec ? sec * 1000 : this.options.waitForTimeout;
3151
- let currentTabs;
3152
- let count = 0;
3153
-
3154
- do {
3155
- currentTabs = await this.grabNumberOfOpenTabs();
3156
- await this.wait(1);
3157
- count += 1000;
3158
- if (currentTabs >= expectedTabs) return;
3159
- } while (count <= waitTimeout);
3160
-
3161
- throw new Error(`Expected ${expectedTabs} tabs are not met after ${waitTimeout / 1000} sec.`);
3162
- }
3163
-
3164
- async _getContext() {
3165
- if (this.context && this.context.constructor.name === 'Frame') {
3166
- return this.context;
3167
- }
3168
- return this.page;
3169
- }
3170
-
3171
- /**
3172
- * Waiting for the part of the URL to match the expected. Useful for SPA to understand that page was changed.
3173
- *
3174
- * ```js
3175
- * I.waitInUrl('/info', 2);
3176
- * ```
3177
- *
3178
- * @param {string} urlPart value to check.
3179
- * @param {number} [sec=1] (optional, `1` by default) time in seconds to wait
3180
- * @returns {void} automatically synchronized promise through #recorder
3181
- *
3182
- */
3183
- async waitInUrl(urlPart, sec = null) {
3184
- const waitTimeout = sec ? sec * 1000 : this.options.waitForTimeout;
3185
-
3186
- return this.page.waitForFunction((urlPart) => {
3187
- const currUrl = decodeURIComponent(decodeURIComponent(decodeURIComponent(window.location.href)));
3188
- return currUrl.indexOf(urlPart) > -1;
3189
- }, { timeout: waitTimeout }, urlPart).catch(async (e) => {
3190
- const currUrl = await this._getPageUrl(); // Required because the waitForFunction can't return data.
3191
- if (/Waiting failed:/i.test(e.message) || /failed: timeout/i.test(e.message)) {
3192
- throw new Error(`expected url to include ${urlPart}, but found ${currUrl}`);
3193
- } else {
3194
- throw e;
3195
- }
3196
- });
3197
- }
3198
-
3199
- /**
3200
- * Waits for the entire URL to match the expected
3201
- *
3202
- * ```js
3203
- * I.waitUrlEquals('/info', 2);
3204
- * I.waitUrlEquals('http://127.0.0.1:8000/info');
3205
- * ```
3206
- *
3207
- * @param {string} urlPart value to check.
3208
- * @param {number} [sec=1] (optional, `1` by default) time in seconds to wait
3209
- * @returns {void} automatically synchronized promise through #recorder
3210
- *
3211
- */
3212
- async waitUrlEquals(urlPart, sec = null) {
3213
- const waitTimeout = sec ? sec * 1000 : this.options.waitForTimeout;
3214
-
3215
- const baseUrl = this.options.url;
3216
- if (urlPart.indexOf('http') < 0) {
3217
- urlPart = baseUrl + urlPart;
3218
- }
3219
-
3220
- return this.page.waitForFunction((urlPart) => {
3221
- const currUrl = decodeURIComponent(decodeURIComponent(decodeURIComponent(window.location.href)));
3222
- return currUrl.indexOf(urlPart) > -1;
3223
- }, { timeout: waitTimeout }, urlPart).catch(async (e) => {
3224
- const currUrl = await this._getPageUrl(); // Required because the waitForFunction can't return data.
3225
- if (/Waiting failed/i.test(e.message) || /failed: timeout/i.test(e.message)) {
3226
- throw new Error(`expected url to be ${urlPart}, but found ${currUrl}`);
3227
- } else {
3228
- throw e;
3229
- }
3230
- });
3231
- }
3232
-
3233
- /**
3234
- * Waits for a text to appear (by default waits for 1sec).
3235
- * Element can be located by CSS or XPath.
3236
- * Narrow down search results by providing context.
3237
- *
3238
- * ```js
3239
- * I.waitForText('Thank you, form has been submitted');
3240
- * I.waitForText('Thank you, form has been submitted', 5, '#modal');
3241
- * ```
3242
- *
3243
- * @param {string }text to wait for.
3244
- * @param {number} [sec=1] (optional, `1` by default) time in seconds to wait
3245
- * @param {CodeceptJS.LocatorOrString} [context] (optional) element located by CSS|XPath|strict locator.
3246
- * @returns {void} automatically synchronized promise through #recorder
3247
- *
3248
- */
3249
- async waitForText(text, sec = null, context = null) {
3250
- const waitTimeout = sec ? sec * 1000 : this.options.waitForTimeout;
3251
- let waiter;
3252
-
3253
- const contextObject = await this._getContext();
3254
-
3255
- if (context) {
3256
- const locator = new Locator(context, 'css');
3257
- if (locator.isCSS()) {
3258
- waiter = contextObject.waitForFunction((locator, text) => {
3259
- const el = document.querySelector(locator);
3260
- if (!el) return false;
3261
- return el.innerText.indexOf(text) > -1;
3262
- }, { timeout: waitTimeout }, locator.value, text);
3263
- }
3264
-
3265
- if (locator.isXPath()) {
3266
- waiter = contextObject.waitForFunction((locator, text, $XPath) => {
3267
- eval($XPath); // eslint-disable-line no-eval
3268
- const el = $XPath(null, locator);
3269
- if (!el.length) return false;
3270
- return el[0].innerText.indexOf(text) > -1;
3271
- }, { timeout: waitTimeout }, locator.value, text, $XPath.toString());
3272
- }
3273
- } else {
3274
- waiter = contextObject.waitForFunction(text => document.body && document.body.innerText.indexOf(text) > -1, { timeout: waitTimeout }, text);
3275
- }
3276
-
3277
- return waiter.catch((err) => {
3278
- throw new Error(`Text "${text}" was not found on page after ${waitTimeout / 1000} sec\n${err.message}`);
3279
- });
3280
- }
3281
-
3282
- /**
3283
- * Waits for a network request.
3284
- *
3285
- * ```js
3286
- * I.waitForRequest('http://example.com/resource');
3287
- * I.waitForRequest(request => request.url() === 'http://example.com' && request.method() === 'GET');
3288
- * ```
3289
- *
3290
- * @param {string|function} urlOrPredicate
3291
- * @param {?number} [sec=null] seconds to wait
3292
- */
3293
- async waitForRequest(urlOrPredicate, sec = null) {
3294
- const timeout = sec ? sec * 1000 : this.options.waitForTimeout;
3295
- return this.page.waitForRequest(urlOrPredicate, { timeout });
3296
- }
3297
-
3298
- /**
3299
- * Waits for a network response.
3300
- *
3301
- * ```js
3302
- * I.waitForResponse('http://example.com/resource');
3303
- * I.waitForResponse(response => response.url() === 'http://example.com' && response.request().method() === 'GET');
3304
- * ```
3305
- *
3306
- * @param {string|function} urlOrPredicate
3307
- * @param {?number} [sec=null] number of seconds to wait
3308
- */
3309
- async waitForResponse(urlOrPredicate, sec = null) {
3310
- const timeout = sec ? sec * 1000 : this.options.waitForTimeout;
3311
- return this.page.waitForResponse(urlOrPredicate, { timeout });
3312
- }
3313
-
3314
- /**
3315
- * Switches frame or in case of null locator reverts to parent.
3316
- *
3317
- * ```js
3318
- * I.switchTo('iframe'); // switch to first iframe
3319
- * I.switchTo(); // switch back to main page
3320
- * ```
3321
- *
3322
- * @param {?CodeceptJS.LocatorOrString} [locator=null] (optional, `null` by default) element located by CSS|XPath|strict locator.
3323
- * @returns {void} automatically synchronized promise through #recorder
3324
- *
3325
- */
3326
- async switchTo(locator) {
3327
- if (Number.isInteger(locator)) {
3328
- // Select by frame index of current context
3329
-
3330
- let childFrames = null;
3331
- if (this.context && typeof this.context.childFrames === 'function') {
3332
- childFrames = this.context.childFrames();
3333
- } else {
3334
- childFrames = this.page.mainFrame().childFrames();
3335
- }
3336
-
3337
- if (locator >= 0 && locator < childFrames.length) {
3338
- this.context = childFrames[locator];
3339
- } else {
3340
- throw new Error('Element #invalidIframeSelector was not found by text|CSS|XPath');
3341
- }
3342
- return;
3343
- }
3344
- if (!locator) {
3345
- this.context = await this.page.mainFrame().$('body');
3346
- return;
3347
- }
3348
-
3349
- // iframe by selector
3350
- const els = await this._locate(locator);
3351
- assertElementExists(els, locator);
3352
- const contentFrame = await els[0].contentFrame();
3353
-
3354
- if (contentFrame) {
3355
- this.context = contentFrame;
3356
- } else {
3357
- this.context = els[0];
3358
- }
3359
- }
3360
-
3361
- /**
3362
- * Waits for a function to return true (waits for 1 sec by default).
3363
- * Running in browser context.
3364
- *
3365
- * ```js
3366
- * I.waitForFunction(fn[, [args[, timeout]])
3367
- * ```
3368
- *
3369
- * ```js
3370
- * I.waitForFunction(() => window.requests == 0);
3371
- * I.waitForFunction(() => window.requests == 0, 5); // waits for 5 sec
3372
- * I.waitForFunction((count) => window.requests == count, [3], 5) // pass args and wait for 5 sec
3373
- * ```
3374
- *
3375
- * @param {string|function} fn to be executed in browser context.
3376
- * @param {any[]|number} [argsOrSec] (optional, `1` by default) arguments for function or seconds.
3377
- * @param {number} [sec] (optional, `1` by default) time in seconds to wait
3378
- * @returns {void} automatically synchronized promise through #recorder
3379
- *
3380
- */
3381
- async waitForFunction(fn, argsOrSec = null, sec = null) {
3382
- let args = [];
3383
- if (argsOrSec) {
3384
- if (Array.isArray(argsOrSec)) {
3385
- args = argsOrSec;
3386
- } else if (typeof argsOrSec === 'number') {
3387
- sec = argsOrSec;
3388
- }
3389
- }
3390
- const waitTimeout = sec ? sec * 1000 : this.options.waitForTimeout;
3391
- const context = await this._getContext();
3392
- return context.waitForFunction(fn, { timeout: waitTimeout }, ...args);
3393
- }
3394
-
3395
- /**
3396
- * Waits for navigation to finish. By default, takes configured `waitForNavigation` option.
3397
- *
3398
- * See [Puppeteer's reference](https://github.com/GoogleChrome/puppeteer/blob/master/docs/api.md#pagewaitfornavigationoptions)
3399
- *
3400
- * @param {*} opts
3401
- */
3402
- async waitForNavigation(opts = {}) {
3403
- opts = {
3404
- timeout: this.options.getPageTimeout,
3405
- waitUntil: this.options.waitForNavigation,
3406
- ...opts,
3407
- };
3408
- return this.page.waitForNavigation(opts);
3409
- }
3410
-
3411
- async waitUntilExists(locator, sec) {
3412
- console.log(`waitUntilExists deprecated:
3413
- * use 'waitForElement' to wait for element to be attached
3414
- * use 'waitForDetached to wait for element to be removed'`);
3415
- return this.waitForDetached(locator, sec);
3416
- }
3417
-
3418
- /**
3419
- * Waits for an element to become not attached to the DOM on a page (by default waits for 1sec).
3420
- * Element can be located by CSS or XPath.
3421
- *
3422
- * ```js
3423
- * I.waitForDetached('#popup');
3424
- * ```
3425
- *
3426
- * @param {CodeceptJS.LocatorOrString} locator element located by CSS|XPath|strict locator.
3427
- * @param {number} [sec=1] (optional, `1` by default) time in seconds to wait
3428
- * @returns {void} automatically synchronized promise through #recorder
3429
- *
3430
- */
3431
- async waitForDetached(locator, sec) {
3432
- const waitTimeout = sec ? sec * 1000 : this.options.waitForTimeout;
3433
- locator = new Locator(locator, 'css');
3434
-
3435
- let waiter;
3436
- const context = await this._getContext();
3437
- if (locator.isCSS()) {
3438
- const visibleFn = function (locator) {
3439
- return document.querySelector(locator) === null;
3440
- };
3441
- waiter = context.waitForFunction(visibleFn, { timeout: waitTimeout }, locator.value);
3442
- } else {
3443
- const visibleFn = function (locator, $XPath) {
3444
- eval($XPath); // eslint-disable-line no-eval
3445
- return $XPath(null, locator).length === 0;
3446
- };
3447
- waiter = context.waitForFunction(visibleFn, { timeout: waitTimeout }, locator.value, $XPath.toString());
3448
- }
3449
- return waiter.catch((err) => {
3450
- throw new Error(`element (${locator.toString()}) still on page after ${waitTimeout / 1000} sec\n${err.message}`);
3451
- });
3452
- }
3453
-
3454
- async _waitForAction() {
3455
- return this.wait(this.options.waitForAction / 1000);
3456
- }
3457
-
3458
- /**
3459
- * Grab the data from performance timing using Navigation Timing API.
3460
- * The returned data will contain following things in ms:
3461
- * - responseEnd,
3462
- * - domInteractive,
3463
- * - domContentLoadedEventEnd,
3464
- * - loadEventEnd
3465
- * Resumes test execution, so **should be used inside an async function with `await`** operator.
3466
- *
3467
- * ```js
3468
- * await I.amOnPage('https://example.com');
3469
- * let data = await I.grabDataFromPerformanceTiming();
3470
- * //Returned data
3471
- * { // all results are in [ms]
3472
- * responseEnd: 23,
3473
- * domInteractive: 44,
3474
- * domContentLoadedEventEnd: 196,
3475
- * loadEventEnd: 241
3476
- * }
3477
- * ```
3478
- * @returns {void} automatically synchronized promise through #recorder
3479
- *
3480
- */
3481
- async grabDataFromPerformanceTiming() {
3482
- return perfTiming;
3483
- }
3484
-
3485
- /**
3486
- * Grab the width, height, location of given locator.
3487
- * Provide `width` or `height`as second param to get your desired prop.
3488
- * Resumes test execution, so **should be used inside an async function with `await`** operator.
3489
- *
3490
- * Returns an object with `x`, `y`, `width`, `height` keys.
3491
- *
3492
- * ```js
3493
- * const value = await I.grabElementBoundingRect('h3');
3494
- * // value is like { x: 226.5, y: 89, width: 527, height: 220 }
3495
- * ```
3496
- *
3497
- * To get only one metric use second parameter:
3498
- *
3499
- * ```js
3500
- * const width = await I.grabElementBoundingRect('h3', 'width');
3501
- * // width == 527
3502
- * ```
3503
- * @param {LocatorOrString} locator element located by CSS|XPath|strict locator.
3504
- * @param {string=} elementSize x, y, width or height of the given element.
3505
- * @returns {Promise<DOMRect>|Promise<number>} Element bounding rectangle
3506
- *
3507
- */
3508
- async grabElementBoundingRect(locator, prop) {
3509
- const els = await this._locate(locator);
3510
- assertElementExists(els, locator);
3511
- const rect = await els[0].boundingBox();
3512
- if (prop) return rect[prop];
3513
- return rect;
3514
- }
3515
- }
3516
-
3517
- module.exports = Puppeteer;
3518
-
3519
- async function findElements(matcher, locator) {
3520
- if (locator.react) return findReact(matcher.executionContext(), locator);
3521
- locator = new Locator(locator, 'css');
3522
- if (!locator.isXPath()) return matcher.$$(locator.simplify());
3523
- // puppeteer version < 19.4.0 is no longer supported. This one is backward support.
3524
- if (puppeteer.default?.defaultBrowserRevision) {
3525
- return matcher.$$(`xpath/${locator.value}`);
3526
- }
3527
- return matcher.$x(locator.value);
3528
- }
3529
-
3530
- async function proceedClick(locator, context = null, options = {}) {
3531
- let matcher = await this.context;
3532
- if (context) {
3533
- const els = await this._locate(context);
3534
- assertElementExists(els, context);
3535
- matcher = els[0];
3536
- }
3537
- const els = await findClickable.call(this, matcher, locator);
3538
- if (context) {
3539
- assertElementExists(els, locator, 'Clickable element', `was not found inside element ${new Locator(context).toString()}`);
3540
- } else {
3541
- assertElementExists(els, locator, 'Clickable element');
3542
- }
3543
-
3544
- highlightActiveElement.call(this, els[0], await this._getContext());
3545
-
3546
- await els[0].click(options);
3547
- const promises = [];
3548
- if (options.waitForNavigation) {
3549
- promises.push(this.waitForNavigation());
3550
- }
3551
- promises.push(this._waitForAction());
3552
-
3553
- return Promise.all(promises);
3554
- }
3555
-
3556
- async function findClickable(matcher, locator) {
3557
- if (locator.react) return findReact(matcher.executionContext(), locator);
3558
- locator = new Locator(locator);
3559
- if (!locator.isFuzzy()) return findElements.call(this, matcher, locator);
3560
-
3561
- let els;
3562
- const literal = xpathLocator.literal(locator.value);
3563
-
3564
- els = await findElements.call(this, matcher, Locator.clickable.narrow(literal));
3565
- if (els.length) return els;
3566
-
3567
- els = await findElements.call(this, matcher, Locator.clickable.wide(literal));
3568
- if (els.length) return els;
3569
-
3570
- try {
3571
- els = await findElements.call(this, matcher, Locator.clickable.self(literal));
3572
- if (els.length) return els;
3573
- } catch (err) {
3574
- // Do nothing
3575
- }
3576
-
3577
- return findElements.call(this, matcher, locator.value); // by css or xpath
3578
- }
3579
-
3580
- async function proceedSee(assertType, text, context, strict = false) {
3581
- let description;
3582
- let allText;
3583
- if (!context) {
3584
- let el = await this.context;
3585
-
3586
- if (el && !el.getProperty) {
3587
- // Fallback to body
3588
- el = await this.context.$('body');
3589
- }
3590
-
3591
- allText = [await el.getProperty('innerText').then(p => p.jsonValue())];
3592
- description = 'web application';
3593
- } else {
3594
- const locator = new Locator(context, 'css');
3595
- description = `element ${locator.toString()}`;
3596
- const els = await this._locate(locator);
3597
- assertElementExists(els, locator.toString());
3598
- allText = await Promise.all(els.map(el => el.getProperty('innerText').then(p => p.jsonValue())));
3599
- }
3600
-
3601
- if (strict) {
3602
- return allText.map(elText => equals(description)[assertType](text, elText));
3603
- }
3604
- return stringIncludes(description)[assertType](normalizeSpacesInString(text), normalizeSpacesInString(allText.join(' | ')));
3605
- }
3606
-
3607
- async function findCheckable(locator, context) {
3608
- let contextEl = await this.context;
3609
- if (typeof context === 'string') {
3610
- contextEl = await findElements.call(this, contextEl, (new Locator(context, 'css')).simplify());
3611
- contextEl = contextEl[0];
3612
- }
3613
-
3614
- const matchedLocator = new Locator(locator);
3615
- if (!matchedLocator.isFuzzy()) {
3616
- return findElements.call(this, contextEl, matchedLocator.simplify());
3617
- }
3618
-
3619
- const literal = xpathLocator.literal(locator);
3620
- let els = await findElements.call(this, contextEl, Locator.checkable.byText(literal));
3621
- if (els.length) {
3622
- return els;
3623
- }
3624
- els = await findElements.call(this, contextEl, Locator.checkable.byName(literal));
3625
- if (els.length) {
3626
- return els;
3627
- }
3628
- return findElements.call(this, contextEl, locator);
3629
- }
3630
-
3631
- async function proceedIsChecked(assertType, option) {
3632
- let els = await findCheckable.call(this, option);
3633
- assertElementExists(els, option, 'Checkable');
3634
- els = await Promise.all(els.map(el => el.getProperty('checked')));
3635
- els = await Promise.all(els.map(el => el.jsonValue()));
3636
- const selected = els.reduce((prev, cur) => prev || cur);
3637
- return truth(`checkable ${option}`, 'to be checked')[assertType](selected);
3638
- }
3639
-
3640
- async function findVisibleFields(locator) {
3641
- const els = await findFields.call(this, locator);
3642
- const visible = await Promise.all(els.map(el => el.boundingBox()));
3643
- return els.filter((el, index) => visible[index]);
3644
- }
3645
-
3646
- async function findFields(locator) {
3647
- const matchedLocator = new Locator(locator);
3648
- if (!matchedLocator.isFuzzy()) {
3649
- return this._locate(matchedLocator);
3650
- }
3651
- const literal = xpathLocator.literal(locator);
3652
-
3653
- let els = await this._locate({ xpath: Locator.field.labelEquals(literal) });
3654
- if (els.length) {
3655
- return els;
3656
- }
3657
-
3658
- els = await this._locate({ xpath: Locator.field.labelContains(literal) });
3659
- if (els.length) {
3660
- return els;
3661
- }
3662
- els = await this._locate({ xpath: Locator.field.byName(literal) });
3663
- if (els.length) {
3664
- return els;
3665
- }
3666
- return this._locate({ css: locator });
3667
- }
3668
-
3669
- async function proceedDragAndDrop(sourceLocator, destinationLocator) {
3670
- const src = await this._locate(sourceLocator);
3671
- assertElementExists(src, sourceLocator, 'Source Element');
3672
-
3673
- const dst = await this._locate(destinationLocator);
3674
- assertElementExists(dst, destinationLocator, 'Destination Element');
3675
-
3676
- // Note: Using public api .getClickablePoint becaues the .BoundingBox does not take into account iframe offsets
3677
- const dragSource = await getClickablePoint(src[0]);
3678
- const dragDestination = await getClickablePoint(dst[0]);
3679
-
3680
- // Drag start point
3681
- await this.page.mouse.move(dragSource.x, dragSource.y, { steps: 5 });
3682
- await this.page.mouse.down();
3683
-
3684
- // Drag destination
3685
- await this.page.mouse.move(dragDestination.x, dragDestination.y, { steps: 5 });
3686
- await this.page.mouse.up();
3687
-
3688
- await this._waitForAction();
3689
- }
3690
-
3691
- async function proceedSeeInField(assertType, field, value) {
3692
- const els = await findVisibleFields.call(this, field);
3693
- assertElementExists(els, field, 'Field');
3694
- const el = els[0];
3695
- const tag = await el.getProperty('tagName').then(el => el.jsonValue());
3696
- const fieldType = await el.getProperty('type').then(el => el.jsonValue());
3697
-
3698
- const proceedMultiple = async (elements) => {
3699
- const fields = Array.isArray(elements) ? elements : [elements];
3700
-
3701
- const elementValues = [];
3702
- for (const element of fields) {
3703
- elementValues.push(await element.getProperty('value').then(el => el.jsonValue()));
3704
- }
3705
-
3706
- if (typeof value === 'boolean') {
3707
- equals(`no. of items matching > 0: ${field}`)[assertType](value, !!elementValues.length);
3708
- } else {
3709
- if (assertType === 'assert') {
3710
- equals(`select option by ${field}`)[assertType](true, elementValues.length > 0);
3711
- }
3712
- elementValues.forEach(val => stringIncludes(`fields by ${field}`)[assertType](value, val));
3713
- }
3714
- };
3715
-
3716
- if (tag === 'SELECT') {
3717
- const selectedOptions = await el.$$('option:checked');
3718
- // locate option by values and check them
3719
- if (value === '') {
3720
- return proceedMultiple(selectedOptions);
3721
- }
3722
-
3723
- const options = await filterFieldsByValue(selectedOptions, value, true);
3724
- return proceedMultiple(options);
3725
- }
3726
-
3727
- if (tag === 'INPUT') {
3728
- if (fieldType === 'checkbox' || fieldType === 'radio') {
3729
- if (typeof value === 'boolean') {
3730
- // Filter by values
3731
- const options = await filterFieldsBySelectionState(els, true);
3732
- return proceedMultiple(options);
3733
- }
3734
-
3735
- const options = await filterFieldsByValue(els, value, true);
3736
- return proceedMultiple(options);
3737
- }
3738
- return proceedMultiple(els[0]);
3739
- }
3740
- const fieldVal = await el.getProperty('value').then(el => el.jsonValue());
3741
- return stringIncludes(`fields by ${field}`)[assertType](value, fieldVal);
3742
- }
3743
-
3744
- async function filterFieldsByValue(elements, value, onlySelected) {
3745
- const matches = [];
3746
- for (const element of elements) {
3747
- const val = await element.getProperty('value').then(el => el.jsonValue());
3748
- let isSelected = true;
3749
- if (onlySelected) {
3750
- isSelected = await elementSelected(element);
3751
- }
3752
- if ((value == null || val.indexOf(value) > -1) && isSelected) {
3753
- matches.push(element);
3754
- }
3755
- }
3756
- return matches;
3757
- }
3758
-
3759
- async function filterFieldsBySelectionState(elements, state) {
3760
- const matches = [];
3761
- for (const element of elements) {
3762
- const isSelected = await elementSelected(element);
3763
- if (isSelected === state) {
3764
- matches.push(element);
3765
- }
3766
- }
3767
- return matches;
3768
- }
3769
-
3770
- async function elementSelected(element) {
3771
- const type = await element.getProperty('type').then(el => el.jsonValue());
3772
-
3773
- if (type === 'checkbox' || type === 'radio') {
3774
- return element.getProperty('checked').then(el => el.jsonValue());
3775
- }
3776
- return element.getProperty('selected').then(el => el.jsonValue());
3777
- }
3778
-
3779
- function isFrameLocator(locator) {
3780
- locator = new Locator(locator);
3781
- if (locator.isFrame()) {
3782
- const _locator = new Locator(locator);
3783
- return _locator.value;
3784
- }
3785
- return false;
3786
- }
3787
-
3788
- function assertElementExists(res, locator, prefix, suffix) {
3789
- if (!res || res.length === 0) {
3790
- throw new ElementNotFound(locator, prefix, suffix);
3791
- }
3792
- }
3793
-
3794
- function $XPath(element, selector) {
3795
- const found = document.evaluate(selector, element || document.body, null, 5, null);
3796
- const res = [];
3797
- let current = null;
3798
- while (current = found.iterateNext()) {
3799
- res.push(current);
3800
- }
3801
- return res;
3802
- }
3803
-
3804
- async function targetCreatedHandler(page) {
3805
- if (!page) return;
3806
- this.withinLocator = null;
3807
- page.on('load', () => {
3808
- page.$('body')
3809
- .catch(() => null)
3810
- .then(context => this.context = context);
3811
- });
3812
- page.on('console', (msg) => {
3813
- this.debugSection(`Browser:${ucfirst(msg.type())}`, (msg._text || '') + msg.args().join(' '));
3814
- consoleLogStore.add(msg);
3815
- });
3816
-
3817
- if (this.options.userAgent) {
3818
- await page.setUserAgent(this.options.userAgent);
3819
- }
3820
- if (this.options.windowSize && this.options.windowSize.indexOf('x') > 0) {
3821
- const dimensions = this.options.windowSize.split('x');
3822
- const width = parseInt(dimensions[0], 10);
3823
- const height = parseInt(dimensions[1], 10);
3824
- await page.setViewport({ width, height });
3825
- }
3826
- }
3827
-
3828
- // BC compatibility for Puppeteer < 10
3829
- async function getClickablePoint(el) {
3830
- if (el.clickablePoint) return el.clickablePoint();
3831
- if (el._clickablePoint) return el._clickablePoint();
3832
- return null;
3833
- }
3834
-
3835
- // List of key values to key definitions
3836
- // https://github.com/GoogleChrome/puppeteer/blob/v1.20.0/lib/USKeyboardLayout.js
3837
- const keyDefinitionMap = {
3838
- /* eslint-disable quote-props */
3839
- '0': 'Digit0',
3840
- '1': 'Digit1',
3841
- '2': 'Digit2',
3842
- '3': 'Digit3',
3843
- '4': 'Digit4',
3844
- '5': 'Digit5',
3845
- '6': 'Digit6',
3846
- '7': 'Digit7',
3847
- '8': 'Digit8',
3848
- '9': 'Digit9',
3849
- 'a': 'KeyA',
3850
- 'b': 'KeyB',
3851
- 'c': 'KeyC',
3852
- 'd': 'KeyD',
3853
- 'e': 'KeyE',
3854
- 'f': 'KeyF',
3855
- 'g': 'KeyG',
3856
- 'h': 'KeyH',
3857
- 'i': 'KeyI',
3858
- 'j': 'KeyJ',
3859
- 'k': 'KeyK',
3860
- 'l': 'KeyL',
3861
- 'm': 'KeyM',
3862
- 'n': 'KeyN',
3863
- 'o': 'KeyO',
3864
- 'p': 'KeyP',
3865
- 'q': 'KeyQ',
3866
- 'r': 'KeyR',
3867
- 's': 'KeyS',
3868
- 't': 'KeyT',
3869
- 'u': 'KeyU',
3870
- 'v': 'KeyV',
3871
- 'w': 'KeyW',
3872
- 'x': 'KeyX',
3873
- 'y': 'KeyY',
3874
- 'z': 'KeyZ',
3875
- ';': 'Semicolon',
3876
- '=': 'Equal',
3877
- ',': 'Comma',
3878
- '-': 'Minus',
3879
- '.': 'Period',
3880
- '/': 'Slash',
3881
- '`': 'Backquote',
3882
- '[': 'BracketLeft',
3883
- '\\': 'Backslash',
3884
- ']': 'BracketRight',
3885
- '\'': 'Quote',
3886
- /* eslint-enable quote-props */
3887
- };
3888
-
3889
- function getNormalizedKey(key) {
3890
- const normalizedKey = getNormalizedKeyAttributeValue(key);
3891
- if (key !== normalizedKey) {
3892
- this.debugSection('Input', `Mapping key '${key}' to '${normalizedKey}'`);
3893
- }
3894
- // Use key definition to ensure correct key is displayed when Shift modifier is active
3895
- if (Object.prototype.hasOwnProperty.call(keyDefinitionMap, normalizedKey)) {
3896
- return keyDefinitionMap[normalizedKey];
3897
- }
3898
- return normalizedKey;
3899
- }
3900
-
3901
- function highlightActiveElement(element, context) {
3902
- if (this.options.highlightElement && global.debugMode) {
3903
- highlightElement(element, context);
3904
- }
3905
- }