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,4240 +0,0 @@
1
- let webdriverio;
2
-
3
- const assert = require('assert');
4
- const path = require('path');
5
- const fs = require('fs');
6
-
7
- const Helper = require('@codeceptjs/helper');
8
- const crypto = require('crypto');
9
- const stringIncludes = require('../assert/include').includes;
10
- const { urlEquals, equals } = require('../assert/equal');
11
- const { debug } = require('../output');
12
- const { empty } = require('../assert/empty');
13
- const { truth } = require('../assert/truth');
14
- const {
15
- xpathLocator,
16
- fileExists,
17
- decodeUrl,
18
- chunkArray,
19
- convertCssPropertiesToCamelCase,
20
- screenshotOutputFolder,
21
- getNormalizedKeyAttributeValue,
22
- modifierKeys,
23
- } = require('../utils');
24
- const {
25
- isColorProperty,
26
- convertColorToRGBA,
27
- } = require('../colorUtils');
28
- const ElementNotFound = require('./errors/ElementNotFound');
29
- const ConnectionRefused = require('./errors/ConnectionRefused');
30
- const Locator = require('../locator');
31
- const { highlightElement } = require('./scripts/highlightElement');
32
- const store = require('../store');
33
- const { focusElement } = require('./scripts/focusElement');
34
- const { blurElement } = require('./scripts/blurElement');
35
-
36
- const SHADOW = 'shadow';
37
- const webRoot = 'body';
38
-
39
- /**
40
- * ## Configuration
41
- *
42
- * This helper should be configured in codecept.conf.js
43
- *
44
- * @typedef WebDriverConfig
45
- * @type {object}
46
- * @prop {string} url - base url of website to be tested.
47
- * @prop {string} browser - Browser in which to perform testing.
48
- * @prop {string} [basicAuth] - (optional) the basic authentication to pass to base url. Example: {username: 'username', password: 'password'}
49
- * @prop {string} [host=localhost] - WebDriver host to connect.
50
- * @prop {number} [port=4444] - WebDriver port to connect.
51
- * @prop {string} [protocol=http] - protocol for WebDriver server.
52
- * @prop {string} [path=/wd/hub] - path to WebDriver server.
53
- * @prop {boolean} [restart=true] - restart browser between tests.
54
- * @prop {boolean|number} [smartWait=false] - **enables [SmartWait](http://codecept.io/acceptance/#smartwait)**; wait for additional milliseconds for element to appear. Enable for 5 secs: "smartWait": 5000.
55
- * @prop {boolean} [disableScreenshots=false] - don't save screenshots on failure.
56
- * @prop {boolean} [fullPageScreenshots=false] (optional - make full page screenshots on failure.
57
- * @prop {boolean} [uniqueScreenshotNames=false] - option to prevent screenshot override if you have scenarios with the same name in different suites.
58
- * @prop {boolean} [keepBrowserState=false] - keep browser state between tests when `restart` is set to false.
59
- * @prop {boolean} [keepCookies=false] - keep cookies between tests when `restart` set to false.
60
- * @prop {string} [windowSize=window] default window size. Set to `maximize` or a dimension in the format `640x480`.
61
- * @prop {number} [waitForTimeout=1000] sets default wait time in *ms* for all `wait*` functions.
62
- * @prop {object} [desiredCapabilities] Selenium's [desired capabilities](https://github.com/SeleniumHQ/selenium/wiki/DesiredCapabilities).
63
- * @prop {boolean} [manualStart=false] - do not start browser before a test, start it manually inside a helper with `this.helpers["WebDriver"]._startBrowser()`.
64
- * @prop {object} [timeouts] [WebDriver timeouts](http://webdriver.io/docs/timeouts.html) defined as hash.
65
- * @prop {boolean} [highlightElement] - highlight the interacting elements. Default: false. Note: only activate under verbose mode (--verbose).
66
- * @prop {string} [logLevel=silent] - level of logging verbosity. Default: silent. Options: trace | debug | info | warn | error | silent. More info: https://webdriver.io/docs/configuration/#loglevel
67
- * @prop {boolean} [devtoolsProtocol=false] - enable devtools protocol. Default: false. More info: https://webdriver.io/docs/automationProtocols/#devtools-protocol.
68
- */
69
- const config = {};
70
-
71
- /**
72
- * WebDriver helper which wraps [webdriverio](http://webdriver.io/) library to
73
- * manipulate browser using Selenium WebDriver or PhantomJS.
74
- *
75
- * WebDriver requires Selenium Server and ChromeDriver/GeckoDriver to be installed. Those tools can be easily installed via NPM. Please check [Testing with WebDriver](https://codecept.io/webdriver/#testing-with-webdriver) for more details.
76
- *
77
- * With the release of WebdriverIO version v8.14.0, and onwards, all driver management hassles are now a thing of the past 🙌. Read more [here](https://webdriver.io/blog/2023/07/31/driver-management/).
78
- * One of the significant advantages of this update is that you can now get rid of any driver services you previously had to manage, such as
79
- * `wdio-chromedriver-service`, `wdio-geckodriver-service`, `wdio-edgedriver-service`, `wdio-safaridriver-service`, and even `@wdio/selenium-standalone-service`.
80
- *
81
- * For those who require custom driver options, fear not; WebDriver Helper allows you to pass in driver options through custom WebDriver configuration.
82
- * If you have a custom grid, use a cloud service, or prefer to run your own driver, there's no need to worry since WebDriver Helper will only start a driver when there are no other connection information settings like hostname or port specified.
83
- *
84
- * <!-- configuration -->
85
- *
86
- * Example:
87
- *
88
- * ```js
89
- * {
90
- * helpers: {
91
- * WebDriver : {
92
- * smartWait: 5000,
93
- * browser: "chrome",
94
- * restart: false,
95
- * windowSize: "maximize",
96
- * timeouts: {
97
- * "script": 60000,
98
- * "page load": 10000
99
- * }
100
- * }
101
- * }
102
- * }
103
- * ```
104
- *
105
- * Testing Chrome locally is now more convenient than ever. You can define a browser channel, and WebDriver Helper will take care of downloading the specified browser version for you.
106
- * For example:
107
- *
108
- * ```js
109
- * {
110
- * helpers: {
111
- * WebDriver : {
112
- * smartWait: 5000,
113
- * browser: "chrome",
114
- * browserVersion: '116.0.5793.0', // or 'stable', 'beta', 'dev' or 'canary'
115
- * restart: false,
116
- * windowSize: "maximize",
117
- * timeouts: {
118
- * "script": 60000,
119
- * "page load": 10000
120
- * }
121
- * }
122
- * }
123
- * }
124
- * ```
125
- *
126
- *
127
- * Example with basic authentication
128
- * ```js
129
- * {
130
- * helpers: {
131
- * WebDriver : {
132
- * smartWait: 5000,
133
- * browser: "chrome",
134
- * basicAuth: {username: 'username', password: 'password'},
135
- * restart: false,
136
- * windowSize: "maximize",
137
- * timeouts: {
138
- * "script": 60000,
139
- * "page load": 10000
140
- * }
141
- * }
142
- * }
143
- * }
144
- * ```
145
- *
146
- * Additional configuration params can be used from [webdriverio
147
- * website](http://webdriver.io/guide/getstarted/configuration.html).
148
- *
149
- * ### Headless Chrome
150
- *
151
- * ```js
152
- * {
153
- * helpers: {
154
- * WebDriver : {
155
- * url: "http://localhost",
156
- * browser: "chrome",
157
- * desiredCapabilities: {
158
- * chromeOptions: {
159
- * args: [ "--headless", "--disable-gpu", "--no-sandbox" ]
160
- * }
161
- * }
162
- * }
163
- * }
164
- * }
165
- * ```
166
- *
167
- * ### Running with devtools protocol
168
- *
169
- * ```js
170
- * {
171
- * helpers: {
172
- * WebDriver : {
173
- * url: "http://localhost",
174
- * browser: "chrome",
175
- * devtoolsProtocol: true,
176
- * desiredCapabilities: {
177
- * chromeOptions: {
178
- * args: [ "--headless", "--disable-gpu", "--no-sandbox" ]
179
- * }
180
- * }
181
- * }
182
- * }
183
- * }
184
- * ```
185
- *
186
- * ### Internet Explorer
187
- *
188
- * Additional configuration params can be used from [IE options](https://seleniumhq.github.io/selenium/docs/api/rb/Selenium/WebDriver/IE/Options.html)
189
- *
190
- * ```js
191
- * {
192
- * helpers: {
193
- * WebDriver : {
194
- * url: "http://localhost",
195
- * browser: "internet explorer",
196
- * desiredCapabilities: {
197
- * ieOptions: {
198
- * "ie.browserCommandLineSwitches": "-private",
199
- * "ie.usePerProcessProxy": true,
200
- * "ie.ensureCleanSession": true,
201
- * }
202
- * }
203
- * }
204
- * }
205
- * }
206
- * ```
207
- *
208
- * ### Selenoid Options
209
- *
210
- * [Selenoid](https://aerokube.com/selenoid/latest/) is a modern way to run Selenium inside Docker containers.
211
- * Selenoid is easy to set up and provides more features than original Selenium Server. Use `selenoidOptions` to set Selenoid capabilities
212
- *
213
- * ```js
214
- * {
215
- * helpers: {
216
- * WebDriver : {
217
- * url: "http://localhost",
218
- * browser: "chrome",
219
- * desiredCapabilities: {
220
- * selenoidOptions: {
221
- * enableVNC: true,
222
- * }
223
- * }
224
- * }
225
- * }
226
- * }
227
- * ```
228
- *
229
- * ### Connect Through proxy
230
- *
231
- * CodeceptJS also provides flexible options when you want to execute tests to Selenium servers through proxy. You will
232
- * need to update the `helpers.WebDriver.capabilities.proxy` key.
233
- *
234
- * ```js
235
- * {
236
- * helpers: {
237
- * WebDriver: {
238
- * capabilities: {
239
- * proxy: {
240
- * "proxyType": "manual|pac",
241
- * "proxyAutoconfigUrl": "URL TO PAC FILE",
242
- * "httpProxy": "PROXY SERVER",
243
- * "sslProxy": "PROXY SERVER",
244
- * "ftpProxy": "PROXY SERVER",
245
- * "socksProxy": "PROXY SERVER",
246
- * "socksUsername": "USERNAME",
247
- * "socksPassword": "PASSWORD",
248
- * "noProxy": "BYPASS ADDRESSES"
249
- * }
250
- * }
251
- * }
252
- * }
253
- * }
254
- * ```
255
- * For example,
256
- *
257
- * ```js
258
- * {
259
- * helpers: {
260
- * WebDriver: {
261
- * capabilities: {
262
- * proxy: {
263
- * "proxyType": "manual",
264
- * "httpProxy": "http://corporate.proxy:8080",
265
- * "socksUsername": "codeceptjs",
266
- * "socksPassword": "secret",
267
- * "noProxy": "127.0.0.1,localhost"
268
- * }
269
- * }
270
- * }
271
- * }
272
- * }
273
- * ```
274
- *
275
- * Please refer to [Selenium - Proxy Object](https://github.com/SeleniumHQ/selenium/wiki/DesiredCapabilities) for more
276
- * information.
277
- *
278
- * ### Cloud Providers
279
- *
280
- * WebDriver makes it possible to execute tests against services like `Sauce Labs` `BrowserStack` `TestingBot`
281
- * Check out their documentation on [available parameters](http://webdriver.io/guide/usage/cloudservices.html)
282
- *
283
- * Connecting to `BrowserStack` and `Sauce Labs` is simple. All you need to do
284
- * is set the `user` and `key` parameters. WebDriver automatically know which
285
- * service provider to connect to.
286
- *
287
- * ```js
288
- * {
289
- * helpers:{
290
- * WebDriver: {
291
- * url: "YOUR_DESIRED_HOST",
292
- * user: "YOUR_BROWSERSTACK_USER",
293
- * key: "YOUR_BROWSERSTACK_KEY",
294
- * capabilities: {
295
- * "browserName": "chrome",
296
- *
297
- * // only set this if you're using BrowserStackLocal to test a local domain
298
- * // "browserstack.local": true,
299
- *
300
- * // set this option to tell browserstack to provide addition debugging info
301
- * // "browserstack.debug": true,
302
- * }
303
- * }
304
- * }
305
- * }
306
- * ```
307
- *
308
- * #### SauceLabs
309
- *
310
- * SauceLabs can be configured via wdio service, which should be installed additionally:
311
- *
312
- * ```
313
- * npm i @wdio/sauce-service --save
314
- * ```
315
- *
316
- * It is important to make sure it is compatible with current webdriverio version.
317
- *
318
- * Enable `wdio` plugin in plugins list and add `sauce` service:
319
- *
320
- * ```js
321
- * plugins: {
322
- * wdio: {
323
- * enabled: true,
324
- * services: ['sauce'],
325
- * user: ... ,// saucelabs username
326
- * key: ... // saucelabs api key
327
- * // additional config, from sauce service
328
- * }
329
- * }
330
- * ```
331
- *
332
- * See [complete reference on webdriver.io](https://webdriver.io/docs/sauce-service.html).
333
- *
334
- * > Alternatively, use [codeceptjs-saucehelper](https://github.com/puneet0191/codeceptjs-saucehelper/) for better reporting.
335
- *
336
- * #### BrowserStack
337
- *
338
- * BrowserStack can be configured via wdio service, which should be installed additionally:
339
- *
340
- * ```
341
- * npm i @wdio/browserstack-service --save
342
- * ```
343
- *
344
- * It is important to make sure it is compatible with current webdriverio version.
345
- *
346
- * Enable `wdio` plugin in plugins list and add `browserstack` service:
347
- *
348
- * ```js
349
- * plugins: {
350
- * wdio: {
351
- * enabled: true,
352
- * services: ['browserstack'],
353
- * user: ... ,// browserstack username
354
- * key: ... // browserstack api key
355
- * // additional config, from browserstack service
356
- * }
357
- * }
358
- * ```
359
- *
360
- * See [complete reference on webdriver.io](https://webdriver.io/docs/browserstack-service.html).
361
- *
362
- * > Alternatively, use [codeceptjs-bshelper](https://github.com/PeterNgTr/codeceptjs-bshelper) for better reporting.
363
- *
364
- * #### TestingBot
365
- *
366
- * > **Recommended**: use official [TestingBot Helper](https://github.com/testingbot/codeceptjs-tbhelper).
367
- *
368
- * Alternatively, TestingBot can be configured via wdio service, which should be installed additionally:
369
- *
370
- * ```
371
- * npm i @wdio/testingbot-service --save
372
- * ```
373
- *
374
- * It is important to make sure it is compatible with current webdriverio version.
375
- *
376
- * Enable `wdio` plugin in plugins list and add `testingbot` service:
377
- *
378
- * ```js
379
- * plugins: {
380
- * wdio: {
381
- * enabled: true,
382
- * services: ['testingbot'],
383
- * user: ... ,// testingbot key
384
- * key: ... // testingbot secret
385
- * // additional config, from testingbot service
386
- * }
387
- * }
388
- * ```
389
- *
390
- * See [complete reference on webdriver.io](https://webdriver.io/docs/testingbot-service.html).
391
- *
392
- * #### Applitools
393
- *
394
- * Visual testing via Applitools service
395
- *
396
- * > Use [CodeceptJS Applitools Helper](https://github.com/PeterNgTr/codeceptjs-applitoolshelper) with Applitools wdio service.
397
- *
398
- *
399
- * ### Multiremote Capabilities
400
- *
401
- * This is a work in progress but you can control two browsers at a time right out of the box.
402
- * Individual control is something that is planned for a later version.
403
- *
404
- * Here is the [webdriverio docs](http://webdriver.io/guide/usage/multiremote.html) on the subject
405
- *
406
- * ```js
407
- * {
408
- * helpers: {
409
- * WebDriver: {
410
- * "multiremote": {
411
- * "MyChrome": {
412
- * "desiredCapabilities": {
413
- * "browserName": "chrome"
414
- * }
415
- * },
416
- * "MyFirefox": {
417
- * "desiredCapabilities": {
418
- * "browserName": "firefox"
419
- * }
420
- * }
421
- * }
422
- * }
423
- * }
424
- * }
425
- * ```
426
- *
427
- * ## Access From Helpers
428
- *
429
- * Receive a WebDriver client from a custom helper by accessing `browser` property:
430
- *
431
- * ```js
432
- * const { WebDriver } = this.helpers;
433
- * const browser = WebDriver.browser
434
- * ```
435
- *
436
- * ## Methods
437
- */
438
- class WebDriver extends Helper {
439
- constructor(config) {
440
- super(config);
441
- webdriverio = require('webdriverio');
442
-
443
- // set defaults
444
- this.root = webRoot;
445
- this.isWeb = true;
446
- this.isRunning = false;
447
- this.sessionWindows = {};
448
- this.activeSessionName = '';
449
- this.customLocatorStrategies = config.customLocatorStrategies;
450
-
451
- this._setConfig(config);
452
-
453
- Locator.addFilter((locator, result) => {
454
- if (typeof locator === 'string' && locator.indexOf('~') === 0) {
455
- // accessibility locator
456
- if (this.isWeb) {
457
- result.value = `[aria-label="${locator.slice(1)}"]`;
458
- result.type = 'css';
459
- result.output = `aria-label=${locator.slice(1)}`;
460
- }
461
- }
462
- });
463
- }
464
-
465
- _validateConfig(config) {
466
- const defaults = {
467
- logLevel: 'silent',
468
- // codeceptjs
469
- remoteFileUpload: true,
470
- smartWait: 0,
471
- waitForTimeout: 1000, // ms
472
- capabilities: {},
473
- restart: true,
474
- uniqueScreenshotNames: false,
475
- disableScreenshots: false,
476
- fullPageScreenshots: false,
477
- manualStart: false,
478
- keepCookies: false,
479
- keepBrowserState: false,
480
- deprecationWarnings: false,
481
- highlightElement: false,
482
- };
483
-
484
- // override defaults with config
485
- config = Object.assign(defaults, config);
486
-
487
- if (config.host) {
488
- // webdriverio spec
489
- config.hostname = config.host;
490
- config.path = '/wd/hub';
491
- }
492
- config.baseUrl = config.url || config.baseUrl;
493
- if (config.desiredCapabilities && Object.keys(config.desiredCapabilities).length) {
494
- config.capabilities = config.desiredCapabilities;
495
- }
496
- config.capabilities.browserName = config.browser || config.capabilities.browserName;
497
- config.capabilities.browserVersion = config.browserVersion || config.capabilities.browserVersion;
498
- if (config.capabilities.chromeOptions) {
499
- config.capabilities['goog:chromeOptions'] = config.capabilities.chromeOptions;
500
- delete config.capabilities.chromeOptions;
501
- }
502
- if (config.capabilities.firefoxOptions) {
503
- config.capabilities['moz:firefoxOptions'] = config.capabilities.firefoxOptions;
504
- delete config.capabilities.firefoxOptions;
505
- }
506
- if (config.capabilities.ieOptions) {
507
- config.capabilities['se:ieOptions'] = config.capabilities.ieOptions;
508
- delete config.capabilities.ieOptions;
509
- }
510
- if (config.capabilities.selenoidOptions) {
511
- config.capabilities['selenoid:options'] = config.capabilities.selenoidOptions;
512
- delete config.capabilities.selenoidOptions;
513
- }
514
-
515
- config.waitForTimeoutInSeconds = config.waitForTimeout / 1000; // convert to seconds
516
-
517
- if (!config.capabilities.platformName && (!config.url || !config.browser)) {
518
- throw new Error(`
519
- WebDriver requires at url and browser to be set.
520
- Check your codeceptjs config file to ensure these are set properly
521
- {
522
- "helpers": {
523
- "WebDriver": {
524
- "url": "YOUR_HOST"
525
- "browser": "YOUR_PREFERRED_TESTING_BROWSER"
526
- }
527
- }
528
- }
529
- `);
530
- }
531
-
532
- return config;
533
- }
534
-
535
- static _checkRequirements() {
536
- try {
537
- require('webdriverio');
538
- } catch (e) {
539
- return ['webdriverio@^6.12.1'];
540
- }
541
- }
542
-
543
- static _config() {
544
- return [{
545
- name: 'url',
546
- message: 'Base url of site to be tested',
547
- default: 'http://localhost',
548
- }, {
549
- name: 'browser',
550
- message: 'Browser in which testing will be performed',
551
- default: 'chrome',
552
- }];
553
- }
554
-
555
- _beforeSuite() {
556
- if (!this.options.restart && !this.options.manualStart && !this.isRunning) {
557
- this.debugSection('Session', 'Starting singleton browser session');
558
- return this._startBrowser();
559
- }
560
- }
561
-
562
- _lookupCustomLocator(customStrategy) {
563
- if (typeof (this.customLocatorStrategies) !== 'object') {
564
- return null;
565
- }
566
- const strategy = this.customLocatorStrategies[customStrategy];
567
- return typeof (strategy) === 'function' ? strategy : null;
568
- }
569
-
570
- _isCustomLocator(locator) {
571
- const locatorObj = new Locator(locator);
572
- if (locatorObj.isCustom()) {
573
- const customLocator = this._lookupCustomLocator(locatorObj.type);
574
- if (customLocator) {
575
- return true;
576
- }
577
- throw new Error('Please define "customLocatorStrategies" as an Object and the Locator Strategy as a "function".');
578
- }
579
- return false;
580
- }
581
-
582
- async _res(locator) {
583
- const res = (this._isShadowLocator(locator) || this._isCustomLocator(locator))
584
- ? await this._locate(locator)
585
- : await this.$$(withStrictLocator(locator));
586
- return res;
587
- }
588
-
589
- async _startBrowser() {
590
- try {
591
- if (this.options.multiremote) {
592
- this.browser = await webdriverio.multiremote(this.options.multiremote);
593
- } else {
594
- // remove non w3c capabilities
595
- delete this.options.capabilities.protocol;
596
- delete this.options.capabilities.hostname;
597
- delete this.options.capabilities.port;
598
- delete this.options.capabilities.path;
599
- if (this.options.devtoolsProtocol) {
600
- if (!['chrome', 'chromium'].includes(this.options.browser.toLowerCase())) throw Error('The devtools protocol is only working with Chrome or Chromium');
601
- this.options.automationProtocol = 'devtools';
602
- }
603
- this.browser = await webdriverio.remote(this.options);
604
- }
605
- } catch (err) {
606
- if (err.toString().indexOf('ECONNREFUSED')) {
607
- throw new ConnectionRefused(err);
608
- }
609
- throw err;
610
- }
611
-
612
- this.isRunning = true;
613
- if (this.options.timeouts && this.isWeb) {
614
- await this.defineTimeout(this.options.timeouts);
615
- }
616
-
617
- await this._resizeWindowIfNeeded(this.browser, this.options.windowSize);
618
-
619
- this.$$ = this.browser.$$.bind(this.browser);
620
-
621
- if (this._isCustomLocatorStrategyDefined()) {
622
- Object.keys(this.customLocatorStrategies).forEach(async (customLocator) => {
623
- this.debugSection('Weddriver', `adding custom locator strategy: ${customLocator}`);
624
- const locatorFunction = this._lookupCustomLocator(customLocator);
625
- this.browser.addLocatorStrategy(customLocator, locatorFunction);
626
- });
627
- }
628
-
629
- if (this.browser.capabilities && this.browser.capabilities.platformName) {
630
- this.browser.capabilities.platformName = this.browser.capabilities.platformName.toLowerCase();
631
- }
632
- return this.browser;
633
- }
634
-
635
- _isCustomLocatorStrategyDefined() {
636
- return this.customLocatorStrategies && Object.keys(this.customLocatorStrategies).length;
637
- }
638
-
639
- async _stopBrowser() {
640
- if (this.browser && this.isRunning) await this.browser.deleteSession();
641
- }
642
-
643
- async _before() {
644
- this.context = this.root;
645
- if (this.options.restart && !this.options.manualStart) return this._startBrowser();
646
- if (!this.isRunning && !this.options.manualStart) return this._startBrowser();
647
- if (this.browser) this.$$ = this.browser.$$.bind(this.browser);
648
- return this.browser;
649
- }
650
-
651
- async _after() {
652
- if (!this.isRunning) return;
653
- if (this.options.restart) {
654
- this.isRunning = false;
655
- return this.browser.deleteSession();
656
- }
657
- if (this.browser.isInsideFrame) await this.browser.switchToFrame(null);
658
-
659
- if (this.options.keepBrowserState) return;
660
-
661
- if (!this.options.keepCookies && this.options.capabilities.browserName) {
662
- this.debugSection('Session', 'cleaning cookies and localStorage');
663
- await this.browser.deleteCookies();
664
- }
665
- await this.browser.execute('localStorage.clear();').catch((err) => {
666
- if (!(err.message.indexOf("Storage is disabled inside 'data:' URLs.") > -1)) throw err;
667
- });
668
- await this.closeOtherTabs();
669
- return this.browser;
670
- }
671
-
672
- _afterSuite() {
673
- }
674
-
675
- _finishTest() {
676
- if (!this.options.restart && this.isRunning) return this._stopBrowser();
677
- }
678
-
679
- _session() {
680
- const defaultSession = this.browser;
681
- return {
682
- start: async (sessionName, opts) => {
683
- // opts.disableScreenshots = true; // screenshots cant be saved as session will be already closed
684
- opts = this._validateConfig(Object.assign(this.options, opts));
685
- this.debugSection('New Browser', JSON.stringify(opts));
686
- const browser = await webdriverio.remote(opts);
687
- this.activeSessionName = sessionName;
688
- if (opts.timeouts && this.isWeb) {
689
- await this._defineBrowserTimeout(browser, opts.timeouts);
690
- }
691
-
692
- await this._resizeWindowIfNeeded(browser, opts.windowSize);
693
-
694
- return browser;
695
- },
696
- stop: async (browser) => {
697
- if (!browser) return;
698
- return browser.deleteSession();
699
- },
700
- loadVars: async (browser) => {
701
- if (this.context !== this.root) throw new Error('Can\'t start session inside within block');
702
- this.browser = browser;
703
- this.$$ = this.browser.$$.bind(this.browser);
704
- this.sessionWindows[this.activeSessionName] = browser;
705
- },
706
- restoreVars: async (session) => {
707
- if (!session) {
708
- this.activeSessionName = '';
709
- }
710
- this.browser = defaultSession;
711
- this.$$ = this.browser.$$.bind(this.browser);
712
- },
713
- };
714
- }
715
-
716
- /**
717
- * Use [webdriverio](https://webdriver.io/docs/api.html) API inside a test.
718
- *
719
- * First argument is a description of an action.
720
- * Second argument is async function that gets this helper as parameter.
721
- *
722
- * { [`browser`](https://webdriver.io/docs/api.html)) } object from WebDriver API is available.
723
- *
724
- * ```js
725
- * I.useWebDriverTo('open multiple windows', async ({ browser }) {
726
- * // create new window
727
- * await browser.newWindow('https://webdriver.io');
728
- * });
729
- * ```
730
- *
731
- * @param {string} description used to show in logs.
732
- * @param {function} fn async functuion that executed with WebDriver helper as argument
733
- */
734
- useWebDriverTo(description, fn) {
735
- return this._useTo(...arguments);
736
- }
737
-
738
- async _failed() {
739
- if (this.context !== this.root) await this._withinEnd();
740
- }
741
-
742
- async _withinBegin(locator) {
743
- const frame = isFrameLocator(locator);
744
- if (frame) {
745
- this.browser.isInsideFrame = true;
746
- if (Array.isArray(frame)) {
747
- // this.switchTo(null);
748
- await forEachAsync(frame, async f => this.switchTo(f));
749
- return;
750
- }
751
- await this.switchTo(frame);
752
- return;
753
- }
754
- this.context = locator;
755
-
756
- let res = await this.browser.$$(withStrictLocator(locator));
757
- assertElementExists(res, locator);
758
- res = usingFirstElement(res);
759
- this.context = res.selector;
760
- this.$$ = res.$$.bind(res);
761
- }
762
-
763
- async _withinEnd() {
764
- if (this.browser.isInsideFrame) {
765
- this.browser.isInsideFrame = false;
766
- return this.switchTo(null);
767
- }
768
- this.context = this.root;
769
- this.$$ = this.browser.$$.bind(this.browser);
770
- }
771
-
772
- /**
773
- * Check if locator is type of "Shadow"
774
- *
775
- * @param {object} locator
776
- */
777
- _isShadowLocator(locator) {
778
- return locator.type === SHADOW || locator[SHADOW];
779
- }
780
-
781
- /**
782
- * Locate Element within the Shadow Dom
783
- *
784
- * @param {object} locator
785
- */
786
- async _locateShadow(locator) {
787
- const shadow = locator.value ? locator.value : locator[SHADOW];
788
- const shadowSequence = [];
789
- let elements;
790
-
791
- if (!Array.isArray(shadow)) {
792
- throw new Error(`Shadow '${shadow}' should be defined as an Array of elements.`);
793
- }
794
-
795
- // traverse through the Shadow locators in sequence
796
- for (let index = 0; index < shadow.length; index++) {
797
- const shadowElement = shadow[index];
798
- shadowSequence.push(shadowElement);
799
-
800
- if (!elements) {
801
- elements = await (this.browser.$$(shadowElement));
802
- } else if (Array.isArray(elements)) {
803
- elements = await elements[0].shadow$$(shadowElement);
804
- } else if (elements) {
805
- elements = await elements.shadow$$(shadowElement);
806
- }
807
-
808
- if (!elements || !elements[0]) {
809
- throw new Error(`Shadow Element '${shadowElement}' is not found. It is possible the element is incorrect or elements sequence is incorrect. Please verify the sequence '${shadowSequence.join('>')}' is correctly chained.`);
810
- }
811
- }
812
-
813
- this.debugSection('Elements', `Found ${elements.length} '${SHADOW}' elements`);
814
-
815
- return elements;
816
- }
817
-
818
- /**
819
- * Smart Wait to locate an element
820
- *
821
- * @param {object} locator
822
- */
823
- async _smartWait(locator) {
824
- this.debugSection(`SmartWait (${this.options.smartWait}ms)`, `Locating ${JSON.stringify(locator)} in ${this.options.smartWait}`);
825
- await this.defineTimeout({ implicit: this.options.smartWait });
826
- }
827
-
828
- /**
829
- * Get elements by different locator types, including strict locator.
830
- * Should be used in custom helpers:
831
- *
832
- * ```js
833
- * this.helpers['WebDriver']._locate({name: 'password'}).then //...
834
- * ```
835
- *
836
- *
837
- * @param {CodeceptJS.LocatorOrString} locator element located by CSS|XPath|strict locator.
838
- */
839
- async _locate(locator, smartWait = false) {
840
- if (require('../store').debugMode) smartWait = false;
841
-
842
- // special locator type for Shadow DOM
843
- if (this._isShadowLocator(locator)) {
844
- if (!this.options.smartWait || !smartWait) {
845
- const els = await this._locateShadow(locator);
846
- return els;
847
- }
848
-
849
- const els = await this._locateShadow(locator);
850
- return els;
851
- }
852
-
853
- // special locator type for React
854
- if (locator.react) {
855
- const els = await this.browser.react$$(locator.react, locator.props || undefined, locator.state || undefined);
856
- this.debugSection('Elements', `Found ${els.length} react components`);
857
- return els;
858
- }
859
-
860
- if (!this.options.smartWait || !smartWait) {
861
- if (this._isCustomLocator(locator)) {
862
- const locatorObj = new Locator(locator);
863
- return this.browser.custom$$(locatorObj.type, locatorObj.value);
864
- }
865
-
866
- const els = await this.$$(withStrictLocator(locator));
867
- return els;
868
- }
869
-
870
- await this._smartWait(locator);
871
-
872
- if (this._isCustomLocator(locator)) {
873
- const locatorObj = new Locator(locator);
874
- return this.browser.custom$$(locatorObj.type, locatorObj.value);
875
- }
876
-
877
- const els = await this.$$(withStrictLocator(locator));
878
- await this.defineTimeout({ implicit: 0 });
879
- return els;
880
- }
881
-
882
- _grabCustomLocator(locator) {
883
- if (typeof locator === 'string') {
884
- locator = new Locator(locator);
885
- }
886
- return locator.value ? locator.value : locator.custom;
887
- }
888
-
889
- /**
890
- * Find a checkbox by providing human-readable text:
891
- *
892
- * ```js
893
- * this.helpers['WebDriver']._locateCheckable('I agree with terms and conditions').then // ...
894
- * ```
895
- *
896
- * @param {CodeceptJS.LocatorOrString} locator element located by CSS|XPath|strict locator.
897
- */
898
- async _locateCheckable(locator) {
899
- return findCheckable.call(this, locator, this.$$.bind(this)).then(res => res);
900
- }
901
-
902
- /**
903
- * Find a clickable element by providing human-readable text:
904
- *
905
- * ```js
906
- * const els = await this.helpers.WebDriver._locateClickable('Next page');
907
- * const els = await this.helpers.WebDriver._locateClickable('Next page', '.pages');
908
- * ```
909
- *
910
- * @param {CodeceptJS.LocatorOrString} locator element located by CSS|XPath|strict locator.
911
- */
912
- async _locateClickable(locator, context) {
913
- const locateFn = prepareLocateFn.call(this, context);
914
- return findClickable.call(this, locator, locateFn);
915
- }
916
-
917
- /**
918
- * Find field elements by providing human-readable text:
919
- *
920
- * ```js
921
- * this.helpers['WebDriver']._locateFields('Your email').then // ...
922
- * ```
923
- *
924
- * @param {CodeceptJS.LocatorOrString} locator element located by CSS|XPath|strict locator.
925
- */
926
- async _locateFields(locator) {
927
- return findFields.call(this, locator).then(res => res);
928
- }
929
-
930
- /**
931
- * Grab WebElements for given locator
932
- * Resumes test execution, so **should be used inside an async function with `await`** operator.
933
- *
934
- * ```js
935
- * const webElements = await I.grabWebElements('#button');
936
- * ```
937
- *
938
- * @param {CodeceptJS.LocatorOrString} locator element located by CSS|XPath|strict locator.
939
- * @returns {Promise<*>} WebElement of being used Web helper
940
- *
941
- *
942
- */
943
- async grabWebElements(locator) {
944
- return this._locate(locator);
945
- }
946
-
947
- /**
948
- * Set [WebDriver timeouts](https://webdriver.io/docs/timeouts.html) in realtime.
949
- *
950
- * Timeouts are expected to be passed as object:
951
- *
952
- * ```js
953
- * I.defineTimeout({ script: 5000 });
954
- * I.defineTimeout({ implicit: 10000, pageLoad: 10000, script: 5000 });
955
- * ```
956
- *
957
- * @param {*} timeouts WebDriver timeouts object.
958
- */
959
- defineTimeout(timeouts) {
960
- return this._defineBrowserTimeout(this.browser, timeouts);
961
- }
962
-
963
- _defineBrowserTimeout(browser, timeouts) {
964
- return browser.setTimeout(timeouts);
965
- }
966
-
967
- /**
968
- * Opens a web page in a browser. Requires relative or absolute url.
969
- * If url starts with `/`, opens a web page of a site defined in `url` config parameter.
970
- *
971
- * ```js
972
- * I.amOnPage('/'); // opens main page of website
973
- * I.amOnPage('https://github.com'); // opens github
974
- * I.amOnPage('/login'); // opens a login page
975
- * ```
976
- *
977
- * @param {string} url url path or global url.
978
- * @returns {void} automatically synchronized promise through #recorder
979
- *
980
- *
981
- */
982
- amOnPage(url) {
983
- let split_url;
984
- if (this.config.basicAuth) {
985
- if (url.startsWith('/')) {
986
- url = this.config.url + url;
987
- }
988
- split_url = url.split('//');
989
- url = `${split_url[0]}//${this.config.basicAuth.username}:${this.config.basicAuth.password}@${split_url[1]}`;
990
- }
991
- return this.browser.url(url);
992
- }
993
-
994
- /**
995
- * Perform a click on a link or a button, given by a locator.
996
- * If a fuzzy locator is given, the page will be searched for a button, link, or image matching the locator string.
997
- * For buttons, the "value" attribute, "name" attribute, and inner text are searched. For links, the link text is searched.
998
- * For images, the "alt" attribute and inner text of any parent links are searched.
999
- *
1000
- * The second parameter is a context (CSS or XPath locator) to narrow the search.
1001
- *
1002
- * ```js
1003
- * // simple link
1004
- * I.click('Logout');
1005
- * // button of form
1006
- * I.click('Submit');
1007
- * // CSS button
1008
- * I.click('#form input[type=submit]');
1009
- * // XPath
1010
- * I.click('//form/*[@type=submit]');
1011
- * // link in context
1012
- * I.click('Logout', '#nav');
1013
- * // using strict locator
1014
- * I.click({css: 'nav a.login'});
1015
- * ```
1016
- *
1017
- * @param {CodeceptJS.LocatorOrString} locator clickable link or button located by text, or any element located by CSS|XPath|strict locator.
1018
- * @param {?CodeceptJS.LocatorOrString | null} [context=null] (optional, `null` by default) element to search in CSS|XPath|Strict locator.
1019
- * @returns {void} automatically synchronized promise through #recorder
1020
- *
1021
- *
1022
- * {{ react }}
1023
- */
1024
- async click(locator, context = null) {
1025
- const clickMethod = this.browser.isMobile && !this.browser.isW3C ? 'touchClick' : 'elementClick';
1026
- const locateFn = prepareLocateFn.call(this, context);
1027
-
1028
- const res = await findClickable.call(this, locator, locateFn);
1029
- if (context) {
1030
- assertElementExists(res, locator, 'Clickable element', `was not found inside element ${new Locator(context)}`);
1031
- } else {
1032
- assertElementExists(res, locator, 'Clickable element');
1033
- }
1034
- const elem = usingFirstElement(res);
1035
- highlightActiveElement.call(this, elem);
1036
- return this.browser[clickMethod](getElementId(elem));
1037
- }
1038
-
1039
- /**
1040
- * Perform an emulated click on a link or a button, given by a locator.
1041
- * Unlike normal click instead of sending native event, emulates a click with JavaScript.
1042
- * This works on hidden, animated or inactive elements as well.
1043
- *
1044
- * If a fuzzy locator is given, the page will be searched for a button, link, or image matching the locator string.
1045
- * For buttons, the "value" attribute, "name" attribute, and inner text are searched. For links, the link text is searched.
1046
- * For images, the "alt" attribute and inner text of any parent links are searched.
1047
- *
1048
- * The second parameter is a context (CSS or XPath locator) to narrow the search.
1049
- *
1050
- * ```js
1051
- * // simple link
1052
- * I.forceClick('Logout');
1053
- * // button of form
1054
- * I.forceClick('Submit');
1055
- * // CSS button
1056
- * I.forceClick('#form input[type=submit]');
1057
- * // XPath
1058
- * I.forceClick('//form/*[@type=submit]');
1059
- * // link in context
1060
- * I.forceClick('Logout', '#nav');
1061
- * // using strict locator
1062
- * I.forceClick({css: 'nav a.login'});
1063
- * ```
1064
- *
1065
- * @param {CodeceptJS.LocatorOrString} locator clickable link or button located by text, or any element located by CSS|XPath|strict locator.
1066
- * @param {?CodeceptJS.LocatorOrString} [context=null] (optional, `null` by default) element to search in CSS|XPath|Strict locator.
1067
- * @returns {void} automatically synchronized promise through #recorder
1068
- *
1069
- *
1070
- * {{ react }}
1071
- */
1072
- async forceClick(locator, context = null) {
1073
- const locateFn = prepareLocateFn.call(this, context);
1074
-
1075
- const res = await findClickable.call(this, locator, locateFn);
1076
- if (context) {
1077
- assertElementExists(res, locator, 'Clickable element', `was not found inside element ${new Locator(context)}`);
1078
- } else {
1079
- assertElementExists(res, locator, 'Clickable element');
1080
- }
1081
- const elem = usingFirstElement(res);
1082
- highlightActiveElement.call(this, elem);
1083
-
1084
- return this.executeScript((el) => {
1085
- if (document.activeElement instanceof HTMLElement) {
1086
- document.activeElement.blur();
1087
- }
1088
- const event = document.createEvent('MouseEvent');
1089
- event.initEvent('click', true, true);
1090
- return el.dispatchEvent(event);
1091
- }, elem);
1092
- }
1093
-
1094
- /**
1095
- * Performs a double-click on an element matched by link|button|label|CSS or XPath.
1096
- * Context can be specified as second parameter to narrow search.
1097
- *
1098
- * ```js
1099
- * I.doubleClick('Edit');
1100
- * I.doubleClick('Edit', '.actions');
1101
- * I.doubleClick({css: 'button.accept'});
1102
- * I.doubleClick('.btn.edit');
1103
- * ```
1104
- *
1105
- * @param {CodeceptJS.LocatorOrString} locator clickable link or button located by text, or any element located by CSS|XPath|strict locator.
1106
- * @param {?CodeceptJS.LocatorOrString} [context=null] (optional, `null` by default) element to search in CSS|XPath|Strict locator.
1107
- * @returns {void} automatically synchronized promise through #recorder
1108
- *
1109
- *
1110
- * {{ react }}
1111
- */
1112
- async doubleClick(locator, context = null) {
1113
- const locateFn = prepareLocateFn.call(this, context);
1114
-
1115
- const res = await findClickable.call(this, locator, locateFn);
1116
- if (context) {
1117
- assertElementExists(res, locator, 'Clickable element', `was not found inside element ${new Locator(context)}`);
1118
- } else {
1119
- assertElementExists(res, locator, 'Clickable element');
1120
- }
1121
-
1122
- const elem = usingFirstElement(res);
1123
- highlightActiveElement.call(this, elem);
1124
- return elem.doubleClick();
1125
- }
1126
-
1127
- /**
1128
- * Performs right click on a clickable element matched by semantic locator, CSS or XPath.
1129
- *
1130
- * ```js
1131
- * // right click element with id el
1132
- * I.rightClick('#el');
1133
- * // right click link or button with text "Click me"
1134
- * I.rightClick('Click me');
1135
- * // right click button with text "Click me" inside .context
1136
- * I.rightClick('Click me', '.context');
1137
- * ```
1138
- *
1139
- * @param {CodeceptJS.LocatorOrString} locator clickable element located by CSS|XPath|strict locator.
1140
- * @param {?CodeceptJS.LocatorOrString} [context=null] (optional, `null` by default) element located by CSS|XPath|strict locator.
1141
- * @returns {void} automatically synchronized promise through #recorder
1142
- *
1143
- *
1144
- * {{ react }}
1145
- */
1146
- async rightClick(locator, context) {
1147
- const locateFn = prepareLocateFn.call(this, context);
1148
-
1149
- const res = await findClickable.call(this, locator, locateFn);
1150
- if (context) {
1151
- assertElementExists(res, locator, 'Clickable element', `was not found inside element ${new Locator(context)}`);
1152
- } else {
1153
- assertElementExists(res, locator, 'Clickable element');
1154
- }
1155
-
1156
- const el = usingFirstElement(res);
1157
-
1158
- await el.moveTo();
1159
-
1160
- if (this.browser.isW3C) {
1161
- return el.click({ button: 'right' });
1162
- }
1163
- // JSON Wire version
1164
- await this.browser.buttonDown(2);
1165
- }
1166
-
1167
- /**
1168
- * Emulates right click on an element.
1169
- * Unlike normal click instead of sending native event, emulates a click with JavaScript.
1170
- * This works on hidden, animated or inactive elements as well.
1171
- *
1172
- * If a fuzzy locator is given, the page will be searched for a button, link, or image matching the locator string.
1173
- * For buttons, the "value" attribute, "name" attribute, and inner text are searched. For links, the link text is searched.
1174
- * For images, the "alt" attribute and inner text of any parent links are searched.
1175
- *
1176
- * The second parameter is a context (CSS or XPath locator) to narrow the search.
1177
- *
1178
- * ```js
1179
- * // simple link
1180
- * I.forceRightClick('Menu');
1181
- * ```
1182
- *
1183
- * @param {CodeceptJS.LocatorOrString} locator clickable link or button located by text, or any element located by CSS|XPath|strict locator.
1184
- * @param {?CodeceptJS.LocatorOrString} [context=null] (optional, `null` by default) element to search in CSS|XPath|Strict locator.
1185
- * @returns {void} automatically synchronized promise through #recorder
1186
- *
1187
- *
1188
- * {{ react }}
1189
- */
1190
- async forceRightClick(locator, context = null) {
1191
- const locateFn = prepareLocateFn.call(this, context);
1192
-
1193
- const res = await findClickable.call(this, locator, locateFn);
1194
- if (context) {
1195
- assertElementExists(res, locator, 'Clickable element', `was not found inside element ${new Locator(context)}`);
1196
- } else {
1197
- assertElementExists(res, locator, 'Clickable element');
1198
- }
1199
- const elem = usingFirstElement(res);
1200
-
1201
- return this.executeScript((el) => {
1202
- if (document.activeElement instanceof HTMLElement) {
1203
- document.activeElement.blur();
1204
- }
1205
- const event = document.createEvent('MouseEvent');
1206
- event.initEvent('contextmenu', true, true);
1207
- return el.dispatchEvent(event);
1208
- }, elem);
1209
- }
1210
-
1211
- /**
1212
- * Fills a text field or textarea, after clearing its value, with the given string.
1213
- * Field is located by name, label, CSS, or XPath.
1214
- *
1215
- * ```js
1216
- * // by label
1217
- * I.fillField('Email', 'hello@world.com');
1218
- * // by name
1219
- * I.fillField('password', secret('123456'));
1220
- * // by CSS
1221
- * I.fillField('form#login input[name=username]', 'John');
1222
- * // or by strict locator
1223
- * I.fillField({css: 'form#login input[name=username]'}, 'John');
1224
- * ```
1225
- * @param {CodeceptJS.LocatorOrString} field located by label|name|CSS|XPath|strict locator.
1226
- * @param {CodeceptJS.StringOrSecret} value text value to fill.
1227
- * @returns {void} automatically synchronized promise through #recorder
1228
- *
1229
- * {{ react }}
1230
- * {{ custom }}
1231
- *
1232
- */
1233
- async fillField(field, value) {
1234
- const res = await findFields.call(this, field);
1235
- assertElementExists(res, field, 'Field');
1236
- const elem = usingFirstElement(res);
1237
- highlightActiveElement.call(this, elem);
1238
- await elem.clearValue();
1239
- await elem.setValue(value.toString());
1240
- }
1241
-
1242
- /**
1243
- * Appends text to a input field or textarea.
1244
- * Field is located by name, label, CSS or XPath
1245
- *
1246
- * ```js
1247
- * I.appendField('#myTextField', 'appended');
1248
- * // typing secret
1249
- * I.appendField('password', secret('123456'));
1250
- * ```
1251
- * @param {CodeceptJS.LocatorOrString} field located by label|name|CSS|XPath|strict locator
1252
- * @param {string} value text value to append.
1253
- * @returns {void} automatically synchronized promise through #recorder
1254
- *
1255
- * {{ react }}
1256
- */
1257
- async appendField(field, value) {
1258
- const res = await findFields.call(this, field);
1259
- assertElementExists(res, field, 'Field');
1260
- const elem = usingFirstElement(res);
1261
- highlightActiveElement.call(this, elem);
1262
- if (this.options.automationProtocol) {
1263
- const curentValue = await elem.getValue();
1264
- return elem.setValue(curentValue + value.toString());
1265
- }
1266
- return elem.addValue(value.toString());
1267
- }
1268
-
1269
- /**
1270
- * Clears a `<textarea>` or text `<input>` element's value.
1271
- *
1272
- * ```js
1273
- * I.clearField('Email');
1274
- * I.clearField('user[email]');
1275
- * I.clearField('#email');
1276
- * ```
1277
- * @param {LocatorOrString} editable field located by label|name|CSS|XPath|strict locator.
1278
- * @returns {void} automatically synchronized promise through #recorder.
1279
- *
1280
- *
1281
- */
1282
- async clearField(field) {
1283
- const res = await findFields.call(this, field);
1284
- assertElementExists(res, field, 'Field');
1285
- const elem = usingFirstElement(res);
1286
- highlightActiveElement.call(this, elem);
1287
- if (this.options.automationProtocol) {
1288
- return elem.setValue('');
1289
- }
1290
- return elem.clearValue(getElementId(elem));
1291
- }
1292
-
1293
- /**
1294
- * Selects an option in a drop-down select.
1295
- * Field is searched by label | name | CSS | XPath.
1296
- * Option is selected by visible text or by value.
1297
- *
1298
- * ```js
1299
- * I.selectOption('Choose Plan', 'Monthly'); // select by label
1300
- * I.selectOption('subscription', 'Monthly'); // match option by text
1301
- * I.selectOption('subscription', '0'); // or by value
1302
- * I.selectOption('//form/select[@name=account]','Premium');
1303
- * I.selectOption('form select[name=account]', 'Premium');
1304
- * I.selectOption({css: 'form select[name=account]'}, 'Premium');
1305
- * ```
1306
- *
1307
- * Provide an array for the second argument to select multiple options.
1308
- *
1309
- * ```js
1310
- * I.selectOption('Which OS do you use?', ['Android', 'iOS']);
1311
- * ```
1312
- * @param {LocatorOrString} select field located by label|name|CSS|XPath|strict locator.
1313
- * @param {string|Array<*>} option visible text or value of option.
1314
- * @returns {void} automatically synchronized promise through #recorder
1315
- *
1316
- */
1317
- async selectOption(select, option) {
1318
- const res = await findFields.call(this, select);
1319
- assertElementExists(res, select, 'Selectable field');
1320
- const elem = usingFirstElement(res);
1321
- highlightActiveElement.call(this, elem);
1322
-
1323
- if (!Array.isArray(option)) {
1324
- option = [option];
1325
- }
1326
-
1327
- // select options by visible text
1328
- let els = await forEachAsync(option, async opt => this.browser.findElementsFromElement(getElementId(elem), 'xpath', Locator.select.byVisibleText(xpathLocator.literal(opt))));
1329
-
1330
- const clickOptionFn = async (el) => {
1331
- if (el[0]) el = el[0];
1332
- const elementId = getElementId(el);
1333
- if (elementId) return this.browser.elementClick(elementId);
1334
- };
1335
-
1336
- if (Array.isArray(els) && els.length) {
1337
- return forEachAsync(els, clickOptionFn);
1338
- }
1339
- // select options by value
1340
- els = await forEachAsync(option, async opt => this.browser.findElementsFromElement(getElementId(elem), 'xpath', Locator.select.byValue(xpathLocator.literal(opt))));
1341
- if (els.length === 0) {
1342
- throw new ElementNotFound(select, `Option "${option}" in`, 'was not found neither by a visible text nor by a value');
1343
- }
1344
- return forEachAsync(els, clickOptionFn);
1345
- }
1346
-
1347
- /**
1348
- * Appium: not tested
1349
- *
1350
- * Attaches a file to element located by label, name, CSS or XPath
1351
- * Path to file is relative current codecept directory (where codecept.conf.ts or codecept.conf.js is located).
1352
- * File will be uploaded to remote system (if tests are running remotely).
1353
- *
1354
- * ```js
1355
- * I.attachFile('Avatar', 'data/avatar.jpg');
1356
- * I.attachFile('form input[name=avatar]', 'data/avatar.jpg');
1357
- * ```
1358
- *
1359
- * @param {CodeceptJS.LocatorOrString} locator field located by label|name|CSS|XPath|strict locator.
1360
- * @param {string} pathToFile local file path relative to codecept.conf.ts or codecept.conf.js config file.
1361
- * @returns {void} automatically synchronized promise through #recorder
1362
- *
1363
- */
1364
- async attachFile(locator, pathToFile) {
1365
- let file = path.join(global.codecept_dir, pathToFile);
1366
- if (!fileExists(file)) {
1367
- throw new Error(`File at ${file} can not be found on local system`);
1368
- }
1369
-
1370
- const res = await findFields.call(this, locator);
1371
- this.debug(`Uploading ${file}`);
1372
- assertElementExists(res, locator, 'File field');
1373
- const el = usingFirstElement(res);
1374
-
1375
- // Remote Upload (when running Selenium Server)
1376
- if (this.options.remoteFileUpload && !this.options.automationProtocol) {
1377
- try {
1378
- this.debugSection('File', 'Uploading file to remote server');
1379
- file = await this.browser.uploadFile(file);
1380
- } catch (err) {
1381
- throw new Error(`File can't be transferred to remote server. Set \`remoteFileUpload: false\` in config to upload file locally.\n${err.message}`);
1382
- }
1383
- }
1384
-
1385
- return el.addValue(file);
1386
- }
1387
-
1388
- /**
1389
- * Appium: not tested
1390
- * Selects a checkbox or radio button.
1391
- * Element is located by label or name or CSS or XPath.
1392
- *
1393
- * The second parameter is a context (CSS or XPath locator) to narrow the search.
1394
- *
1395
- * ```js
1396
- * I.checkOption('#agree');
1397
- * I.checkOption('I Agree to Terms and Conditions');
1398
- * I.checkOption('agree', '//form');
1399
- * ```
1400
- * @param {CodeceptJS.LocatorOrString} field checkbox located by label | name | CSS | XPath | strict locator.
1401
- * @param {?CodeceptJS.LocatorOrString} [context=null] (optional, `null` by default) element located by CSS | XPath | strict locator.
1402
- * @returns {void} automatically synchronized promise through #recorder
1403
- *
1404
- */
1405
- async checkOption(field, context = null) {
1406
- const clickMethod = this.browser.isMobile && !this.browser.isW3C ? 'touchClick' : 'elementClick';
1407
- const locateFn = prepareLocateFn.call(this, context);
1408
-
1409
- const res = await findCheckable.call(this, field, locateFn);
1410
-
1411
- assertElementExists(res, field, 'Checkable');
1412
- const elem = usingFirstElement(res);
1413
- const elementId = getElementId(elem);
1414
- highlightActiveElement.call(this, elem);
1415
-
1416
- const isSelected = await this.browser.isElementSelected(elementId);
1417
- if (isSelected) return Promise.resolve(true);
1418
- return this.browser[clickMethod](elementId);
1419
- }
1420
-
1421
- /**
1422
- * Appium: not tested
1423
- * Unselects a checkbox or radio button.
1424
- * Element is located by label or name or CSS or XPath.
1425
- *
1426
- * The second parameter is a context (CSS or XPath locator) to narrow the search.
1427
- *
1428
- * ```js
1429
- * I.uncheckOption('#agree');
1430
- * I.uncheckOption('I Agree to Terms and Conditions');
1431
- * I.uncheckOption('agree', '//form');
1432
- * ```
1433
- * @param {CodeceptJS.LocatorOrString} field checkbox located by label | name | CSS | XPath | strict locator.
1434
- * @param {?CodeceptJS.LocatorOrString} [context=null] (optional, `null` by default) element located by CSS | XPath | strict locator.
1435
- * @returns {void} automatically synchronized promise through #recorder
1436
- *
1437
- */
1438
- async uncheckOption(field, context = null) {
1439
- const clickMethod = this.browser.isMobile && !this.browser.isW3C ? 'touchClick' : 'elementClick';
1440
- const locateFn = prepareLocateFn.call(this, context);
1441
-
1442
- const res = await findCheckable.call(this, field, locateFn);
1443
-
1444
- assertElementExists(res, field, 'Checkable');
1445
- const elem = usingFirstElement(res);
1446
- const elementId = getElementId(elem);
1447
- highlightActiveElement.call(this, elem);
1448
-
1449
- const isSelected = await this.browser.isElementSelected(elementId);
1450
- if (!isSelected) return Promise.resolve(true);
1451
- return this.browser[clickMethod](elementId);
1452
- }
1453
-
1454
- /**
1455
- * Retrieves all texts from an element located by CSS or XPath and returns it to test.
1456
- * Resumes test execution, so **should be used inside async with `await`** operator.
1457
- *
1458
- * ```js
1459
- * let pins = await I.grabTextFromAll('#pin li');
1460
- * ```
1461
- *
1462
- * @param {CodeceptJS.LocatorOrString} locator element located by CSS|XPath|strict locator.
1463
- * @returns {Promise<string[]>} attribute value
1464
- *
1465
- *
1466
- */
1467
- async grabTextFromAll(locator) {
1468
- const res = await this._locate(locator, true);
1469
- const val = await forEachAsync(res, el => this.browser.getElementText(getElementId(el)));
1470
- this.debugSection('GrabText', String(val));
1471
- return val;
1472
- }
1473
-
1474
- /**
1475
- * Retrieves a text from an element located by CSS or XPath and returns it to test.
1476
- * Resumes test execution, so **should be used inside async with `await`** operator.
1477
- *
1478
- * ```js
1479
- * let pin = await I.grabTextFrom('#pin');
1480
- * ```
1481
- * If multiple elements found returns first element.
1482
- *
1483
- * @param {CodeceptJS.LocatorOrString} locator element located by CSS|XPath|strict locator.
1484
- * @returns {Promise<string>} attribute value
1485
- *
1486
- *
1487
- */
1488
- async grabTextFrom(locator) {
1489
- const texts = await this.grabTextFromAll(locator);
1490
- assertElementExists(texts, locator);
1491
- if (texts.length > 1) {
1492
- this.debugSection('GrabText', `Using first element out of ${texts.length}`);
1493
- }
1494
-
1495
- return texts[0];
1496
- }
1497
-
1498
- /**
1499
- * Retrieves all the innerHTML from elements located by CSS or XPath and returns it to test.
1500
- * Resumes test execution, so **should be used inside async function with `await`** operator.
1501
- *
1502
- * ```js
1503
- * let postHTMLs = await I.grabHTMLFromAll('.post');
1504
- * ```
1505
- *
1506
- * @param {CodeceptJS.LocatorOrString} element located by CSS|XPath|strict locator.
1507
- * @returns {Promise<string[]>} HTML code for an element
1508
- *
1509
- *
1510
- */
1511
- async grabHTMLFromAll(locator) {
1512
- const elems = await this._locate(locator, true);
1513
- const html = await forEachAsync(elems, elem => elem.getHTML(false));
1514
- this.debugSection('GrabHTML', String(html));
1515
- return html;
1516
- }
1517
-
1518
- /**
1519
- * Retrieves the innerHTML from an element located by CSS or XPath and returns it to test.
1520
- * Resumes test execution, so **should be used inside async function with `await`** operator.
1521
- * If more than one element is found - HTML of first element is returned.
1522
- *
1523
- * ```js
1524
- * let postHTML = await I.grabHTMLFrom('#post');
1525
- * ```
1526
- *
1527
- * @param {CodeceptJS.LocatorOrString} element located by CSS|XPath|strict locator.
1528
- * @returns {Promise<string>} HTML code for an element
1529
- *
1530
- *
1531
- */
1532
- async grabHTMLFrom(locator) {
1533
- const html = await this.grabHTMLFromAll(locator);
1534
- assertElementExists(html, locator);
1535
- if (html.length > 1) {
1536
- this.debugSection('GrabHTML', `Using first element out of ${html.length}`);
1537
- }
1538
-
1539
- return html[0];
1540
- }
1541
-
1542
- /**
1543
- * Retrieves an array of value from a form located by CSS or XPath and returns it to test.
1544
- * Resumes test execution, so **should be used inside async function with `await`** operator.
1545
- *
1546
- * ```js
1547
- * let inputs = await I.grabValueFromAll('//form/input');
1548
- * ```
1549
- * @param {CodeceptJS.LocatorOrString} locator field located by label|name|CSS|XPath|strict locator.
1550
- * @returns {Promise<string[]>} attribute value
1551
- *
1552
- *
1553
- */
1554
- async grabValueFromAll(locator) {
1555
- const res = await this._locate(locator, true);
1556
- const val = await forEachAsync(res, el => el.getValue());
1557
- this.debugSection('GrabValue', String(val));
1558
-
1559
- return val;
1560
- }
1561
-
1562
- /**
1563
- * Retrieves a value from a form element located by CSS or XPath and returns it to test.
1564
- * Resumes test execution, so **should be used inside async function with `await`** operator.
1565
- * If more than one element is found - value of first element is returned.
1566
- *
1567
- * ```js
1568
- * let email = await I.grabValueFrom('input[name=email]');
1569
- * ```
1570
- * @param {CodeceptJS.LocatorOrString} locator field located by label|name|CSS|XPath|strict locator.
1571
- * @returns {Promise<string>} attribute value
1572
- *
1573
- *
1574
- */
1575
- async grabValueFrom(locator) {
1576
- const values = await this.grabValueFromAll(locator);
1577
- assertElementExists(values, locator);
1578
- if (values.length > 1) {
1579
- this.debugSection('GrabValue', `Using first element out of ${values.length}`);
1580
- }
1581
-
1582
- return values[0];
1583
- }
1584
-
1585
- /**
1586
- * Grab array of CSS properties for given locator
1587
- * Resumes test execution, so **should be used inside an async function with `await`** operator.
1588
- *
1589
- * ```js
1590
- * const values = await I.grabCssPropertyFromAll('h3', 'font-weight');
1591
- * ```
1592
- *
1593
- * @param {CodeceptJS.LocatorOrString} locator element located by CSS|XPath|strict locator.
1594
- * @param {string} cssProperty CSS property name.
1595
- * @returns {Promise<string[]>} CSS value
1596
- *
1597
- */
1598
- async grabCssPropertyFromAll(locator, cssProperty) {
1599
- const res = await this._locate(locator, true);
1600
- const val = await forEachAsync(res, async el => this.browser.getElementCSSValue(getElementId(el), cssProperty));
1601
- this.debugSection('Grab', String(val));
1602
- return val;
1603
- }
1604
-
1605
- /**
1606
- * Grab CSS property for given locator
1607
- * Resumes test execution, so **should be used inside an async function with `await`** operator.
1608
- * If more than one element is found - value of first element is returned.
1609
- *
1610
- * ```js
1611
- * const value = await I.grabCssPropertyFrom('h3', 'font-weight');
1612
- * ```
1613
- *
1614
- * @param {CodeceptJS.LocatorOrString} locator element located by CSS|XPath|strict locator.
1615
- * @param {string} cssProperty CSS property name.
1616
- * @returns {Promise<string>} CSS value
1617
- *
1618
- */
1619
- async grabCssPropertyFrom(locator, cssProperty) {
1620
- const cssValues = await this.grabCssPropertyFromAll(locator, cssProperty);
1621
- assertElementExists(cssValues, locator);
1622
-
1623
- if (cssValues.length > 1) {
1624
- this.debugSection('GrabCSS', `Using first element out of ${cssValues.length}`);
1625
- }
1626
-
1627
- return cssValues[0];
1628
- }
1629
-
1630
- /**
1631
- * Retrieves an array of attributes from elements located by CSS or XPath and returns it to test.
1632
- * Resumes test execution, so **should be used inside async with `await`** operator.
1633
- *
1634
- * ```js
1635
- * let hints = await I.grabAttributeFromAll('.tooltip', 'title');
1636
- * ```
1637
- * @param {CodeceptJS.LocatorOrString} locator element located by CSS|XPath|strict locator.
1638
- * @param {string} attr attribute name.
1639
- * @returns {Promise<string[]>} attribute value
1640
- *
1641
- */
1642
- async grabAttributeFromAll(locator, attr) {
1643
- const res = await this._locate(locator, true);
1644
- const val = await forEachAsync(res, async el => el.getAttribute(attr));
1645
- this.debugSection('GrabAttribute', String(val));
1646
- return val;
1647
- }
1648
-
1649
- /**
1650
- * Retrieves an attribute from an element located by CSS or XPath and returns it to test.
1651
- * Resumes test execution, so **should be used inside async with `await`** operator.
1652
- * If more than one element is found - attribute of first element is returned.
1653
- *
1654
- * ```js
1655
- * let hint = await I.grabAttributeFrom('#tooltip', 'title');
1656
- * ```
1657
- * @param {CodeceptJS.LocatorOrString} locator element located by CSS|XPath|strict locator.
1658
- * @param {string} attr attribute name.
1659
- * @returns {Promise<string>} attribute value
1660
- *
1661
- */
1662
- async grabAttributeFrom(locator, attr) {
1663
- const attrs = await this.grabAttributeFromAll(locator, attr);
1664
- assertElementExists(attrs, locator);
1665
- if (attrs.length > 1) {
1666
- this.debugSection('GrabAttribute', `Using first element out of ${attrs.length}`);
1667
- }
1668
- return attrs[0];
1669
- }
1670
-
1671
- /**
1672
- * Checks that title contains text.
1673
- *
1674
- * ```js
1675
- * I.seeInTitle('Home Page');
1676
- * ```
1677
- *
1678
- * @param {string} text text value to check.
1679
- * @returns {void} automatically synchronized promise through #recorder
1680
- *
1681
- */
1682
- async seeInTitle(text) {
1683
- const title = await this.browser.getTitle();
1684
- return stringIncludes('web page title').assert(text, title);
1685
- }
1686
-
1687
- /**
1688
- * Checks that title is equal to provided one.
1689
- *
1690
- * ```js
1691
- * I.seeTitleEquals('Test title.');
1692
- * ```
1693
- *
1694
- * @param {string} text value to check.
1695
- * @returns {void} automatically synchronized promise through #recorder
1696
- *
1697
- */
1698
- async seeTitleEquals(text) {
1699
- const title = await this.browser.getTitle();
1700
- return assert.equal(title, text, `expected web page title to be ${text}, but found ${title}`);
1701
- }
1702
-
1703
- /**
1704
- * Checks that title does not contain text.
1705
- *
1706
- * ```js
1707
- * I.dontSeeInTitle('Error');
1708
- * ```
1709
- *
1710
- * @param {string} text value to check.
1711
- * @returns {void} automatically synchronized promise through #recorder
1712
- *
1713
- */
1714
- async dontSeeInTitle(text) {
1715
- const title = await this.browser.getTitle();
1716
- return stringIncludes('web page title').negate(text, title);
1717
- }
1718
-
1719
- /**
1720
- * Retrieves a page title and returns it to test.
1721
- * Resumes test execution, so **should be used inside async with `await`** operator.
1722
- *
1723
- * ```js
1724
- * let title = await I.grabTitle();
1725
- * ```
1726
- *
1727
- * @returns {Promise<string>} title
1728
- */
1729
- async grabTitle() {
1730
- const title = await this.browser.getTitle();
1731
- this.debugSection('Title', title);
1732
- return title;
1733
- }
1734
-
1735
- /**
1736
- * Checks that a page contains a visible text.
1737
- * Use context parameter to narrow down the search.
1738
- *
1739
- * ```js
1740
- * I.see('Welcome'); // text welcome on a page
1741
- * I.see('Welcome', '.content'); // text inside .content div
1742
- * I.see('Register', {css: 'form.register'}); // use strict locator
1743
- * ```
1744
- * @param {string} text expected on page.
1745
- * @param {?CodeceptJS.LocatorOrString} [context=null] (optional, `null` by default) element located by CSS|Xpath|strict locator in which to search for text.
1746
- * @returns {void} automatically synchronized promise through #recorder
1747
- *
1748
- *
1749
- * {{ react }}
1750
- */
1751
- async see(text, context = null) {
1752
- return proceedSee.call(this, 'assert', text, context);
1753
- }
1754
-
1755
- /**
1756
- * Checks that text is equal to provided one.
1757
- *
1758
- * ```js
1759
- * I.seeTextEquals('text', 'h1');
1760
- * ```
1761
- *
1762
- * @param {string} text element value to check.
1763
- * @param {CodeceptJS.LocatorOrString?} [context=null] element located by CSS|XPath|strict locator.
1764
- * @returns {void} automatically synchronized promise through #recorder
1765
- *
1766
- */
1767
- async seeTextEquals(text, context = null) {
1768
- return proceedSee.call(this, 'assert', text, context, true);
1769
- }
1770
-
1771
- /**
1772
- * Opposite to `see`. Checks that a text is not present on a page.
1773
- * Use context parameter to narrow down the search.
1774
- *
1775
- * ```js
1776
- * I.dontSee('Login'); // assume we are already logged in.
1777
- * I.dontSee('Login', '.nav'); // no login inside .nav element
1778
- * ```
1779
- *
1780
- * @param {string} text which is not present.
1781
- * @param {CodeceptJS.LocatorOrString} [context] (optional) element located by CSS|XPath|strict locator in which to perfrom search.
1782
- * @returns {void} automatically synchronized promise through #recorder
1783
- *
1784
- *
1785
- * {{ react }}
1786
- */
1787
- async dontSee(text, context = null) {
1788
- return proceedSee.call(this, 'negate', text, context);
1789
- }
1790
-
1791
- /**
1792
- * Checks that the given input field or textarea equals to given value.
1793
- * For fuzzy locators, fields are matched by label text, the "name" attribute, CSS, and XPath.
1794
- *
1795
- * ```js
1796
- * I.seeInField('Username', 'davert');
1797
- * I.seeInField({css: 'form textarea'},'Type your comment here');
1798
- * I.seeInField('form input[type=hidden]','hidden_value');
1799
- * I.seeInField('#searchform input','Search');
1800
- * ```
1801
- * @param {CodeceptJS.LocatorOrString} field located by label|name|CSS|XPath|strict locator.
1802
- * @param {CodeceptJS.StringOrSecret} value value to check.
1803
- * @returns {void} automatically synchronized promise through #recorder
1804
- *
1805
- *
1806
- */
1807
- async seeInField(field, value) {
1808
- const _value = (typeof value === 'boolean') ? value : value.toString();
1809
- return proceedSeeField.call(this, 'assert', field, _value);
1810
- }
1811
-
1812
- /**
1813
- * Checks that value of input field or textarea doesn't equal to given value
1814
- * Opposite to `seeInField`.
1815
- *
1816
- * ```js
1817
- * I.dontSeeInField('email', 'user@user.com'); // field by name
1818
- * I.dontSeeInField({ css: 'form input.email' }, 'user@user.com'); // field by CSS
1819
- * ```
1820
- *
1821
- * @param {CodeceptJS.LocatorOrString} field located by label|name|CSS|XPath|strict locator.
1822
- * @param {CodeceptJS.StringOrSecret} value value to check.
1823
- * @returns {void} automatically synchronized promise through #recorder
1824
- *
1825
- *
1826
- */
1827
- async dontSeeInField(field, value) {
1828
- const _value = (typeof value === 'boolean') ? value : value.toString();
1829
- return proceedSeeField.call(this, 'negate', field, _value);
1830
- }
1831
-
1832
- /**
1833
- * Appium: not tested
1834
- * Verifies that the specified checkbox is checked.
1835
- *
1836
- * ```js
1837
- * I.seeCheckboxIsChecked('Agree');
1838
- * I.seeCheckboxIsChecked('#agree'); // I suppose user agreed to terms
1839
- * I.seeCheckboxIsChecked({css: '#signup_form input[type=checkbox]'});
1840
- * ```
1841
- *
1842
- * @param {CodeceptJS.LocatorOrString} field located by label|name|CSS|XPath|strict locator.
1843
- * @returns {void} automatically synchronized promise through #recorder
1844
- *
1845
- */
1846
- async seeCheckboxIsChecked(field) {
1847
- return proceedSeeCheckbox.call(this, 'assert', field);
1848
- }
1849
-
1850
- /**
1851
- * Appium: not tested
1852
- * Verifies that the specified checkbox is not checked.
1853
- *
1854
- * ```js
1855
- * I.dontSeeCheckboxIsChecked('#agree'); // located by ID
1856
- * I.dontSeeCheckboxIsChecked('I agree to terms'); // located by label
1857
- * I.dontSeeCheckboxIsChecked('agree'); // located by name
1858
- * ```
1859
- *
1860
- * @param {CodeceptJS.LocatorOrString} field located by label|name|CSS|XPath|strict locator.
1861
- * @returns {void} automatically synchronized promise through #recorder
1862
- *
1863
- */
1864
- async dontSeeCheckboxIsChecked(field) {
1865
- return proceedSeeCheckbox.call(this, 'negate', field);
1866
- }
1867
-
1868
- /**
1869
- * Checks that a given Element is visible
1870
- * Element is located by CSS or XPath.
1871
- *
1872
- * ```js
1873
- * I.seeElement('#modal');
1874
- * ```
1875
- * @param {CodeceptJS.LocatorOrString} locator located by CSS|XPath|strict locator.
1876
- * @returns {void} automatically synchronized promise through #recorder
1877
- *
1878
- * {{ react }}
1879
- *
1880
- */
1881
- async seeElement(locator) {
1882
- const res = await this._locate(locator, true);
1883
- assertElementExists(res, locator);
1884
- const selected = await forEachAsync(res, async el => el.isDisplayed());
1885
- return truth(`elements of ${(new Locator(locator))}`, 'to be seen').assert(selected);
1886
- }
1887
-
1888
- /**
1889
- * Opposite to `seeElement`. Checks that element is not visible (or in DOM)
1890
- *
1891
- * ```js
1892
- * I.dontSeeElement('.modal'); // modal is not shown
1893
- * ```
1894
- *
1895
- * @param {CodeceptJS.LocatorOrString} locator located by CSS|XPath|Strict locator.
1896
- * @returns {void} automatically synchronized promise through #recorder
1897
- *
1898
- * {{ react }}
1899
- */
1900
- async dontSeeElement(locator) {
1901
- const res = await this._locate(locator, false);
1902
- if (!res || res.length === 0) {
1903
- return truth(`elements of ${(new Locator(locator))}`, 'to be seen').negate(false);
1904
- }
1905
- const selected = await forEachAsync(res, async el => el.isDisplayed());
1906
- return truth(`elements of ${(new Locator(locator))}`, 'to be seen').negate(selected);
1907
- }
1908
-
1909
- /**
1910
- * Checks that a given Element is present in the DOM
1911
- * Element is located by CSS or XPath.
1912
- *
1913
- * ```js
1914
- * I.seeElementInDOM('#modal');
1915
- * ```
1916
- * @param {CodeceptJS.LocatorOrString} locator element located by CSS|XPath|strict locator.
1917
- * @returns {void} automatically synchronized promise through #recorder
1918
- *
1919
- *
1920
- */
1921
- async seeElementInDOM(locator) {
1922
- const res = await this._res(locator);
1923
- return empty('elements').negate(res);
1924
- }
1925
-
1926
- /**
1927
- * Opposite to `seeElementInDOM`. Checks that element is not on page.
1928
- *
1929
- * ```js
1930
- * I.dontSeeElementInDOM('.nav'); // checks that element is not on page visible or not
1931
- * ```
1932
- *
1933
- * @param {CodeceptJS.LocatorOrString} locator located by CSS|XPath|Strict locator.
1934
- * @returns {void} automatically synchronized promise through #recorder
1935
- *
1936
- *
1937
- */
1938
- async dontSeeElementInDOM(locator) {
1939
- const res = await this._res(locator);
1940
- return empty('elements').assert(res);
1941
- }
1942
-
1943
- /**
1944
- * Checks that the current page contains the given string in its raw source code.
1945
- *
1946
- * ```js
1947
- * I.seeInSource('<h1>Green eggs &amp; ham</h1>');
1948
- * ```
1949
- * @param {string} text value to check.
1950
- * @returns {void} automatically synchronized promise through #recorder
1951
- *
1952
- *
1953
- */
1954
- async seeInSource(text) {
1955
- const source = await this.browser.getPageSource();
1956
- return stringIncludes('HTML source of a page').assert(text, source);
1957
- }
1958
-
1959
- /**
1960
- * Retrieves page source and returns it to test.
1961
- * Resumes test execution, so **should be used inside async function with `await`** operator.
1962
- *
1963
- * ```js
1964
- * let pageSource = await I.grabSource();
1965
- * ```
1966
- *
1967
- * @returns {Promise<string>} source code
1968
- *
1969
- */
1970
- async grabSource() {
1971
- return this.browser.getPageSource();
1972
- }
1973
-
1974
- /**
1975
- * Get JS log from browser. Log buffer is reset after each request.
1976
- * Resumes test execution, so **should be used inside an async function with `await`** operator.
1977
- *
1978
- * ```js
1979
- * let logs = await I.grabBrowserLogs();
1980
- * console.log(JSON.stringify(logs))
1981
- * ```
1982
- *
1983
- * @returns {Promise<object[]>|undefined} all browser logs
1984
- *
1985
- */
1986
- async grabBrowserLogs() {
1987
- if (this.browser.isW3C) {
1988
- this.debug('Logs not available in W3C specification');
1989
- return;
1990
- }
1991
- return this.browser.getLogs('browser');
1992
- }
1993
-
1994
- /**
1995
- * Get current URL from browser.
1996
- * Resumes test execution, so should be used inside an async function.
1997
- *
1998
- * ```js
1999
- * let url = await I.grabCurrentUrl();
2000
- * console.log(`Current URL is [${url}]`);
2001
- * ```
2002
- *
2003
- * @returns {Promise<string>} current URL
2004
- */
2005
- async grabCurrentUrl() {
2006
- const res = await this.browser.getUrl();
2007
- this.debugSection('Url', res);
2008
- return res;
2009
- }
2010
-
2011
- /**
2012
- * Checks that the current page does not contains the given string in its raw source code.
2013
- *
2014
- * ```js
2015
- * I.dontSeeInSource('<!--'); // no comments in source
2016
- * ```
2017
- *
2018
- * @param {string} value to check.
2019
- * @returns {void} automatically synchronized promise through #recorder
2020
- *
2021
- */
2022
- async dontSeeInSource(text) {
2023
- const source = await this.browser.getPageSource();
2024
- return stringIncludes('HTML source of a page').negate(text, source);
2025
- }
2026
-
2027
- /**
2028
- * Asserts that an element appears a given number of times in the DOM.
2029
- * Element is located by label or name or CSS or XPath.
2030
- *
2031
- *
2032
- * ```js
2033
- * I.seeNumberOfElements('#submitBtn', 1);
2034
- * ```
2035
- *
2036
- * @param {CodeceptJS.LocatorOrString} locator element located by CSS|XPath|strict locator.
2037
- * @param {number} num number of elements.
2038
- * @returns {void} automatically synchronized promise through #recorder
2039
- *
2040
- * {{ react }}
2041
- */
2042
- async seeNumberOfElements(locator, num) {
2043
- const res = await this._locate(locator);
2044
- return assert.equal(res.length, num, `expected number of elements (${(new Locator(locator))}) is ${num}, but found ${res.length}`);
2045
- }
2046
-
2047
- /**
2048
- * Asserts that an element is visible a given number of times.
2049
- * Element is located by CSS or XPath.
2050
- *
2051
- * ```js
2052
- * I.seeNumberOfVisibleElements('.buttons', 3);
2053
- * ```
2054
- *
2055
- * @param {CodeceptJS.LocatorOrString} locator element located by CSS|XPath|strict locator.
2056
- * @param {number} num number of elements.
2057
- * @returns {void} automatically synchronized promise through #recorder
2058
- *
2059
- * {{ react }}
2060
- */
2061
- async seeNumberOfVisibleElements(locator, num) {
2062
- const res = await this.grabNumberOfVisibleElements(locator);
2063
- return assert.equal(res, num, `expected number of visible elements (${(new Locator(locator))}) is ${num}, but found ${res}`);
2064
- }
2065
-
2066
- /**
2067
- * Checks that all elements with given locator have given CSS properties.
2068
- *
2069
- * ```js
2070
- * I.seeCssPropertiesOnElements('h3', { 'font-weight': "bold"});
2071
- * ```
2072
- *
2073
- * @param {CodeceptJS.LocatorOrString} locator located by CSS|XPath|strict locator.
2074
- * @param {object} cssProperties object with CSS properties and their values to check.
2075
- * @returns {void} automatically synchronized promise through #recorder
2076
- *
2077
- */
2078
- async seeCssPropertiesOnElements(locator, cssProperties) {
2079
- const res = await this._locate(locator);
2080
- assertElementExists(res, locator);
2081
-
2082
- const cssPropertiesCamelCase = convertCssPropertiesToCamelCase(cssProperties);
2083
- const elemAmount = res.length;
2084
- let props = [];
2085
-
2086
- for (const element of res) {
2087
- for (const prop of Object.keys(cssProperties)) {
2088
- const cssProp = await this.grabCssPropertyFrom(locator, prop);
2089
- if (isColorProperty(prop)) {
2090
- props.push(convertColorToRGBA(cssProp));
2091
- } else {
2092
- props.push(cssProp);
2093
- }
2094
- }
2095
- }
2096
-
2097
- const values = Object.keys(cssPropertiesCamelCase).map(key => cssPropertiesCamelCase[key]);
2098
- if (!Array.isArray(props)) props = [props];
2099
- let chunked = chunkArray(props, values.length);
2100
- chunked = chunked.filter((val) => {
2101
- for (let i = 0; i < val.length; ++i) {
2102
- // eslint-disable-next-line eqeqeq
2103
- if (val[i] != values[i]) return false;
2104
- }
2105
- return true;
2106
- });
2107
- return equals(`all elements (${(new Locator(locator))}) to have CSS property ${JSON.stringify(cssProperties)}`).assert(chunked.length, elemAmount);
2108
- }
2109
-
2110
- /**
2111
- * Checks that all elements with given locator have given attributes.
2112
- *
2113
- * ```js
2114
- * I.seeAttributesOnElements('//form', { method: "post"});
2115
- * ```
2116
- *
2117
- * @param {CodeceptJS.LocatorOrString} locator located by CSS|XPath|strict locator.
2118
- * @param {object} attributes attributes and their values to check.
2119
- * @returns {void} automatically synchronized promise through #recorder
2120
- *
2121
- */
2122
- async seeAttributesOnElements(locator, attributes) {
2123
- const res = await this._locate(locator);
2124
- assertElementExists(res, locator);
2125
- const elemAmount = res.length;
2126
-
2127
- let attrs = await forEachAsync(res, async (el) => {
2128
- return forEachAsync(Object.keys(attributes), async attr => el.getAttribute(attr));
2129
- });
2130
-
2131
- const values = Object.keys(attributes).map(key => attributes[key]);
2132
- if (!Array.isArray(attrs)) attrs = [attrs];
2133
- let chunked = chunkArray(attrs, values.length);
2134
- chunked = chunked.filter((val) => {
2135
- for (let i = 0; i < val.length; ++i) {
2136
- const _actual = Number.isNaN(val[i]) || (typeof values[i]) === 'string' ? val[i] : Number.parseInt(val[i], 10);
2137
- const _expected = Number.isNaN(values[i]) || (typeof values[i]) === 'string' ? values[i] : Number.parseInt(values[i], 10);
2138
- if (_actual !== _expected) return false;
2139
- }
2140
- return true;
2141
- });
2142
- return assert.ok(
2143
- chunked.length === elemAmount,
2144
- `expected all elements (${(new Locator(locator))}) to have attributes ${JSON.stringify(attributes)}`,
2145
- );
2146
- }
2147
-
2148
- /**
2149
- * Grab number of visible elements by locator.
2150
- * Resumes test execution, so **should be used inside async function with `await`** operator.
2151
- *
2152
- * ```js
2153
- * let numOfElements = await I.grabNumberOfVisibleElements('p');
2154
- * ```
2155
- *
2156
- * @param {CodeceptJS.LocatorOrString} locator located by CSS|XPath|strict locator.
2157
- * @returns {Promise<number>} number of visible elements
2158
- */
2159
- async grabNumberOfVisibleElements(locator) {
2160
- const res = await this._locate(locator);
2161
-
2162
- let selected = await forEachAsync(res, async el => el.isDisplayed());
2163
- if (!Array.isArray(selected)) selected = [selected];
2164
- selected = selected.filter(val => val === true);
2165
- return selected.length;
2166
- }
2167
-
2168
- /**
2169
- * Checks that current url contains a provided fragment.
2170
- *
2171
- * ```js
2172
- * I.seeInCurrentUrl('/register'); // we are on registration page
2173
- * ```
2174
- *
2175
- * @param {string} url a fragment to check
2176
- * @returns {void} automatically synchronized promise through #recorder
2177
- *
2178
- *
2179
- */
2180
- async seeInCurrentUrl(url) {
2181
- const res = await this.browser.getUrl();
2182
- return stringIncludes('url').assert(url, decodeUrl(res));
2183
- }
2184
-
2185
- /**
2186
- * Checks that current url does not contain a provided fragment.
2187
- *
2188
- * @param {string} url value to check.
2189
- * @returns {void} automatically synchronized promise through #recorder
2190
- *
2191
- *
2192
- */
2193
- async dontSeeInCurrentUrl(url) {
2194
- const res = await this.browser.getUrl();
2195
- return stringIncludes('url').negate(url, decodeUrl(res));
2196
- }
2197
-
2198
- /**
2199
- * Checks that current url is equal to provided one.
2200
- * If a relative url provided, a configured url will be prepended to it.
2201
- * So both examples will work:
2202
- *
2203
- * ```js
2204
- * I.seeCurrentUrlEquals('/register');
2205
- * I.seeCurrentUrlEquals('http://my.site.com/register');
2206
- * ```
2207
- *
2208
- * @param {string} url value to check.
2209
- * @returns {void} automatically synchronized promise through #recorder
2210
- *
2211
- *
2212
- */
2213
- async seeCurrentUrlEquals(url) {
2214
- const res = await this.browser.getUrl();
2215
- return urlEquals(this.options.url).assert(url, decodeUrl(res));
2216
- }
2217
-
2218
- /**
2219
- * Checks that current url is not equal to provided one.
2220
- * If a relative url provided, a configured url will be prepended to it.
2221
- *
2222
- * ```js
2223
- * I.dontSeeCurrentUrlEquals('/login'); // relative url are ok
2224
- * I.dontSeeCurrentUrlEquals('http://mysite.com/login'); // absolute urls are also ok
2225
- * ```
2226
- *
2227
- * @param {string} url value to check.
2228
- * @returns {void} automatically synchronized promise through #recorder
2229
- *
2230
- *
2231
- */
2232
- async dontSeeCurrentUrlEquals(url) {
2233
- const res = await this.browser.getUrl();
2234
- return urlEquals(this.options.url).negate(url, decodeUrl(res));
2235
- }
2236
-
2237
- /**
2238
- * Wraps [execute](http://webdriver.io/api/protocol/execute.html) command.
2239
- *
2240
- * Executes sync script on a page.
2241
- * Pass arguments to function as additional parameters.
2242
- * Will return execution result to a test.
2243
- * In this case you should use async function and await to receive results.
2244
- *
2245
- * Example with jQuery DatePicker:
2246
- *
2247
- * ```js
2248
- * // change date of jQuery DatePicker
2249
- * I.executeScript(function() {
2250
- * // now we are inside browser context
2251
- * $('date').datetimepicker('setDate', new Date());
2252
- * });
2253
- * ```
2254
- * Can return values. Don't forget to use `await` to get them.
2255
- *
2256
- * ```js
2257
- * let date = await I.executeScript(function(el) {
2258
- * // only basic types can be returned
2259
- * return $(el).datetimepicker('getDate').toString();
2260
- * }, '#date'); // passing jquery selector
2261
- * ```
2262
- *
2263
- * @param {string|function} fn function to be executed in browser context.
2264
- * @param {...any} args to be passed to function.
2265
- * @returns {Promise<any>} script return value
2266
- *
2267
- */
2268
- executeScript(...args) {
2269
- return this.browser.execute.apply(this.browser, args);
2270
- }
2271
-
2272
- /**
2273
- * Executes async script on page.
2274
- * Provided function should execute a passed callback (as first argument) to signal it is finished.
2275
- *
2276
- * Example: In Vue.js to make components completely rendered we are waiting for [nextTick](https://vuejs.org/v2/api/#Vue-nextTick).
2277
- *
2278
- * ```js
2279
- * I.executeAsyncScript(function(done) {
2280
- * Vue.nextTick(done); // waiting for next tick
2281
- * });
2282
- * ```
2283
- *
2284
- * By passing value to `done()` function you can return values.
2285
- * Additional arguments can be passed as well, while `done` function is always last parameter in arguments list.
2286
- *
2287
- * ```js
2288
- * let val = await I.executeAsyncScript(function(url, done) {
2289
- * // in browser context
2290
- * $.ajax(url, { success: (data) => done(data); }
2291
- * }, 'http://ajax.callback.url/');
2292
- * ```
2293
- *
2294
- * @param {string|function} fn function to be executed in browser context.
2295
- * @param {...any} args to be passed to function.
2296
- * @returns {Promise<any>} script return value
2297
- *
2298
- *
2299
- */
2300
- executeAsyncScript(...args) {
2301
- return this.browser.executeAsync.apply(this.browser, args);
2302
- }
2303
-
2304
- /**
2305
- * Scroll element into viewport.
2306
- *
2307
- * ```js
2308
- * I.scrollIntoView('#submit');
2309
- * I.scrollIntoView('#submit', true);
2310
- * I.scrollIntoView('#submit', { behavior: "smooth", block: "center", inline: "center" });
2311
- * ```
2312
- *
2313
- * @param {LocatorOrString} locator located by CSS|XPath|strict locator.
2314
- * @param {ScrollIntoViewOptions|boolean} scrollIntoViewOptions either alignToTop=true|false or scrollIntoViewOptions. See https://developer.mozilla.org/en-US/docs/Web/API/Element/scrollIntoView.
2315
- * @returns {void} automatically synchronized promise through #recorder
2316
- *
2317
- *
2318
- */
2319
- async scrollIntoView(locator, scrollIntoViewOptions) {
2320
- const res = await this._locate(withStrictLocator(locator), true);
2321
- assertElementExists(res, locator);
2322
- const elem = usingFirstElement(res);
2323
- return elem.scrollIntoView(scrollIntoViewOptions);
2324
- }
2325
-
2326
- /**
2327
- * Scrolls to element matched by locator.
2328
- * Extra shift can be set with offsetX and offsetY options.
2329
- *
2330
- * ```js
2331
- * I.scrollTo('footer');
2332
- * I.scrollTo('#submit', 5, 5);
2333
- * ```
2334
- *
2335
- * @param {CodeceptJS.LocatorOrString} locator located by CSS|XPath|strict locator.
2336
- * @param {number} [offsetX=0] (optional, `0` by default) X-axis offset.
2337
- * @param {number} [offsetY=0] (optional, `0` by default) Y-axis offset.
2338
- * @returns {void} automatically synchronized promise through #recorder
2339
- *
2340
- *
2341
- */
2342
- async scrollTo(locator, offsetX = 0, offsetY = 0) {
2343
- if (typeof locator === 'number' && typeof offsetX === 'number') {
2344
- offsetY = offsetX;
2345
- offsetX = locator;
2346
- locator = null;
2347
- }
2348
-
2349
- if (locator) {
2350
- const res = await this._locate(withStrictLocator(locator), true);
2351
- assertElementExists(res, locator);
2352
- const elem = usingFirstElement(res);
2353
- const elementId = getElementId(elem);
2354
- if (this.browser.isMobile && !this.browser.isW3C) return this.browser.touchScroll(offsetX, offsetY, elementId);
2355
- const location = await elem.getLocation();
2356
- assertElementExists(location, locator, 'Failed to receive', 'location');
2357
- /* eslint-disable prefer-arrow-callback */
2358
- return this.browser.execute(function (x, y) { return window.scrollTo(x, y); }, location.x + offsetX, location.y + offsetY);
2359
- /* eslint-enable */
2360
- }
2361
-
2362
- if (this.browser.isMobile && !this.browser.isW3C) return this.browser.touchScroll(locator, offsetX, offsetY);
2363
-
2364
- /* eslint-disable prefer-arrow-callback, comma-dangle */
2365
- return this.browser.execute(function (x, y) { return window.scrollTo(x, y); }, offsetX, offsetY);
2366
- /* eslint-enable */
2367
- }
2368
-
2369
- /**
2370
- * Moves cursor to element matched by locator.
2371
- * Extra shift can be set with offsetX and offsetY options.
2372
- *
2373
- * ```js
2374
- * I.moveCursorTo('.tooltip');
2375
- * I.moveCursorTo('#submit', 5,5);
2376
- * ```
2377
- *
2378
- * @param {CodeceptJS.LocatorOrString} locator located by CSS|XPath|strict locator.
2379
- * @param {number} [offsetX=0] (optional, `0` by default) X-axis offset.
2380
- * @param {number} [offsetY=0] (optional, `0` by default) Y-axis offset.
2381
- * @returns {void} automatically synchronized promise through #recorder
2382
- *
2383
- */
2384
- async moveCursorTo(locator, xOffset, yOffset) {
2385
- const res = await this._locate(withStrictLocator(locator), true);
2386
- assertElementExists(res, locator);
2387
- const elem = usingFirstElement(res);
2388
- try {
2389
- await elem.moveTo({ xOffset, yOffset });
2390
- } catch (e) {
2391
- debug(e.message);
2392
- }
2393
- }
2394
-
2395
- /**
2396
- * Saves screenshot of the specified locator to ouput folder (set in codecept.conf.ts or codecept.conf.js).
2397
- * Filename is relative to output folder.
2398
- *
2399
- * ```js
2400
- * I.saveElementScreenshot(`#submit`,'debug.png');
2401
- * ```
2402
- *
2403
- * @param {CodeceptJS.LocatorOrString} locator element located by CSS|XPath|strict locator.
2404
- * @param {string} fileName file name to save.
2405
- * @returns {void} automatically synchronized promise through #recorder
2406
- *
2407
- *
2408
- */
2409
- async saveElementScreenshot(locator, fileName) {
2410
- const outputFile = screenshotOutputFolder(fileName);
2411
-
2412
- const res = await this._locate(withStrictLocator(locator), true);
2413
- assertElementExists(res, locator);
2414
- const elem = usingFirstElement(res);
2415
-
2416
- this.debug(`Screenshot of ${(new Locator(locator))} element has been saved to ${outputFile}`);
2417
- return elem.saveScreenshot(outputFile);
2418
- }
2419
-
2420
- /**
2421
- * Saves a screenshot to ouput folder (set in codecept.conf.ts or codecept.conf.js).
2422
- * Filename is relative to output folder.
2423
- * 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.
2424
- *
2425
- * ```js
2426
- * I.saveScreenshot('debug.png');
2427
- * I.saveScreenshot('debug.png', true) //resizes to available scrollHeight and scrollWidth before taking screenshot
2428
- * ```
2429
- *
2430
- * @param {string} fileName file name to save.
2431
- * @param {boolean} [fullPage=false] (optional, `false` by default) flag to enable fullscreen screenshot mode.
2432
- * @returns {void} automatically synchronized promise through #recorder
2433
- *
2434
- */
2435
- async saveScreenshot(fileName, fullPage = false) {
2436
- const outputFile = screenshotOutputFolder(fileName);
2437
-
2438
- if (this.activeSessionName) {
2439
- const browser = this.sessionWindows[this.activeSessionName];
2440
-
2441
- if (browser) {
2442
- this.debug(`Screenshot of ${this.activeSessionName} session has been saved to ${outputFile}`);
2443
- return browser.saveScreenshot(outputFile);
2444
- }
2445
- }
2446
-
2447
- if (!fullPage) {
2448
- this.debug(`Screenshot has been saved to ${outputFile}`);
2449
- return this.browser.saveScreenshot(outputFile);
2450
- }
2451
-
2452
- /* eslint-disable prefer-arrow-callback, comma-dangle, prefer-const */
2453
- const originalWindowSize = await this.browser.getWindowSize();
2454
-
2455
- let { width, height } = await this.browser.execute(function () {
2456
- return {
2457
- height: document.body.scrollHeight,
2458
- width: document.body.scrollWidth
2459
- };
2460
- }).then(res => res);
2461
-
2462
- if (height < 100) height = 500; // errors for very small height
2463
- /* eslint-enable */
2464
-
2465
- await this.browser.setWindowSize(width, height);
2466
- this.debug(`Screenshot has been saved to ${outputFile}, size: ${width}x${height}`);
2467
- const buffer = await this.browser.saveScreenshot(outputFile);
2468
- await this.browser.setWindowSize(originalWindowSize.width, originalWindowSize.height);
2469
- return buffer;
2470
- }
2471
-
2472
- /**
2473
- * Uses Selenium's JSON [cookie format](https://code.google.com/p/selenium/wiki/JsonWireProtocol#Cookie_JSON_Object).
2474
- * Sets cookie(s).
2475
- *
2476
- * Can be a single cookie object or an array of cookies:
2477
- *
2478
- * ```js
2479
- * I.setCookie({name: 'auth', value: true});
2480
- *
2481
- * // as array
2482
- * I.setCookie([
2483
- * {name: 'auth', value: true},
2484
- * {name: 'agree', value: true}
2485
- * ]);
2486
- * ```
2487
- *
2488
- * @param {Cookie|Array<Cookie>} cookie a cookie object or array of cookie objects.
2489
- * @returns {void} automatically synchronized promise through #recorder
2490
- *
2491
- */
2492
- async setCookie(cookie) {
2493
- return this.browser.setCookies(cookie);
2494
- }
2495
-
2496
- /**
2497
- * Clears a cookie by name,
2498
- * if none provided clears all cookies.
2499
- *
2500
- * ```js
2501
- * I.clearCookie();
2502
- * I.clearCookie('test'); // Playwright currently doesn't support clear a particular cookie name
2503
- * ```
2504
- *
2505
- * @param {?string} [cookie=null] (optional, `null` by default) cookie name
2506
- *
2507
- */
2508
- async clearCookie(cookie) {
2509
- return this.browser.deleteCookies(cookie);
2510
- }
2511
-
2512
- /**
2513
- * Checks that cookie with given name exists.
2514
- *
2515
- * ```js
2516
- * I.seeCookie('Auth');
2517
- * ```
2518
- *
2519
- * @param {string} name cookie name.
2520
- * @returns {void} automatically synchronized promise through #recorder
2521
- *
2522
- */
2523
- async seeCookie(name) {
2524
- const cookie = await this.browser.getCookies([name]);
2525
- return truth(`cookie ${name}`, 'to be set').assert(cookie);
2526
- }
2527
-
2528
- /**
2529
- * Checks that cookie with given name does not exist.
2530
- *
2531
- * ```js
2532
- * I.dontSeeCookie('auth'); // no auth cookie
2533
- * ```
2534
- *
2535
- * @param {string} name cookie name.
2536
- * @returns {void} automatically synchronized promise through #recorder
2537
- *
2538
- */
2539
- async dontSeeCookie(name) {
2540
- const cookie = await this.browser.getCookies([name]);
2541
- return truth(`cookie ${name}`, 'to be set').negate(cookie);
2542
- }
2543
-
2544
- /**
2545
- * Gets a cookie object by name.
2546
- * If none provided gets all cookies.
2547
- * Resumes test execution, so **should be used inside async function with `await`** operator.
2548
- *
2549
- * ```js
2550
- * let cookie = await I.grabCookie('auth');
2551
- * assert(cookie.value, '123456');
2552
- * ```
2553
- *
2554
- * @param {?string} [name=null] cookie name.
2555
- * @returns {any} attribute value
2556
- *
2557
- */
2558
- async grabCookie(name) {
2559
- if (!name) return this.browser.getCookies();
2560
- const cookie = await this.browser.getCookies([name]);
2561
- this.debugSection('Cookie', JSON.stringify(cookie));
2562
- return cookie[0];
2563
- }
2564
-
2565
- /**
2566
- * Accepts the active JavaScript native popup window, as created by window.alert|window.confirm|window.prompt.
2567
- * Don't confuse popups with modal windows, as created by [various
2568
- * libraries](http://jster.net/category/windows-modals-popups).
2569
- */
2570
- async acceptPopup() {
2571
- return this.browser.getAlertText().then((res) => {
2572
- if (res !== null) {
2573
- return this.browser.acceptAlert();
2574
- }
2575
- });
2576
- }
2577
-
2578
- /**
2579
- * Dismisses the active JavaScript popup, as created by `window.alert|window.confirm|window.prompt`.
2580
- *
2581
- */
2582
- async cancelPopup() {
2583
- return this.browser.getAlertText().then((res) => {
2584
- if (res !== null) {
2585
- return this.browser.dismissAlert();
2586
- }
2587
- });
2588
- }
2589
-
2590
- /**
2591
- * Checks that the active JavaScript popup, as created by `window.alert|window.confirm|window.prompt`, contains the
2592
- * given string.
2593
- *
2594
- * @param {string} text value to check.
2595
- */
2596
- async seeInPopup(text) {
2597
- return this.browser.getAlertText().then((res) => {
2598
- if (res === null) {
2599
- throw new Error('Popup is not opened');
2600
- }
2601
- stringIncludes('text in popup').assert(text, res);
2602
- });
2603
- }
2604
-
2605
- /**
2606
- * Grab the text within the popup. If no popup is visible then it will return null.
2607
- * ```js
2608
- * await I.grabPopupText();
2609
- * ```
2610
- * @returns {Promise<string>}
2611
- *
2612
- */
2613
- async grabPopupText() {
2614
- try {
2615
- return await this.browser.getAlertText();
2616
- } catch (err) {
2617
- this.debugSection('Popup', 'Error getting text from popup');
2618
- }
2619
- }
2620
-
2621
- /**
2622
- * Presses a key in the browser and leaves it in a down state.
2623
- *
2624
- * To make combinations with modifier key and user operation (e.g. `'Control'` + [`click`](#click)).
2625
- *
2626
- * ```js
2627
- * I.pressKeyDown('Control');
2628
- * I.click('#element');
2629
- * I.pressKeyUp('Control');
2630
- * ```
2631
- *
2632
- * @param {string} key name of key to press down.
2633
- * @returns {void} automatically synchronized promise through #recorder
2634
- *
2635
- */
2636
- async pressKeyDown(key) {
2637
- key = getNormalizedKey.call(this, key);
2638
- if (!this.browser.isW3C) {
2639
- return this.browser.sendKeys([key]);
2640
- }
2641
- return this.browser.performActions([{
2642
- type: 'key',
2643
- id: 'keyboard',
2644
- actions: [{
2645
- type: 'keyDown',
2646
- value: key,
2647
- }],
2648
- }]);
2649
- }
2650
-
2651
- /**
2652
- * Releases a key in the browser which was previously set to a down state.
2653
- *
2654
- * To make combinations with modifier key and user operation (e.g. `'Control'` + [`click`](#click)).
2655
- *
2656
- * ```js
2657
- * I.pressKeyDown('Control');
2658
- * I.click('#element');
2659
- * I.pressKeyUp('Control');
2660
- * ```
2661
- *
2662
- * @param {string} key name of key to release.
2663
- * @returns {void} automatically synchronized promise through #recorder
2664
- *
2665
- */
2666
- async pressKeyUp(key) {
2667
- key = getNormalizedKey.call(this, key);
2668
- if (!this.browser.isW3C) {
2669
- return this.browser.sendKeys([key]);
2670
- }
2671
- return this.browser.performActions([{
2672
- type: 'key',
2673
- id: 'keyboard',
2674
- actions: [{
2675
- type: 'keyUp',
2676
- value: key,
2677
- }],
2678
- }]);
2679
- }
2680
-
2681
- /**
2682
- * _Note:_ In case a text field or textarea is focused be aware that some browsers do not respect active modifier when combining modifier keys with other keys.
2683
- *
2684
- * Presses a key in the browser (on a focused element).
2685
- *
2686
- * _Hint:_ For populating text field or textarea, it is recommended to use [`fillField`](#fillfield).
2687
- *
2688
- * ```js
2689
- * I.pressKey('Backspace');
2690
- * ```
2691
- *
2692
- * 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.
2693
- *
2694
- * ```js
2695
- * I.pressKey(['Control', 'Z']);
2696
- * ```
2697
- *
2698
- * For specifying operation modifier key based on operating system it is suggested to use `'CommandOrControl'`.
2699
- * This will press `'Command'` (also known as `'Meta'`) on macOS machines and `'Control'` on non-macOS machines.
2700
- *
2701
- * ```js
2702
- * I.pressKey(['CommandOrControl', 'Z']);
2703
- * ```
2704
- *
2705
- * Some of the supported key names are:
2706
- * - `'AltLeft'` or `'Alt'`
2707
- * - `'AltRight'`
2708
- * - `'ArrowDown'`
2709
- * - `'ArrowLeft'`
2710
- * - `'ArrowRight'`
2711
- * - `'ArrowUp'`
2712
- * - `'Backspace'`
2713
- * - `'Clear'`
2714
- * - `'ControlLeft'` or `'Control'`
2715
- * - `'ControlRight'`
2716
- * - `'Command'`
2717
- * - `'CommandOrControl'`
2718
- * - `'Delete'`
2719
- * - `'End'`
2720
- * - `'Enter'`
2721
- * - `'Escape'`
2722
- * - `'F1'` to `'F12'`
2723
- * - `'Home'`
2724
- * - `'Insert'`
2725
- * - `'MetaLeft'` or `'Meta'`
2726
- * - `'MetaRight'`
2727
- * - `'Numpad0'` to `'Numpad9'`
2728
- * - `'NumpadAdd'`
2729
- * - `'NumpadDecimal'`
2730
- * - `'NumpadDivide'`
2731
- * - `'NumpadMultiply'`
2732
- * - `'NumpadSubtract'`
2733
- * - `'PageDown'`
2734
- * - `'PageUp'`
2735
- * - `'Pause'`
2736
- * - `'Return'`
2737
- * - `'ShiftLeft'` or `'Shift'`
2738
- * - `'ShiftRight'`
2739
- * - `'Space'`
2740
- * - `'Tab'`
2741
- *
2742
- * @param {string|string[]} key key or array of keys to press.
2743
- * @returns {void} automatically synchronized promise through #recorder
2744
- *
2745
- */
2746
- async pressKey(key) {
2747
- const modifiers = [];
2748
- if (Array.isArray(key)) {
2749
- for (let k of key) {
2750
- k = getNormalizedKey.call(this, k);
2751
- if (isModifierKey(k)) {
2752
- modifiers.push(k);
2753
- } else {
2754
- key = k;
2755
- break;
2756
- }
2757
- }
2758
- } else {
2759
- key = getNormalizedKey.call(this, key);
2760
- }
2761
- for (const modifier of modifiers) {
2762
- await this.pressKeyDown(modifier);
2763
- }
2764
- if (!this.browser.isW3C) {
2765
- await this.browser.sendKeys([key]);
2766
- } else {
2767
- await this.browser.performActions([{
2768
- type: 'key',
2769
- id: 'keyboard',
2770
- actions: [{
2771
- type: 'keyDown',
2772
- value: key,
2773
- }, {
2774
- type: 'keyUp',
2775
- value: key,
2776
- }],
2777
- }]);
2778
- }
2779
- for (const modifier of modifiers) {
2780
- await this.pressKeyUp(modifier);
2781
- }
2782
- }
2783
-
2784
- /**
2785
- * Types out the given text into an active field.
2786
- * To slow down typing use a second parameter, to set interval between key presses.
2787
- * _Note:_ Should be used when [`fillField`](#fillfield) is not an option.
2788
- *
2789
- * ```js
2790
- * // passing in a string
2791
- * I.type('Type this out.');
2792
- *
2793
- * // typing values with a 100ms interval
2794
- * I.type('4141555311111111', 100);
2795
- *
2796
- * // passing in an array
2797
- * I.type(['T', 'E', 'X', 'T']);
2798
- *
2799
- * // passing a secret
2800
- * I.type(secret('123456'));
2801
- * ```
2802
- *
2803
- * @param {string|string[]} key or array of keys to type.
2804
- * @param {?number} [delay=null] (optional) delay in ms between key presses
2805
- * @returns {void} automatically synchronized promise through #recorder
2806
- *
2807
- */
2808
- async type(keys, delay = null) {
2809
- if (!Array.isArray(keys)) {
2810
- keys = keys.toString();
2811
- keys = keys.split('');
2812
- }
2813
- if (delay) {
2814
- for (const key of keys) {
2815
- await this.browser.keys(key);
2816
- await this.wait(delay / 1000);
2817
- }
2818
- return;
2819
- }
2820
- await this.browser.keys(keys);
2821
- }
2822
-
2823
- /**
2824
- * Appium: not tested in web, in apps doesn't work
2825
- *
2826
- * Resize the current window to provided width and height.
2827
- * First parameter can be set to `maximize`.
2828
- *
2829
- * @param {number} width width in pixels or `maximize`.
2830
- * @param {number} height height in pixels.
2831
- * @returns {void} automatically synchronized promise through #recorder
2832
- *
2833
- */
2834
- async resizeWindow(width, height) {
2835
- return this.browser.setWindowSize(width, height);
2836
- }
2837
-
2838
- async _resizeBrowserWindow(browser, width, height) {
2839
- if (width === 'maximize') {
2840
- const size = await browser.maximizeWindow();
2841
- this.debugSection('Window Size', size);
2842
- return;
2843
- }
2844
- if (browser.isW3C) {
2845
- return browser.setWindowRect(null, null, parseInt(width, 10), parseInt(height, 10));
2846
- }
2847
- return browser.setWindowSize(parseInt(width, 10), parseInt(height, 10));
2848
- }
2849
-
2850
- async _resizeWindowIfNeeded(browser, windowSize) {
2851
- if (this.isWeb && windowSize === 'maximize') {
2852
- await this._resizeBrowserWindow(browser, 'maximize');
2853
- } else if (this.isWeb && windowSize && windowSize.indexOf('x') > 0) {
2854
- const dimensions = windowSize.split('x');
2855
- await this._resizeBrowserWindow(browser, dimensions[0], dimensions[1]);
2856
- }
2857
- }
2858
-
2859
- /**
2860
- * Calls [focus](https://developer.mozilla.org/en-US/docs/Web/API/HTMLElement/focus) on the matching element.
2861
- *
2862
- * Examples:
2863
- *
2864
- * ```js
2865
- * I.dontSee('#add-to-cart-btn');
2866
- * I.focus('#product-tile')
2867
- * I.see('#add-to-cart-bnt');
2868
- * ```
2869
- *
2870
- * @param {CodeceptJS.LocatorOrString} locator field located by label|name|CSS|XPath|strict locator.
2871
- * @param {any} [options] Playwright only: [Additional options](https://playwright.dev/docs/api/class-locator#locator-focus) for available options object as 2nd argument.
2872
- * @returns {void} automatically synchronized promise through #recorder
2873
- *
2874
- *
2875
- */
2876
- async focus(locator) {
2877
- const els = await this._locate(locator);
2878
- assertElementExists(els, locator, 'Element to focus');
2879
- const el = usingFirstElement(els);
2880
-
2881
- await focusElement(el, this.browser);
2882
- }
2883
-
2884
- /**
2885
- * Remove focus from a text input, button, etc.
2886
- * Calls [blur](https://developer.mozilla.org/en-US/docs/Web/API/HTMLElement/focus) on the element.
2887
- *
2888
- * Examples:
2889
- *
2890
- * ```js
2891
- * I.blur('.text-area')
2892
- * ```
2893
- * ```js
2894
- * //element `#product-tile` is focused
2895
- * I.see('#add-to-cart-btn');
2896
- * I.blur('#product-tile')
2897
- * I.dontSee('#add-to-cart-btn');
2898
- * ```
2899
- *
2900
- * @param {CodeceptJS.LocatorOrString} locator field located by label|name|CSS|XPath|strict locator.
2901
- * @param {any} [options] Playwright only: [Additional options](https://playwright.dev/docs/api/class-locator#locator-blur) for available options object as 2nd argument.
2902
- * @returns {void} automatically synchronized promise through #recorder
2903
- *
2904
- *
2905
- */
2906
- async blur(locator) {
2907
- const els = await this._locate(locator);
2908
- assertElementExists(els, locator, 'Element to blur');
2909
- const el = usingFirstElement(els);
2910
-
2911
- await blurElement(el, this.browser);
2912
- }
2913
-
2914
- /**
2915
- * Appium: not tested
2916
- * Drag an item to a destination element.
2917
- *
2918
- * ```js
2919
- * I.dragAndDrop('#dragHandle', '#container');
2920
- * ```
2921
- *
2922
- * @param {LocatorOrString} srcElement located by CSS|XPath|strict locator.
2923
- * @param {LocatorOrString} destElement located by CSS|XPath|strict locator.
2924
- * @returns {void} automatically synchronized promise through #recorder
2925
- *
2926
- */
2927
- async dragAndDrop(srcElement, destElement) {
2928
- let sourceEl = await this._locate(srcElement);
2929
- assertElementExists(sourceEl, srcElement);
2930
- sourceEl = usingFirstElement(sourceEl);
2931
-
2932
- let destEl = await this._locate(destElement);
2933
- assertElementExists(destEl, destElement);
2934
- destEl = usingFirstElement(destEl);
2935
-
2936
- return sourceEl.dragAndDrop(destEl);
2937
- }
2938
-
2939
- /**
2940
- * Drag the scrubber of a slider to a given position
2941
- * For fuzzy locators, fields are matched by label text, the "name" attribute, CSS, and XPath.
2942
- *
2943
- * ```js
2944
- * I.dragSlider('#slider', 30);
2945
- * I.dragSlider('#slider', -70);
2946
- * ```
2947
- *
2948
- * @param {CodeceptJS.LocatorOrString} locator located by label|name|CSS|XPath|strict locator.
2949
- * @param {number} offsetX position to drag.
2950
- * @returns {void} automatically synchronized promise through #recorder
2951
- *
2952
- */
2953
- async dragSlider(locator, offsetX = 0) {
2954
- const browser = this.browser;
2955
- await this.moveCursorTo(locator);
2956
-
2957
- // for chrome
2958
- if (browser.isW3C) {
2959
- const xOffset = await this.grabElementBoundingRect(locator, 'x');
2960
- const yOffset = await this.grabElementBoundingRect(locator, 'y');
2961
-
2962
- return browser.performActions([{
2963
- type: 'pointer',
2964
- id: 'pointer1',
2965
- parameters: { pointerType: 'mouse' },
2966
- actions: [
2967
- {
2968
- type: 'pointerMove', origin: 'pointer', duration: 1000, x: xOffset, y: yOffset,
2969
- },
2970
- { type: 'pointerDown', button: 0 },
2971
- {
2972
- type: 'pointerMove', origin: 'pointer', duration: 1000, x: offsetX, y: 0,
2973
- },
2974
- { type: 'pointerUp', button: 0 },
2975
- ],
2976
- },
2977
- ]);
2978
- }
2979
-
2980
- await browser.buttonDown(0);
2981
- await browser.moveToElement(null, offsetX, 0);
2982
- await browser.buttonUp(0);
2983
- }
2984
-
2985
- /**
2986
- * Get all Window Handles.
2987
- * Useful for referencing a specific handle when calling `I.switchToWindow(handle)`
2988
- *
2989
- * ```js
2990
- * const windows = await I.grabAllWindowHandles();
2991
- * ```
2992
- * @returns {Promise<string[]>}
2993
- *
2994
- */
2995
- async grabAllWindowHandles() {
2996
- return this.browser.getWindowHandles();
2997
- }
2998
-
2999
- /**
3000
- * Get the current Window Handle.
3001
- * Useful for referencing it when calling `I.switchToWindow(handle)`
3002
- * ```js
3003
- * const window = await I.grabCurrentWindowHandle();
3004
- * ```
3005
- * @returns {Promise<string>}
3006
- *
3007
- */
3008
- async grabCurrentWindowHandle() {
3009
- return this.browser.getWindowHandle();
3010
- }
3011
-
3012
- /**
3013
- * Switch to the window with a specified handle.
3014
- *
3015
- * ```js
3016
- * const windows = await I.grabAllWindowHandles();
3017
- * // ... do something
3018
- * await I.switchToWindow( windows[0] );
3019
- *
3020
- * const window = await I.grabCurrentWindowHandle();
3021
- * // ... do something
3022
- * await I.switchToWindow( window );
3023
- * ```
3024
- * @param {string} window name of window handle.
3025
- */
3026
- async switchToWindow(window) {
3027
- await this.browser.switchToWindow(window);
3028
- }
3029
-
3030
- /**
3031
- * Close all tabs except for the current one.
3032
- *
3033
- *
3034
- * ```js
3035
- * I.closeOtherTabs();
3036
- * ```
3037
- *
3038
- * @returns {void} automatically synchronized promise through #recorder
3039
- *
3040
- */
3041
- async closeOtherTabs() {
3042
- const handles = await this.browser.getWindowHandles();
3043
- const currentHandle = await this.browser.getWindowHandle();
3044
- const otherHandles = handles.filter(handle => handle !== currentHandle);
3045
-
3046
- await forEachAsync(otherHandles, async (handle) => {
3047
- await this.browser.switchToWindow(handle);
3048
- await this.browser.closeWindow();
3049
- });
3050
- await this.browser.switchToWindow(currentHandle);
3051
- }
3052
-
3053
- /**
3054
- * Pauses execution for a number of seconds.
3055
- *
3056
- * ```js
3057
- * I.wait(2); // wait 2 secs
3058
- * ```
3059
- *
3060
- * @param {number} sec number of second to wait.
3061
- * @returns {void} automatically synchronized promise through #recorder
3062
- *
3063
- */
3064
- async wait(sec) {
3065
- return new Promise(resolve => {
3066
- setTimeout(resolve, sec * 1000);
3067
- });
3068
- }
3069
-
3070
- /**
3071
- * Waits for element to become enabled (by default waits for 1sec).
3072
- * Element can be located by CSS or XPath.
3073
- *
3074
- * @param {CodeceptJS.LocatorOrString} locator element located by CSS|XPath|strict locator.
3075
- * @param {number} [sec=1] (optional) time in seconds to wait, 1 by default.
3076
- * @returns {void} automatically synchronized promise through #recorder
3077
- *
3078
- */
3079
- async waitForEnabled(locator, sec = null) {
3080
- const aSec = sec || this.options.waitForTimeoutInSeconds;
3081
-
3082
- return this.browser.waitUntil(async () => {
3083
- const res = await this._res(locator);
3084
- if (!res || res.length === 0) {
3085
- return false;
3086
- }
3087
- const selected = await forEachAsync(res, async el => this.browser.isElementEnabled(getElementId(el)));
3088
- if (Array.isArray(selected)) {
3089
- return selected.filter(val => val === true).length > 0;
3090
- }
3091
- return selected;
3092
- }, {
3093
- timeout: aSec * 1000,
3094
- timeoutMsg: `element (${new Locator(locator)}) still not enabled after ${aSec} sec`,
3095
- });
3096
- }
3097
-
3098
- /**
3099
- * Waits for element to be present on page (by default waits for 1sec).
3100
- * Element can be located by CSS or XPath.
3101
- *
3102
- * ```js
3103
- * I.waitForElement('.btn.continue');
3104
- * I.waitForElement('.btn.continue', 5); // wait for 5 secs
3105
- * ```
3106
- *
3107
- * @param {CodeceptJS.LocatorOrString} locator element located by CSS|XPath|strict locator.
3108
- * @param {number} [sec] (optional, `1` by default) time in seconds to wait
3109
- * @returns {void} automatically synchronized promise through #recorder
3110
- *
3111
- */
3112
- async waitForElement(locator, sec = null) {
3113
- const aSec = sec || this.options.waitForTimeoutInSeconds;
3114
-
3115
- return this.browser.waitUntil(async () => {
3116
- const res = await this._res(locator);
3117
- return res && res.length;
3118
- }, { timeout: aSec * 1000, timeoutMsg: `element (${(new Locator(locator))}) still not present on page after ${aSec} sec` });
3119
- }
3120
-
3121
- /**
3122
- * Waits for element to be clickable (by default waits for 1sec).
3123
- * Element can be located by CSS or XPath.
3124
- *
3125
- * ```js
3126
- * I.waitForClickable('.btn.continue');
3127
- * I.waitForClickable('.btn.continue', 5); // wait for 5 secs
3128
- * ```
3129
- *
3130
- * @param {CodeceptJS.LocatorOrString} locator element located by CSS|XPath|strict locator.
3131
- * @param {number} [sec] (optional, `1` by default) time in seconds to wait
3132
- * @returns {void} automatically synchronized promise through #recorder
3133
- *
3134
- */
3135
- async waitForClickable(locator, waitTimeout) {
3136
- waitTimeout = waitTimeout || this.options.waitForTimeoutInSeconds;
3137
- let res = await this._locate(locator);
3138
- res = usingFirstElement(res);
3139
- assertElementExists(res, locator);
3140
-
3141
- return res.waitForClickable({
3142
- timeout: waitTimeout * 1000,
3143
- timeoutMsg: `element ${res.selector} still not clickable after ${waitTimeout} sec`,
3144
- });
3145
- }
3146
-
3147
- /**
3148
- * Waiting for the part of the URL to match the expected. Useful for SPA to understand that page was changed.
3149
- *
3150
- * ```js
3151
- * I.waitInUrl('/info', 2);
3152
- * ```
3153
- *
3154
- * @param {string} urlPart value to check.
3155
- * @param {number} [sec=1] (optional, `1` by default) time in seconds to wait
3156
- * @returns {void} automatically synchronized promise through #recorder
3157
- *
3158
- */
3159
- async waitInUrl(urlPart, sec = null) {
3160
- const client = this.browser;
3161
- const aSec = sec || this.options.waitForTimeoutInSeconds;
3162
- let currUrl = '';
3163
-
3164
- return client
3165
- .waitUntil(function () {
3166
- return this.getUrl().then((res) => {
3167
- currUrl = decodeUrl(res);
3168
- return currUrl.indexOf(urlPart) > -1;
3169
- });
3170
- }, { timeout: aSec * 1000 }).catch((e) => {
3171
- if (e.message.indexOf('timeout')) {
3172
- throw new Error(`expected url to include ${urlPart}, but found ${currUrl}`);
3173
- }
3174
- throw e;
3175
- });
3176
- }
3177
-
3178
- /**
3179
- * Waits for the entire URL to match the expected
3180
- *
3181
- * ```js
3182
- * I.waitUrlEquals('/info', 2);
3183
- * I.waitUrlEquals('http://127.0.0.1:8000/info');
3184
- * ```
3185
- *
3186
- * @param {string} urlPart value to check.
3187
- * @param {number} [sec=1] (optional, `1` by default) time in seconds to wait
3188
- * @returns {void} automatically synchronized promise through #recorder
3189
- *
3190
- */
3191
- async waitUrlEquals(urlPart, sec = null) {
3192
- const aSec = sec || this.options.waitForTimeoutInSeconds;
3193
- const baseUrl = this.options.url;
3194
- if (urlPart.indexOf('http') < 0) {
3195
- urlPart = baseUrl + urlPart;
3196
- }
3197
- let currUrl = '';
3198
- return this.browser.waitUntil(function () {
3199
- return this.getUrl().then((res) => {
3200
- currUrl = decodeUrl(res);
3201
- return currUrl === urlPart;
3202
- });
3203
- }, aSec * 1000).catch((e) => {
3204
- if (e.message.indexOf('timeout')) {
3205
- throw new Error(`expected url to be ${urlPart}, but found ${currUrl}`);
3206
- }
3207
- throw e;
3208
- });
3209
- }
3210
-
3211
- /**
3212
- * Waits for a text to appear (by default waits for 1sec).
3213
- * Element can be located by CSS or XPath.
3214
- * Narrow down search results by providing context.
3215
- *
3216
- * ```js
3217
- * I.waitForText('Thank you, form has been submitted');
3218
- * I.waitForText('Thank you, form has been submitted', 5, '#modal');
3219
- * ```
3220
- *
3221
- * @param {string }text to wait for.
3222
- * @param {number} [sec=1] (optional, `1` by default) time in seconds to wait
3223
- * @param {CodeceptJS.LocatorOrString} [context] (optional) element located by CSS|XPath|strict locator.
3224
- * @returns {void} automatically synchronized promise through #recorder
3225
- *
3226
- *
3227
- */
3228
- async waitForText(text, sec = null, context = null) {
3229
- const aSec = sec || this.options.waitForTimeoutInSeconds;
3230
- const _context = context || this.root;
3231
-
3232
- return this.browser.waitUntil(async () => {
3233
- const res = await this.$$(withStrictLocator.call(this, _context));
3234
- if (!res || res.length === 0) return false;
3235
- const selected = await forEachAsync(res, async el => this.browser.getElementText(getElementId(el)));
3236
- if (Array.isArray(selected)) {
3237
- return selected.filter(part => part.indexOf(text) >= 0).length > 0;
3238
- }
3239
- return selected.indexOf(text) >= 0;
3240
- }, {
3241
- timeout: aSec * 1000,
3242
- timeoutMsg: `element (${_context}) is not in DOM or there is no element(${_context}) with text "${text}" after ${aSec} sec`,
3243
- });
3244
- }
3245
-
3246
- /**
3247
- * Waits for the specified value to be in value attribute.
3248
- *
3249
- * ```js
3250
- * I.waitForValue('//input', "GoodValue");
3251
- * ```
3252
- *
3253
- * @param {LocatorOrString} field input field.
3254
- * @param {string }value expected value.
3255
- * @param {number} [sec=1] (optional, `1` by default) time in seconds to wait
3256
- * @returns {void} automatically synchronized promise through #recorder
3257
- *
3258
- */
3259
- async waitForValue(field, value, sec = null) {
3260
- const client = this.browser;
3261
- const aSec = sec || this.options.waitForTimeoutInSeconds;
3262
-
3263
- return client.waitUntil(async () => {
3264
- const res = await findFields.call(this, field);
3265
- if (!res || res.length === 0) return false;
3266
- const selected = await forEachAsync(res, async el => el.getValue());
3267
- if (Array.isArray(selected)) {
3268
- return selected.filter(part => part.indexOf(value) >= 0).length > 0;
3269
- }
3270
- return selected.indexOf(value) >= 0;
3271
- }, {
3272
- timeout: aSec * 1000,
3273
- timeoutMsg: `element (${field}) is not in DOM or there is no element(${field}) with value "${value}" after ${aSec} sec`,
3274
- });
3275
- }
3276
-
3277
- /**
3278
- * Waits for an element to become visible on a page (by default waits for 1sec).
3279
- * Element can be located by CSS or XPath.
3280
- *
3281
- * ```js
3282
- * I.waitForVisible('#popup');
3283
- * ```
3284
- *
3285
- * @param {CodeceptJS.LocatorOrString} locator element located by CSS|XPath|strict locator.
3286
- * @param {number} [sec=1] (optional, `1` by default) time in seconds to wait
3287
- * @returns {void} automatically synchronized promise through #recorder
3288
- *
3289
- *
3290
- */
3291
- async waitForVisible(locator, sec = null) {
3292
- const aSec = sec || this.options.waitForTimeoutInSeconds;
3293
-
3294
- return this.browser.waitUntil(async () => {
3295
- const res = await this._res(locator);
3296
- if (!res || res.length === 0) return false;
3297
- const selected = await forEachAsync(res, async el => el.isDisplayed());
3298
- if (Array.isArray(selected)) {
3299
- return selected.filter(val => val === true).length > 0;
3300
- }
3301
- return selected;
3302
- }, { timeout: aSec * 1000, timeoutMsg: `element (${new Locator(locator)}) still not visible after ${aSec} sec` });
3303
- }
3304
-
3305
- /**
3306
- * Waits for a specified number of elements on the page.
3307
- *
3308
- * ```js
3309
- * I.waitNumberOfVisibleElements('a', 3);
3310
- * ```
3311
- *
3312
- * @param {CodeceptJS.LocatorOrString} locator element located by CSS|XPath|strict locator.
3313
- * @param {number} num number of elements.
3314
- * @param {number} [sec=1] (optional, `1` by default) time in seconds to wait
3315
- * @returns {void} automatically synchronized promise through #recorder
3316
- *
3317
- */
3318
- async waitNumberOfVisibleElements(locator, num, sec = null) {
3319
- const aSec = sec || this.options.waitForTimeoutInSeconds;
3320
-
3321
- return this.browser.waitUntil(async () => {
3322
- const res = await this._res(locator);
3323
- if (!res || res.length === 0) return false;
3324
- let selected = await forEachAsync(res, async el => el.isDisplayed());
3325
-
3326
- if (!Array.isArray(selected)) selected = [selected];
3327
- selected = selected.filter(val => val === true);
3328
- return selected.length === num;
3329
- }, { timeout: aSec * 1000, timeoutMsg: `The number of elements (${new Locator(locator)}) is not ${num} after ${aSec} sec` });
3330
- }
3331
-
3332
- /**
3333
- * Waits for an element to be removed or become invisible on a page (by default waits for 1sec).
3334
- * Element can be located by CSS or XPath.
3335
- *
3336
- * ```js
3337
- * I.waitForInvisible('#popup');
3338
- * ```
3339
- *
3340
- * @param {CodeceptJS.LocatorOrString} locator element located by CSS|XPath|strict locator.
3341
- * @param {number} [sec=1] (optional, `1` by default) time in seconds to wait
3342
- * @returns {void} automatically synchronized promise through #recorder
3343
- *
3344
- */
3345
- async waitForInvisible(locator, sec = null) {
3346
- const aSec = sec || this.options.waitForTimeoutInSeconds;
3347
-
3348
- return this.browser.waitUntil(async () => {
3349
- const res = await this._res(locator);
3350
- if (!res || res.length === 0) return true;
3351
- const selected = await forEachAsync(res, async el => el.isDisplayed());
3352
- return !selected.length;
3353
- }, { timeout: aSec * 1000, timeoutMsg: `element (${new Locator(locator)}) still visible after ${aSec} sec` });
3354
- }
3355
-
3356
- /**
3357
- * Waits for an element to hide (by default waits for 1sec).
3358
- * Element can be located by CSS or XPath.
3359
- *
3360
- * ```js
3361
- * I.waitToHide('#popup');
3362
- * ```
3363
- *
3364
- * @param {CodeceptJS.LocatorOrString} locator element located by CSS|XPath|strict locator.
3365
- * @param {number} [sec=1] (optional, `1` by default) time in seconds to wait
3366
- * @returns {void} automatically synchronized promise through #recorder
3367
- *
3368
- */
3369
- async waitToHide(locator, sec = null) {
3370
- return this.waitForInvisible(locator, sec);
3371
- }
3372
-
3373
- /**
3374
- * Waits for an element to become not attached to the DOM on a page (by default waits for 1sec).
3375
- * Element can be located by CSS or XPath.
3376
- *
3377
- * ```js
3378
- * I.waitForDetached('#popup');
3379
- * ```
3380
- *
3381
- * @param {CodeceptJS.LocatorOrString} locator element located by CSS|XPath|strict locator.
3382
- * @param {number} [sec=1] (optional, `1` by default) time in seconds to wait
3383
- * @returns {void} automatically synchronized promise through #recorder
3384
- *
3385
- */
3386
- async waitForDetached(locator, sec = null) {
3387
- const aSec = sec || this.options.waitForTimeoutInSeconds;
3388
-
3389
- return this.browser.waitUntil(async () => {
3390
- const res = await this._res(locator);
3391
- if (!res || res.length === 0) {
3392
- return true;
3393
- }
3394
- return false;
3395
- }, { timeout: aSec * 1000, timeoutMsg: `element (${new Locator(locator)}) still on page after ${aSec} sec` });
3396
- }
3397
-
3398
- /**
3399
- * Waits for a function to return true (waits for 1 sec by default).
3400
- * Running in browser context.
3401
- *
3402
- * ```js
3403
- * I.waitForFunction(fn[, [args[, timeout]])
3404
- * ```
3405
- *
3406
- * ```js
3407
- * I.waitForFunction(() => window.requests == 0);
3408
- * I.waitForFunction(() => window.requests == 0, 5); // waits for 5 sec
3409
- * I.waitForFunction((count) => window.requests == count, [3], 5) // pass args and wait for 5 sec
3410
- * ```
3411
- *
3412
- * @param {string|function} fn to be executed in browser context.
3413
- * @param {any[]|number} [argsOrSec] (optional, `1` by default) arguments for function or seconds.
3414
- * @param {number} [sec] (optional, `1` by default) time in seconds to wait
3415
- * @returns {void} automatically synchronized promise through #recorder
3416
- *
3417
- */
3418
- async waitForFunction(fn, argsOrSec = null, sec = null) {
3419
- let args = [];
3420
- if (argsOrSec) {
3421
- if (Array.isArray(argsOrSec)) {
3422
- args = argsOrSec;
3423
- } else if (typeof argsOrSec === 'number') {
3424
- sec = argsOrSec;
3425
- }
3426
- }
3427
-
3428
- const aSec = sec || this.options.waitForTimeoutInSeconds;
3429
-
3430
- return this.browser.waitUntil(async () => this.browser.execute(fn, ...args), { timeout: aSec * 1000, timeoutMsg: '' });
3431
- }
3432
-
3433
- /**
3434
- * Waits for number of tabs.
3435
- *
3436
- * ```js
3437
- * I.waitForNumberOfTabs(2);
3438
- * ```
3439
- *
3440
- * @param {number} expectedTabs expecting the number of tabs.
3441
- * @param {number} sec number of secs to wait.
3442
- * @returns {void} automatically synchronized promise through #recorder
3443
- *
3444
- */
3445
- async waitForNumberOfTabs(expectedTabs, sec) {
3446
- const waitTimeout = sec ? sec * 1000 : this.options.waitForTimeoutInSeconds;
3447
- let currentTabs;
3448
- let count = 0;
3449
-
3450
- do {
3451
- currentTabs = await this.grabNumberOfOpenTabs();
3452
- await this.wait(1);
3453
- count += 1000;
3454
- if (currentTabs >= expectedTabs) return;
3455
- } while (count <= waitTimeout);
3456
-
3457
- throw new Error(`Expected ${expectedTabs} tabs are not met after ${waitTimeout / 1000} sec.`);
3458
- }
3459
-
3460
- /**
3461
- * Switches frame or in case of null locator reverts to parent.
3462
- *
3463
- * ```js
3464
- * I.switchTo('iframe'); // switch to first iframe
3465
- * I.switchTo(); // switch back to main page
3466
- * ```
3467
- *
3468
- * @param {?CodeceptJS.LocatorOrString} [locator=null] (optional, `null` by default) element located by CSS|XPath|strict locator.
3469
- * @returns {void} automatically synchronized promise through #recorder
3470
- *
3471
- */
3472
- async switchTo(locator) {
3473
- this.browser.isInsideFrame = true;
3474
- if (Number.isInteger(locator)) {
3475
- if (this.options.automationProtocol) {
3476
- return this.browser.switchToFrame(locator + 1);
3477
- }
3478
- return this.browser.switchToFrame(locator);
3479
- }
3480
- if (!locator) {
3481
- return this.browser.switchToFrame(null);
3482
- }
3483
-
3484
- let res = await this._locate(locator, true);
3485
- assertElementExists(res, locator);
3486
- res = usingFirstElement(res);
3487
- return this.browser.switchToFrame(res);
3488
- }
3489
-
3490
- /**
3491
- * Switch focus to a particular tab by its number. It waits tabs loading and then switch tab.
3492
- *
3493
- * ```js
3494
- * I.switchToNextTab();
3495
- * I.switchToNextTab(2);
3496
- * ```
3497
- *
3498
- * @param {number} [num] (optional) number of tabs to switch forward, default: 1.
3499
- * @param {number | null} [sec] (optional) time in seconds to wait.
3500
- * @returns {void} automatically synchronized promise through #recorder
3501
- *
3502
- */
3503
- async switchToNextTab(num = 1, sec = null) {
3504
- const aSec = sec || this.options.waitForTimeoutInSeconds;
3505
- let target;
3506
- const current = await this.browser.getWindowHandle();
3507
-
3508
- await this.browser.waitUntil(async () => {
3509
- await this.browser.getWindowHandles().then((handles) => {
3510
- if (handles.indexOf(current) + num + 1 <= handles.length) {
3511
- target = handles[handles.indexOf(current) + num];
3512
- }
3513
- });
3514
- return target;
3515
- }, { timeout: aSec * 1000, timeoutMsg: `There is no ability to switch to next tab with offset ${num}` });
3516
- return this.browser.switchToWindow(target);
3517
- }
3518
-
3519
- /**
3520
- * Switch focus to a particular tab by its number. It waits tabs loading and then switch tab.
3521
- *
3522
- * ```js
3523
- * I.switchToPreviousTab();
3524
- * I.switchToPreviousTab(2);
3525
- * ```
3526
- *
3527
- * @param {number} [num] (optional) number of tabs to switch backward, default: 1.
3528
- * @param {number?} [sec] (optional) time in seconds to wait.
3529
- * @returns {void} automatically synchronized promise through #recorder
3530
- *
3531
- */
3532
- async switchToPreviousTab(num = 1, sec = null) {
3533
- const aSec = sec || this.options.waitForTimeoutInSeconds;
3534
- const current = await this.browser.getWindowHandle();
3535
- let target;
3536
-
3537
- await this.browser.waitUntil(async () => {
3538
- await this.browser.getWindowHandles().then((handles) => {
3539
- if (handles.indexOf(current) - num > -1) {
3540
- target = handles[handles.indexOf(current) - num];
3541
- }
3542
- });
3543
- return target;
3544
- }, { timeout: aSec * 1000, timeoutMsg: `There is no ability to switch to previous tab with offset ${num}` });
3545
- return this.browser.switchToWindow(target);
3546
- }
3547
-
3548
- /**
3549
- * Close current tab.
3550
- *
3551
- * ```js
3552
- * I.closeCurrentTab();
3553
- * ```
3554
- *
3555
- * @returns {void} automatically synchronized promise through #recorder
3556
- *
3557
- */
3558
- async closeCurrentTab() {
3559
- await this.browser.closeWindow();
3560
- const handles = await this.browser.getWindowHandles();
3561
- if (handles[0]) await this.browser.switchToWindow(handles[0]);
3562
- }
3563
-
3564
- /**
3565
- * Open new tab and switch to it.
3566
- *
3567
- * ```js
3568
- * I.openNewTab();
3569
- * ```
3570
- *
3571
- * @returns {void} automatically synchronized promise through #recorder
3572
- *
3573
- */
3574
- async openNewTab(url = 'about:blank', windowName = null) {
3575
- const client = this.browser;
3576
- const crypto = require('crypto');
3577
- if (windowName == null) {
3578
- windowName = crypto.randomBytes(32).toString('hex');
3579
- }
3580
- return client.newWindow(url, windowName);
3581
- }
3582
-
3583
- /**
3584
- * Grab number of open tabs.
3585
- * Resumes test execution, so **should be used inside async function with `await`** operator.
3586
- *
3587
- * ```js
3588
- * let tabs = await I.grabNumberOfOpenTabs();
3589
- * ```
3590
- *
3591
- * @returns {Promise<number>} number of open tabs
3592
- *
3593
- */
3594
- async grabNumberOfOpenTabs() {
3595
- const pages = await this.browser.getWindowHandles();
3596
- this.debugSection('Tabs', `Total ${pages.length}`);
3597
- return pages.length;
3598
- }
3599
-
3600
- /**
3601
- * Reload the current page.
3602
- *
3603
- * ```js
3604
- * I.refreshPage();
3605
- * ```
3606
- * @returns {void} automatically synchronized promise through #recorder
3607
- *
3608
- */
3609
- async refreshPage() {
3610
- const client = this.browser;
3611
- return client.refresh();
3612
- }
3613
-
3614
- /**
3615
- * Scroll page to the top.
3616
- *
3617
- * ```js
3618
- * I.scrollPageToTop();
3619
- * ```
3620
- * @returns {void} automatically synchronized promise through #recorder
3621
- *
3622
- */
3623
- scrollPageToTop() {
3624
- const client = this.browser;
3625
- /* eslint-disable prefer-arrow-callback */
3626
- return client.execute(function () {
3627
- window.scrollTo(0, 0);
3628
- });
3629
- /* eslint-enable */
3630
- }
3631
-
3632
- /**
3633
- * Scroll page to the bottom.
3634
- *
3635
- * ```js
3636
- * I.scrollPageToBottom();
3637
- * ```
3638
- * @returns {void} automatically synchronized promise through #recorder
3639
- *
3640
- */
3641
- scrollPageToBottom() {
3642
- const client = this.browser;
3643
- /* eslint-disable prefer-arrow-callback, comma-dangle */
3644
- return client.execute(function () {
3645
- const body = document.body;
3646
- const html = document.documentElement;
3647
- window.scrollTo(0, Math.max(
3648
- body.scrollHeight,
3649
- body.offsetHeight,
3650
- html.clientHeight,
3651
- html.scrollHeight,
3652
- html.offsetHeight
3653
- ));
3654
- });
3655
- /* eslint-enable */
3656
- }
3657
-
3658
- /**
3659
- * Retrieves a page scroll position and returns it to test.
3660
- * Resumes test execution, so **should be used inside an async function with `await`** operator.
3661
- *
3662
- * ```js
3663
- * let { x, y } = await I.grabPageScrollPosition();
3664
- * ```
3665
- *
3666
- * @returns {Promise<PageScrollPosition>} scroll position
3667
- *
3668
- */
3669
- async grabPageScrollPosition() {
3670
- /* eslint-disable comma-dangle */
3671
- function getScrollPosition() {
3672
- return {
3673
- x: window.pageXOffset,
3674
- y: window.pageYOffset
3675
- };
3676
- }
3677
- /* eslint-enable comma-dangle */
3678
- return this.executeScript(getScrollPosition);
3679
- }
3680
-
3681
- /**
3682
- * This method is **deprecated**.
3683
- *
3684
- *
3685
- * Set the current geo location
3686
- *
3687
- *
3688
- * ```js
3689
- * I.setGeoLocation(121.21, 11.56);
3690
- * I.setGeoLocation(121.21, 11.56, 10);
3691
- * ```
3692
- *
3693
- * @param {number} latitude to set.
3694
- * @param {number} longitude to set
3695
- * @param {number=} altitude (optional, null by default) to set
3696
- * @returns {void} automatically synchronized promise through #recorder
3697
- *
3698
- */
3699
- async setGeoLocation(latitude, longitude) {
3700
- if (!this.options.automationProtocol) {
3701
- console.log(`setGeoLocation deprecated:
3702
- * This command is deprecated due to using deprecated JSON Wire Protocol command. More info: https://webdriver.io/docs/api/jsonwp/#setgeolocation
3703
- * Switch to devtools protocol to use this command by setting devtoolsProtocol: true in the configuration`);
3704
- return;
3705
- }
3706
- this.geoLocation = { latitude, longitude };
3707
- const puppeteerBrowser = await this.browser.getPuppeteer();
3708
- await this.browser.call(async () => {
3709
- const pages = await puppeteerBrowser.pages();
3710
- await pages[0].setGeolocation({ latitude, longitude });
3711
- });
3712
- }
3713
-
3714
- /**
3715
- * This method is **deprecated**.
3716
- *
3717
- * Return the current geo location
3718
- * Resumes test execution, so **should be used inside async function with `await`** operator.
3719
- *
3720
- * ```js
3721
- * let geoLocation = await I.grabGeoLocation();
3722
- * ```
3723
- *
3724
- * @returns {Promise<{ latitude: number, longitude: number, altitude: number }>}
3725
- *
3726
- */
3727
- async grabGeoLocation() {
3728
- if (!this.options.automationProtocol) {
3729
- console.log(`grabGeoLocation deprecated:
3730
- * This command is deprecated due to using deprecated JSON Wire Protocol command. More info: https://webdriver.io/docs/api/jsonwp/#getgeolocation
3731
- * Switch to devtools protocol to use this command by setting devtoolsProtocol: true in the configuration`);
3732
- return;
3733
- }
3734
- if (!this.geoLocation) return 'No GeoLocation is set!';
3735
- return this.geoLocation;
3736
- }
3737
-
3738
- /**
3739
- * Grab the width, height, location of given locator.
3740
- * Provide `width` or `height`as second param to get your desired prop.
3741
- * Resumes test execution, so **should be used inside an async function with `await`** operator.
3742
- *
3743
- * Returns an object with `x`, `y`, `width`, `height` keys.
3744
- *
3745
- * ```js
3746
- * const value = await I.grabElementBoundingRect('h3');
3747
- * // value is like { x: 226.5, y: 89, width: 527, height: 220 }
3748
- * ```
3749
- *
3750
- * To get only one metric use second parameter:
3751
- *
3752
- * ```js
3753
- * const width = await I.grabElementBoundingRect('h3', 'width');
3754
- * // width == 527
3755
- * ```
3756
- * @param {LocatorOrString} locator element located by CSS|XPath|strict locator.
3757
- * @param {string=} elementSize x, y, width or height of the given element.
3758
- * @returns {Promise<DOMRect>|Promise<number>} Element bounding rectangle
3759
- *
3760
- */
3761
- async grabElementBoundingRect(locator, prop) {
3762
- const res = await this._locate(locator, true);
3763
- assertElementExists(res, locator);
3764
- const el = usingFirstElement(res);
3765
-
3766
- const rect = {
3767
- ...await el.getLocation(),
3768
- ...await el.getSize(),
3769
- };
3770
- if (prop) return rect[prop];
3771
- return rect;
3772
- }
3773
-
3774
- /**
3775
- * Placeholder for ~ locator only test case write once run on both Appium and WebDriver.
3776
- * @param {*} caps
3777
- * @param {*} fn
3778
- */
3779
- /* eslint-disable */
3780
- runOnIOS(caps, fn) {
3781
- }
3782
-
3783
- /**
3784
- * Placeholder for ~ locator only test case write once run on both Appium and WebDriver.
3785
- * @param {*} caps
3786
- * @param {*} fn
3787
- */
3788
- runOnAndroid(caps, fn) {
3789
- }
3790
- /* eslint-enable */
3791
-
3792
- /**
3793
- * Placeholder for ~ locator only test case write once run on both Appium and WebDriver.
3794
- */
3795
- runInWeb(fn) {
3796
- return fn();
3797
- }
3798
- }
3799
-
3800
- async function proceedSee(assertType, text, context, strict = false) {
3801
- let description;
3802
- if (!context) {
3803
- if (this.context === webRoot) {
3804
- context = this.context;
3805
- description = 'web page';
3806
- } else {
3807
- description = `current context ${this.context}`;
3808
- context = './/*';
3809
- }
3810
- } else {
3811
- description = `element ${context}`;
3812
- }
3813
-
3814
- const smartWaitEnabled = assertType === 'assert';
3815
- const res = await this._locate(withStrictLocator(context), smartWaitEnabled);
3816
- assertElementExists(res, context);
3817
- const selected = await forEachAsync(res, async el => this.browser.getElementText(getElementId(el)));
3818
- if (strict) {
3819
- if (Array.isArray(selected) && selected.length !== 0) {
3820
- return selected.map(elText => equals(description)[assertType](text, elText));
3821
- }
3822
- return equals(description)[assertType](text, selected);
3823
- }
3824
- return stringIncludes(description)[assertType](text, selected);
3825
- }
3826
-
3827
- /**
3828
- * Mimic Array.forEach() API, but with an async callback function.
3829
- * Execute each callback on each array item serially. Useful when using WebDriver API.
3830
- *
3831
- * Added due because of problem with chrome driver when too many requests
3832
- * are made simultaneously. https://bugs.chromium.org/p/chromedriver/issues/detail?id=2152#c9
3833
- * @private
3834
- * @param {Array} array Input array items to iterate over.
3835
- * @param {Function} callback - Async function to excute on each array item.
3836
- * @param {object} [options] - Configurable options.
3837
- * @param {boolean} [options.expandArrayResults=true] - Flag to flat one dimension array results.
3838
- * @return {Promise<Array>} - Array of values.
3839
- */
3840
- async function forEachAsync(array, callback, options = { expandArrayResults: true }) {
3841
- const {
3842
- expandArrayResults = true,
3843
- } = options;
3844
- const inputArray = Array.isArray(array) ? array : [array];
3845
- const values = [];
3846
- for (let index = 0; index < inputArray.length; index++) {
3847
- const res = await callback(inputArray[index], index, inputArray);
3848
-
3849
- if (Array.isArray(res) && expandArrayResults) {
3850
- res.forEach(val => values.push(val));
3851
- } else if (res) {
3852
- values.push(res);
3853
- }
3854
- }
3855
- return values;
3856
- }
3857
-
3858
- /**
3859
- * Mimic Array.filter() API, but with an async callback function.
3860
- * Execute each callback on each array item serially. Useful when using WebDriver API.
3861
- *
3862
- * Added due because of problem with chrome driver when too many requests
3863
- * are made simultaneously. https://bugs.chromium.org/p/chromedriver/issues/detail?id=2152#c9
3864
- * @private
3865
- * @param {Array} array - Input array items to iterate over.
3866
- * @param {Function} callback - Async functin to excute on each array item.
3867
- * @return {Promise<Array>} - Array of values.
3868
- */
3869
- async function filterAsync(array, callback) {
3870
- const inputArray = Array.isArray(array) ? array : [array];
3871
- const values = [];
3872
- for (let index = 0; index < inputArray.length; index++) {
3873
- const res = await callback(inputArray[index], index, inputArray);
3874
- const value = Array.isArray(res) ? res[0] : res;
3875
-
3876
- if (value) {
3877
- values.push(inputArray[index]);
3878
- }
3879
- }
3880
- return values;
3881
- }
3882
-
3883
- async function findClickable(locator, locateFn) {
3884
- locator = new Locator(locator);
3885
-
3886
- if (this._isCustomLocator(locator)) {
3887
- return locateFn(locator.value);
3888
- }
3889
-
3890
- if (locator.isAccessibilityId() && !this.isWeb) return locateFn(locator, true);
3891
- if (!locator.isFuzzy()) return locateFn(locator, true);
3892
-
3893
- let els;
3894
- const literal = xpathLocator.literal(locator.value);
3895
-
3896
- els = await locateFn(Locator.clickable.narrow(literal));
3897
- if (els.length) return els;
3898
-
3899
- els = await locateFn(Locator.clickable.wide(literal));
3900
- if (els.length) return els;
3901
-
3902
- els = await locateFn(Locator.clickable.self(literal));
3903
- if (els.length) return els;
3904
-
3905
- return locateFn(locator.value); // by css or xpath
3906
- }
3907
-
3908
- async function findFields(locator) {
3909
- locator = new Locator(locator);
3910
-
3911
- if (this._isCustomLocator(locator)) {
3912
- return this._locate(locator);
3913
- }
3914
-
3915
- if (locator.isAccessibilityId() && !this.isWeb) return this._locate(locator, true);
3916
- if (!locator.isFuzzy()) return this._locate(locator, true);
3917
-
3918
- const literal = xpathLocator.literal(locator.value);
3919
- let els = await this._locate(Locator.field.labelEquals(literal));
3920
- if (els.length) return els;
3921
-
3922
- els = await this._locate(Locator.field.labelContains(literal));
3923
- if (els.length) return els;
3924
-
3925
- els = await this._locate(Locator.field.byName(literal));
3926
- if (els.length) return els;
3927
- return this._locate(locator.value); // by css or xpath
3928
- }
3929
-
3930
- async function proceedSeeField(assertType, field, value) {
3931
- const res = await findFields.call(this, field);
3932
- assertElementExists(res, field, 'Field');
3933
- const elem = usingFirstElement(res);
3934
- const elemId = getElementId(elem);
3935
-
3936
- const proceedMultiple = async (fields) => {
3937
- const fieldResults = toArray(await forEachAsync(fields, async (el) => {
3938
- const elementId = getElementId(el);
3939
- return this.browser.isW3C ? el.getValue() : this.browser.getElementAttribute(elementId, 'value');
3940
- }));
3941
-
3942
- if (typeof value === 'boolean') {
3943
- equals(`no. of items matching > 0: ${field}`)[assertType](value, !!fieldResults.length);
3944
- } else {
3945
- // Assert that results were found so the forEach assert does not silently pass
3946
- equals(`no. of items matching > 0: ${field}`)[assertType](true, !!fieldResults.length);
3947
- fieldResults.forEach(val => stringIncludes(`fields by ${field}`)[assertType](value, val));
3948
- }
3949
- };
3950
-
3951
- const proceedSingle = el => el.getValue().then((res) => {
3952
- if (res === null) {
3953
- throw new Error(`Element ${el.selector} has no value attribute`);
3954
- }
3955
- stringIncludes(`fields by ${field}`)[assertType](value, res);
3956
- });
3957
-
3958
- const filterBySelected = async elements => filterAsync(elements, async el => this.browser.isElementSelected(getElementId(el)));
3959
-
3960
- const filterSelectedByValue = async (elements, value) => {
3961
- return filterAsync(elements, async (el) => {
3962
- const elementId = getElementId(el);
3963
- const currentValue = this.browser.isW3C ? await el.getValue() : await this.browser.getElementAttribute(elementId, 'value');
3964
- const isSelected = await this.browser.isElementSelected(elementId);
3965
- return currentValue === value && isSelected;
3966
- });
3967
- };
3968
-
3969
- const tag = await elem.getTagName();
3970
- if (tag === 'select') {
3971
- const subOptions = await this.browser.findElementsFromElement(elemId, 'css', 'option');
3972
-
3973
- if (value === '') {
3974
- // Don't filter by value
3975
- const selectedOptions = await filterBySelected(subOptions);
3976
- return proceedMultiple(selectedOptions);
3977
- }
3978
-
3979
- const options = await filterSelectedByValue(subOptions, value);
3980
- return proceedMultiple(options);
3981
- }
3982
-
3983
- if (tag === 'input') {
3984
- const fieldType = await elem.getAttribute('type');
3985
-
3986
- if (fieldType === 'checkbox' || fieldType === 'radio') {
3987
- if (typeof value === 'boolean') {
3988
- // Support boolean values
3989
- const options = await filterBySelected(res);
3990
- return proceedMultiple(options);
3991
- }
3992
-
3993
- const options = await filterSelectedByValue(res, value);
3994
- return proceedMultiple(options);
3995
- }
3996
- return proceedSingle(elem);
3997
- }
3998
- return proceedSingle(elem);
3999
- }
4000
-
4001
- function toArray(item) {
4002
- if (!Array.isArray(item)) {
4003
- return [item];
4004
- }
4005
- return item;
4006
- }
4007
-
4008
- async function proceedSeeCheckbox(assertType, field) {
4009
- const res = await findFields.call(this, field);
4010
- assertElementExists(res, field, 'Field');
4011
-
4012
- const selected = await forEachAsync(res, async el => this.browser.isElementSelected(getElementId(el)));
4013
- return truth(`checkable field "${field}"`, 'to be checked')[assertType](selected);
4014
- }
4015
-
4016
- async function findCheckable(locator, locateFn) {
4017
- let els;
4018
- locator = new Locator(locator);
4019
-
4020
- if (this._isCustomLocator(locator)) {
4021
- return locateFn(locator.value);
4022
- }
4023
-
4024
- if (locator.isAccessibilityId() && !this.isWeb) return locateFn(locator, true);
4025
- if (!locator.isFuzzy()) return locateFn(locator, true);
4026
-
4027
- const literal = xpathLocator.literal(locator.value);
4028
- els = await locateFn(Locator.checkable.byText(literal));
4029
- if (els.length) return els;
4030
- els = await locateFn(Locator.checkable.byName(literal));
4031
- if (els.length) return els;
4032
-
4033
- return locateFn(locator.value); // by css or xpath
4034
- }
4035
-
4036
- function withStrictLocator(locator) {
4037
- locator = new Locator(locator);
4038
- return locator.simplify();
4039
- }
4040
-
4041
- function isFrameLocator(locator) {
4042
- locator = new Locator(locator);
4043
- if (locator.isFrame()) return locator.value;
4044
- return false;
4045
- }
4046
-
4047
- function assertElementExists(res, locator, prefix, suffix) {
4048
- if (!res || res.length === 0) {
4049
- throw new ElementNotFound(locator, prefix, suffix);
4050
- }
4051
- }
4052
-
4053
- function usingFirstElement(els) {
4054
- if (els.length > 1) debug(`[Elements] Using first element out of ${els.length}`);
4055
- return els[0];
4056
- }
4057
-
4058
- function getElementId(el) {
4059
- // W3C WebDriver web element identifier
4060
- // https://w3c.github.io/webdriver/#dfn-web-element-identifier
4061
- if (el['element-6066-11e4-a52e-4f735466cecf']) {
4062
- return el['element-6066-11e4-a52e-4f735466cecf'];
4063
- }
4064
- // (deprecated) JsonWireProtocol identifier
4065
- // https://github.com/SeleniumHQ/selenium/wiki/JsonWireProtocol#webelement-json-object
4066
- if (el.ELEMENT) {
4067
- return el.ELEMENT;
4068
- }
4069
-
4070
- return null;
4071
- }
4072
-
4073
- // List of known key values to unicode code points
4074
- // https://www.w3.org/TR/webdriver/#keyboard-actions
4075
- const keyUnicodeMap = {
4076
- /* eslint-disable quote-props */
4077
- 'Unidentified': '\uE000',
4078
- 'Cancel': '\uE001',
4079
- 'Clear': '\uE005',
4080
- 'Help': '\uE002',
4081
- 'Pause': '\uE00B',
4082
- 'Backspace': '\uE003',
4083
- 'Return': '\uE006',
4084
- 'Enter': '\uE007',
4085
- 'Escape': '\uE00C',
4086
- 'Alt': '\uE00A',
4087
- 'AltLeft': '\uE00A',
4088
- 'AltRight': '\uE052',
4089
- 'Control': '\uE009',
4090
- 'ControlLeft': '\uE009',
4091
- 'ControlRight': '\uE051',
4092
- 'Meta': '\uE03D',
4093
- 'MetaLeft': '\uE03D',
4094
- 'MetaRight': '\uE053',
4095
- 'Shift': '\uE008',
4096
- 'ShiftLeft': '\uE008',
4097
- 'ShiftRight': '\uE050',
4098
- 'Space': '\uE00D',
4099
- ' ': '\uE00D',
4100
- 'Tab': '\uE004',
4101
- 'Insert': '\uE016',
4102
- 'Delete': '\uE017',
4103
- 'End': '\uE010',
4104
- 'Home': '\uE011',
4105
- 'PageUp': '\uE00E',
4106
- 'PageDown': '\uE00F',
4107
- 'ArrowDown': '\uE015',
4108
- 'ArrowLeft': '\uE012',
4109
- 'ArrowRight': '\uE014',
4110
- 'ArrowUp': '\uE013',
4111
- 'F1': '\uE031',
4112
- 'F2': '\uE032',
4113
- 'F3': '\uE033',
4114
- 'F4': '\uE034',
4115
- 'F5': '\uE035',
4116
- 'F6': '\uE036',
4117
- 'F7': '\uE037',
4118
- 'F8': '\uE038',
4119
- 'F9': '\uE039',
4120
- 'F10': '\uE03A',
4121
- 'F11': '\uE03B',
4122
- 'F12': '\uE03C',
4123
- 'Numpad0': '\uE01A',
4124
- 'Numpad1': '\uE01B',
4125
- 'Numpad2': '\uE01C',
4126
- 'Numpad3': '\uE01D',
4127
- 'Numpad4': '\uE01E',
4128
- 'Numpad5': '\uE01F',
4129
- 'Numpad6': '\uE020',
4130
- 'Numpad7': '\uE021',
4131
- 'Numpad8': '\uE022',
4132
- 'Numpad9': '\uE023',
4133
- 'NumpadMultiply': '\uE024',
4134
- 'NumpadAdd': '\uE025',
4135
- 'NumpadSubtract': '\uE027',
4136
- 'NumpadDecimal': '\uE028',
4137
- 'NumpadDivide': '\uE029',
4138
- 'NumpadEnter': '\uE007',
4139
- 'NumpadInsert': '\uE05C', // 'Numpad0' alternate (when NumLock off)
4140
- 'NumpadDelete': '\uE05D', // 'NumpadDecimal' alternate (when NumLock off)
4141
- 'NumpadEnd': '\uE056', // 'Numpad1' alternate (when NumLock off)
4142
- 'NumpadHome': '\uE057', // 'Numpad7' alternate (when NumLock off)
4143
- 'NumpadPageDown': '\uE055', // 'Numpad3' alternate (when NumLock off)
4144
- 'NumpadPageUp': '\uE054', // 'Numpad9' alternate (when NumLock off)
4145
- 'NumpadArrowDown': '\uE05B', // 'Numpad2' alternate (when NumLock off)
4146
- 'NumpadArrowLeft': '\uE058', // 'Numpad4' alternate (when NumLock off)
4147
- 'NumpadArrowRight': '\uE05A', // 'Numpad6' alternate (when NumLock off)
4148
- 'NumpadArrowUp': '\uE059', // 'Numpad8' alternate (when NumLock off)
4149
- 'Comma': '\uE026', // ',' alias
4150
- 'Digit0': '0', // '0' alias
4151
- 'Digit1': '1', // '1' alias
4152
- 'Digit2': '2', // '2' alias
4153
- 'Digit3': '3', // '3' alias
4154
- 'Digit4': '4', // '4' alias
4155
- 'Digit5': '5', // '5' alias
4156
- 'Digit6': '6', // '6' alias
4157
- 'Digit7': '7', // '7' alias
4158
- 'Digit8': '8', // '8' alias
4159
- 'Digit9': '9', // '9' alias
4160
- 'Equal': '\uE019', // '=' alias
4161
- 'KeyA': 'a', // 'a' alias
4162
- 'KeyB': 'b', // 'b' alias
4163
- 'KeyC': 'c', // 'c' alias
4164
- 'KeyD': 'd', // 'd' alias
4165
- 'KeyE': 'e', // 'e' alias
4166
- 'KeyF': 'f', // 'f' alias
4167
- 'KeyG': 'g', // 'g' alias
4168
- 'KeyH': 'h', // 'h' alias
4169
- 'KeyI': 'i', // 'i' alias
4170
- 'KeyJ': 'j', // 'j' alias
4171
- 'KeyK': 'k', // 'k' alias
4172
- 'KeyL': 'l', // 'l' alias
4173
- 'KeyM': 'm', // 'm' alias
4174
- 'KeyN': 'n', // 'n' alias
4175
- 'KeyO': 'o', // 'o' alias
4176
- 'KeyP': 'p', // 'p' alias
4177
- 'KeyQ': 'q', // 'q' alias
4178
- 'KeyR': 'r', // 'r' alias
4179
- 'KeyS': 's', // 's' alias
4180
- 'KeyT': 't', // 't' alias
4181
- 'KeyU': 'u', // 'u' alias
4182
- 'KeyV': 'v', // 'v' alias
4183
- 'KeyW': 'w', // 'w' alias
4184
- 'KeyX': 'x', // 'x' alias
4185
- 'KeyY': 'y', // 'y' alias
4186
- 'KeyZ': 'z', // 'z' alias
4187
- 'Period': '.', // '.' alias
4188
- 'Semicolon': '\uE018', // ';' alias
4189
- 'Slash': '/', // '/' alias
4190
- 'ZenkakuHankaku': '\uE040',
4191
- /* eslint-enable quote-props */
4192
- };
4193
-
4194
- function convertKeyToRawKey(key) {
4195
- if (Object.prototype.hasOwnProperty.call(keyUnicodeMap, key)) {
4196
- return keyUnicodeMap[key];
4197
- }
4198
- // Key is raw key when no representative unicode code point for value
4199
- return key;
4200
- }
4201
-
4202
- function getNormalizedKey(key) {
4203
- let normalizedKey = getNormalizedKeyAttributeValue(key);
4204
- // Always use "left" modifier keys for non-W3C sessions,
4205
- // as JsonWireProtocol does not support "right" modifier keys
4206
- if (!this.browser.isW3C) {
4207
- normalizedKey = normalizedKey.replace(/^(Alt|Control|Meta|Shift)Right$/, '$1');
4208
- }
4209
- if (key !== normalizedKey) {
4210
- this.debugSection('Input', `Mapping key '${key}' to '${normalizedKey}'`);
4211
- }
4212
- return convertKeyToRawKey(normalizedKey);
4213
- }
4214
-
4215
- const unicodeModifierKeys = modifierKeys.map(k => convertKeyToRawKey(k));
4216
- function isModifierKey(key) {
4217
- return unicodeModifierKeys.includes(key);
4218
- }
4219
-
4220
- function highlightActiveElement(element) {
4221
- if (this.options.highlightElement && global.debugMode) {
4222
- highlightElement(element, this.browser);
4223
- }
4224
- }
4225
-
4226
- function prepareLocateFn(context) {
4227
- if (!context) return this._locate.bind(this);
4228
- return (l) => {
4229
- l = new Locator(l, 'css');
4230
- return this._locate(context, true).then(async (res) => {
4231
- assertElementExists(res, context, 'Context element');
4232
- if (l.react) {
4233
- return res[0].react$$(l.react, l.props || undefined);
4234
- }
4235
- return res[0].$$(l.simplify());
4236
- });
4237
- };
4238
- }
4239
-
4240
- module.exports = WebDriver;