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