codeceptjs 3.5.10 → 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 (225) 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 +18 -2
  5. package/lib/helper/Expect.js +33 -33
  6. package/lib/helper/Playwright.js +49 -26
  7. package/lib/helper/Puppeteer.js +41 -19
  8. package/lib/helper/WebDriver.js +155 -48
  9. package/lib/helper/extras/PlaywrightReactVueLocator.js +38 -0
  10. package/lib/locator.js +17 -4
  11. package/lib/plugin/retryFailedStep.js +6 -2
  12. package/lib/plugin/retryTo.js +2 -2
  13. package/lib/plugin/tryTo.js +5 -4
  14. package/package.json +25 -22
  15. package/typings/index.d.ts +8 -5
  16. package/typings/promiseBasedTypes.d.ts +203 -75
  17. package/typings/types.d.ts +213 -145
  18. package/docs/advanced.md +0 -351
  19. package/docs/ai.md +0 -248
  20. package/docs/api.md +0 -323
  21. package/docs/basics.md +0 -979
  22. package/docs/bdd.md +0 -539
  23. package/docs/best.md +0 -237
  24. package/docs/books.md +0 -37
  25. package/docs/bootstrap.md +0 -135
  26. package/docs/build/ApiDataFactory.js +0 -410
  27. package/docs/build/Appium.js +0 -2027
  28. package/docs/build/Expect.js +0 -422
  29. package/docs/build/FileSystem.js +0 -228
  30. package/docs/build/GraphQL.js +0 -229
  31. package/docs/build/GraphQLDataFactory.js +0 -309
  32. package/docs/build/JSONResponse.js +0 -338
  33. package/docs/build/Mochawesome.js +0 -71
  34. package/docs/build/Nightmare.js +0 -2152
  35. package/docs/build/OpenAI.js +0 -126
  36. package/docs/build/Playwright.js +0 -5078
  37. package/docs/build/Protractor.js +0 -2706
  38. package/docs/build/Puppeteer.js +0 -3874
  39. package/docs/build/REST.js +0 -344
  40. package/docs/build/TestCafe.js +0 -2125
  41. package/docs/build/WebDriver.js +0 -4124
  42. package/docs/changelog.md +0 -2572
  43. package/docs/commands.md +0 -266
  44. package/docs/community-helpers.md +0 -58
  45. package/docs/configuration.md +0 -157
  46. package/docs/continuous-integration.md +0 -22
  47. package/docs/custom-helpers.md +0 -306
  48. package/docs/data.md +0 -379
  49. package/docs/detox.md +0 -235
  50. package/docs/docker.md +0 -136
  51. package/docs/email.md +0 -183
  52. package/docs/examples.md +0 -149
  53. package/docs/helpers/ApiDataFactory.md +0 -266
  54. package/docs/helpers/Appium.md +0 -1374
  55. package/docs/helpers/Detox.md +0 -586
  56. package/docs/helpers/Expect.md +0 -275
  57. package/docs/helpers/FileSystem.md +0 -152
  58. package/docs/helpers/GraphQL.md +0 -151
  59. package/docs/helpers/GraphQLDataFactory.md +0 -226
  60. package/docs/helpers/JSONResponse.md +0 -254
  61. package/docs/helpers/Mochawesome.md +0 -8
  62. package/docs/helpers/MockRequest.md +0 -377
  63. package/docs/helpers/Nightmare.md +0 -1305
  64. package/docs/helpers/OpenAI.md +0 -70
  65. package/docs/helpers/Playwright.md +0 -2706
  66. package/docs/helpers/Polly.md +0 -44
  67. package/docs/helpers/Protractor.md +0 -1769
  68. package/docs/helpers/Puppeteer-firefox.md +0 -86
  69. package/docs/helpers/Puppeteer.md +0 -2291
  70. package/docs/helpers/REST.md +0 -218
  71. package/docs/helpers/TestCafe.md +0 -1321
  72. package/docs/helpers/WebDriver.md +0 -2460
  73. package/docs/hooks.md +0 -340
  74. package/docs/index.md +0 -111
  75. package/docs/installation.md +0 -75
  76. package/docs/internal-api.md +0 -266
  77. package/docs/locators.md +0 -331
  78. package/docs/mobile-react-native-locators.md +0 -67
  79. package/docs/mobile.md +0 -338
  80. package/docs/pageobjects.md +0 -291
  81. package/docs/parallel.md +0 -400
  82. package/docs/playwright.md +0 -632
  83. package/docs/plugins.md +0 -1259
  84. package/docs/puppeteer.md +0 -316
  85. package/docs/quickstart.md +0 -162
  86. package/docs/react.md +0 -69
  87. package/docs/reports.md +0 -392
  88. package/docs/secrets.md +0 -36
  89. package/docs/shadow.md +0 -68
  90. package/docs/shared/keys.mustache +0 -31
  91. package/docs/shared/react.mustache +0 -1
  92. package/docs/testcafe.md +0 -174
  93. package/docs/translation.md +0 -247
  94. package/docs/tutorial.md +0 -271
  95. package/docs/typescript.md +0 -180
  96. package/docs/ui.md +0 -59
  97. package/docs/videos.md +0 -28
  98. package/docs/visual.md +0 -202
  99. package/docs/vue.md +0 -121
  100. package/docs/webapi/amOnPage.mustache +0 -11
  101. package/docs/webapi/appendField.mustache +0 -11
  102. package/docs/webapi/attachFile.mustache +0 -12
  103. package/docs/webapi/blur.mustache +0 -18
  104. package/docs/webapi/checkOption.mustache +0 -13
  105. package/docs/webapi/clearCookie.mustache +0 -9
  106. package/docs/webapi/clearField.mustache +0 -9
  107. package/docs/webapi/click.mustache +0 -25
  108. package/docs/webapi/clickLink.mustache +0 -8
  109. package/docs/webapi/closeCurrentTab.mustache +0 -7
  110. package/docs/webapi/closeOtherTabs.mustache +0 -8
  111. package/docs/webapi/dontSee.mustache +0 -11
  112. package/docs/webapi/dontSeeCheckboxIsChecked.mustache +0 -10
  113. package/docs/webapi/dontSeeCookie.mustache +0 -8
  114. package/docs/webapi/dontSeeCurrentUrlEquals.mustache +0 -10
  115. package/docs/webapi/dontSeeElement.mustache +0 -8
  116. package/docs/webapi/dontSeeElementInDOM.mustache +0 -8
  117. package/docs/webapi/dontSeeInCurrentUrl.mustache +0 -4
  118. package/docs/webapi/dontSeeInField.mustache +0 -11
  119. package/docs/webapi/dontSeeInSource.mustache +0 -8
  120. package/docs/webapi/dontSeeInTitle.mustache +0 -8
  121. package/docs/webapi/doubleClick.mustache +0 -13
  122. package/docs/webapi/downloadFile.mustache +0 -12
  123. package/docs/webapi/dragAndDrop.mustache +0 -9
  124. package/docs/webapi/dragSlider.mustache +0 -11
  125. package/docs/webapi/executeAsyncScript.mustache +0 -24
  126. package/docs/webapi/executeScript.mustache +0 -26
  127. package/docs/webapi/fillField.mustache +0 -16
  128. package/docs/webapi/focus.mustache +0 -13
  129. package/docs/webapi/forceClick.mustache +0 -28
  130. package/docs/webapi/forceRightClick.mustache +0 -18
  131. package/docs/webapi/grabAllWindowHandles.mustache +0 -7
  132. package/docs/webapi/grabAttributeFrom.mustache +0 -10
  133. package/docs/webapi/grabAttributeFromAll.mustache +0 -9
  134. package/docs/webapi/grabBrowserLogs.mustache +0 -9
  135. package/docs/webapi/grabCookie.mustache +0 -11
  136. package/docs/webapi/grabCssPropertyFrom.mustache +0 -11
  137. package/docs/webapi/grabCssPropertyFromAll.mustache +0 -10
  138. package/docs/webapi/grabCurrentUrl.mustache +0 -9
  139. package/docs/webapi/grabCurrentWindowHandle.mustache +0 -6
  140. package/docs/webapi/grabDataFromPerformanceTiming.mustache +0 -20
  141. package/docs/webapi/grabElementBoundingRect.mustache +0 -20
  142. package/docs/webapi/grabGeoLocation.mustache +0 -8
  143. package/docs/webapi/grabHTMLFrom.mustache +0 -10
  144. package/docs/webapi/grabHTMLFromAll.mustache +0 -9
  145. package/docs/webapi/grabNumberOfOpenTabs.mustache +0 -8
  146. package/docs/webapi/grabNumberOfVisibleElements.mustache +0 -9
  147. package/docs/webapi/grabPageScrollPosition.mustache +0 -8
  148. package/docs/webapi/grabPopupText.mustache +0 -5
  149. package/docs/webapi/grabSource.mustache +0 -8
  150. package/docs/webapi/grabTextFrom.mustache +0 -10
  151. package/docs/webapi/grabTextFromAll.mustache +0 -9
  152. package/docs/webapi/grabTitle.mustache +0 -8
  153. package/docs/webapi/grabValueFrom.mustache +0 -9
  154. package/docs/webapi/grabValueFromAll.mustache +0 -8
  155. package/docs/webapi/grabWebElement.mustache +0 -9
  156. package/docs/webapi/grabWebElements.mustache +0 -9
  157. package/docs/webapi/moveCursorTo.mustache +0 -12
  158. package/docs/webapi/openNewTab.mustache +0 -7
  159. package/docs/webapi/pressKey.mustache +0 -12
  160. package/docs/webapi/pressKeyDown.mustache +0 -12
  161. package/docs/webapi/pressKeyUp.mustache +0 -12
  162. package/docs/webapi/pressKeyWithKeyNormalization.mustache +0 -60
  163. package/docs/webapi/refreshPage.mustache +0 -6
  164. package/docs/webapi/resizeWindow.mustache +0 -6
  165. package/docs/webapi/rightClick.mustache +0 -14
  166. package/docs/webapi/saveElementScreenshot.mustache +0 -10
  167. package/docs/webapi/saveScreenshot.mustache +0 -12
  168. package/docs/webapi/say.mustache +0 -10
  169. package/docs/webapi/scrollIntoView.mustache +0 -11
  170. package/docs/webapi/scrollPageToBottom.mustache +0 -6
  171. package/docs/webapi/scrollPageToTop.mustache +0 -6
  172. package/docs/webapi/scrollTo.mustache +0 -12
  173. package/docs/webapi/see.mustache +0 -11
  174. package/docs/webapi/seeAttributesOnElements.mustache +0 -9
  175. package/docs/webapi/seeCheckboxIsChecked.mustache +0 -10
  176. package/docs/webapi/seeCookie.mustache +0 -8
  177. package/docs/webapi/seeCssPropertiesOnElements.mustache +0 -9
  178. package/docs/webapi/seeCurrentUrlEquals.mustache +0 -11
  179. package/docs/webapi/seeElement.mustache +0 -8
  180. package/docs/webapi/seeElementInDOM.mustache +0 -8
  181. package/docs/webapi/seeInCurrentUrl.mustache +0 -8
  182. package/docs/webapi/seeInField.mustache +0 -12
  183. package/docs/webapi/seeInPopup.mustache +0 -8
  184. package/docs/webapi/seeInSource.mustache +0 -7
  185. package/docs/webapi/seeInTitle.mustache +0 -8
  186. package/docs/webapi/seeNumberOfElements.mustache +0 -11
  187. package/docs/webapi/seeNumberOfVisibleElements.mustache +0 -10
  188. package/docs/webapi/seeTextEquals.mustache +0 -9
  189. package/docs/webapi/seeTitleEquals.mustache +0 -8
  190. package/docs/webapi/selectOption.mustache +0 -21
  191. package/docs/webapi/setCookie.mustache +0 -16
  192. package/docs/webapi/setGeoLocation.mustache +0 -12
  193. package/docs/webapi/switchTo.mustache +0 -9
  194. package/docs/webapi/switchToNextTab.mustache +0 -10
  195. package/docs/webapi/switchToPreviousTab.mustache +0 -10
  196. package/docs/webapi/type.mustache +0 -21
  197. package/docs/webapi/uncheckOption.mustache +0 -13
  198. package/docs/webapi/wait.mustache +0 -8
  199. package/docs/webapi/waitForClickable.mustache +0 -11
  200. package/docs/webapi/waitForDetached.mustache +0 -10
  201. package/docs/webapi/waitForElement.mustache +0 -11
  202. package/docs/webapi/waitForEnabled.mustache +0 -6
  203. package/docs/webapi/waitForFunction.mustache +0 -17
  204. package/docs/webapi/waitForInvisible.mustache +0 -10
  205. package/docs/webapi/waitForText.mustache +0 -13
  206. package/docs/webapi/waitForValue.mustache +0 -10
  207. package/docs/webapi/waitForVisible.mustache +0 -10
  208. package/docs/webapi/waitInUrl.mustache +0 -9
  209. package/docs/webapi/waitNumberOfVisibleElements.mustache +0 -10
  210. package/docs/webapi/waitToHide.mustache +0 -10
  211. package/docs/webapi/waitUrlEquals.mustache +0 -10
  212. package/docs/webdriver.md +0 -655
  213. package/docs/wiki/Books-&-Posts.md +0 -27
  214. package/docs/wiki/Community-Helpers-&-Plugins.md +0 -53
  215. package/docs/wiki/Converting-Playwright-to-Istanbul-Coverage.md +0 -61
  216. package/docs/wiki/Examples.md +0 -145
  217. package/docs/wiki/Google-Summer-of-Code-(GSoC)-2020.md +0 -68
  218. package/docs/wiki/Home.md +0 -16
  219. package/docs/wiki/Migration-to-Appium-v2---CodeceptJS.md +0 -83
  220. package/docs/wiki/Release-Process.md +0 -24
  221. package/docs/wiki/Roadmap.md +0 -23
  222. package/docs/wiki/Tests.md +0 -1393
  223. package/docs/wiki/Upgrading-to-CodeceptJS-3.md +0 -153
  224. package/docs/wiki/Videos.md +0 -19
  225. package/lib/helper/extras/PlaywrightReact.js +0 -9
@@ -1,4124 +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 {CodeceptJS.LocatorOrString} 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 {CodeceptJS.LocatorOrString} 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 {CodeceptJS.LocatorOrString} 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 {CodeceptJS.LocatorOrString} 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 {CodeceptJS.LocatorOrString} 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 {CodeceptJS.LocatorOrString} locator clickable link or button located by text, or any element located by CSS|XPath|strict locator.
960
- * @param {?CodeceptJS.LocatorOrString | 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 {CodeceptJS.LocatorOrString} locator clickable link or button located by text, or any element located by CSS|XPath|strict locator.
1008
- * @param {?CodeceptJS.LocatorOrString} [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 {CodeceptJS.LocatorOrString} locator clickable link or button located by text, or any element located by CSS|XPath|strict locator.
1048
- * @param {?CodeceptJS.LocatorOrString} [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 {CodeceptJS.LocatorOrString} locator clickable element located by CSS|XPath|strict locator.
1082
- * @param {?CodeceptJS.LocatorOrString} [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 {CodeceptJS.LocatorOrString} locator clickable link or button located by text, or any element located by CSS|XPath|strict locator.
1126
- * @param {?CodeceptJS.LocatorOrString} [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 {CodeceptJS.LocatorOrString} field located by label|name|CSS|XPath|strict locator.
1168
- * @param {CodeceptJS.StringOrSecret} 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 {CodeceptJS.LocatorOrString} 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 {LocatorOrString} 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 {LocatorOrString} 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
- * Attaches a file to element located by label, name, CSS or XPath
1283
- * Path to file is relative current codecept directory (where codecept.conf.ts or codecept.conf.js is located).
1284
- * File will be uploaded to remote system (if tests are running remotely).
1285
- *
1286
- * ```js
1287
- * I.attachFile('Avatar', 'data/avatar.jpg');
1288
- * I.attachFile('form input[name=avatar]', 'data/avatar.jpg');
1289
- * ```
1290
- *
1291
- * @param {CodeceptJS.LocatorOrString} locator field located by label|name|CSS|XPath|strict locator.
1292
- * @param {string} pathToFile local file path relative to codecept.conf.ts or codecept.conf.js config file.
1293
- * @returns {void} automatically synchronized promise through #recorder
1294
- *
1295
- * Appium: not tested
1296
- */
1297
- async attachFile(locator, pathToFile) {
1298
- let file = path.join(global.codecept_dir, pathToFile);
1299
- if (!fileExists(file)) {
1300
- throw new Error(`File at ${file} can not be found on local system`);
1301
- }
1302
-
1303
- const res = await findFields.call(this, locator);
1304
- this.debug(`Uploading ${file}`);
1305
- assertElementExists(res, locator, 'File field');
1306
- const el = usingFirstElement(res);
1307
-
1308
- // Remote Upload (when running Selenium Server)
1309
- if (this.options.remoteFileUpload) {
1310
- try {
1311
- this.debugSection('File', 'Uploading file to remote server');
1312
- file = await this.browser.uploadFile(file);
1313
- } catch (err) {
1314
- throw new Error(`File can't be transferred to remote server. Set \`remoteFileUpload: false\` in config to upload file locally.\n${err.message}`);
1315
- }
1316
- }
1317
-
1318
- return el.addValue(file);
1319
- }
1320
-
1321
- /**
1322
- * Selects a checkbox or radio button.
1323
- * Element is located by label or name or CSS or XPath.
1324
- *
1325
- * The second parameter is a context (CSS or XPath locator) to narrow the search.
1326
- *
1327
- * ```js
1328
- * I.checkOption('#agree');
1329
- * I.checkOption('I Agree to Terms and Conditions');
1330
- * I.checkOption('agree', '//form');
1331
- * ```
1332
- * @param {CodeceptJS.LocatorOrString} field checkbox located by label | name | CSS | XPath | strict locator.
1333
- * @param {?CodeceptJS.LocatorOrString} [context=null] (optional, `null` by default) element located by CSS | XPath | strict locator.
1334
- * @returns {void} automatically synchronized promise through #recorder
1335
- *
1336
- * Appium: not tested
1337
- */
1338
- async checkOption(field, context = null) {
1339
- const clickMethod = this.browser.isMobile && !this.browser.isW3C ? 'touchClick' : 'elementClick';
1340
- const locateFn = prepareLocateFn.call(this, context);
1341
-
1342
- const res = await findCheckable.call(this, field, locateFn);
1343
-
1344
- assertElementExists(res, field, 'Checkable');
1345
- const elem = usingFirstElement(res);
1346
- const elementId = getElementId(elem);
1347
- highlightActiveElement.call(this, elem);
1348
-
1349
- const isSelected = await this.browser.isElementSelected(elementId);
1350
- if (isSelected) return Promise.resolve(true);
1351
- return this.browser[clickMethod](elementId);
1352
- }
1353
-
1354
- /**
1355
- * Unselects a checkbox or radio button.
1356
- * Element is located by label or name or CSS or XPath.
1357
- *
1358
- * The second parameter is a context (CSS or XPath locator) to narrow the search.
1359
- *
1360
- * ```js
1361
- * I.uncheckOption('#agree');
1362
- * I.uncheckOption('I Agree to Terms and Conditions');
1363
- * I.uncheckOption('agree', '//form');
1364
- * ```
1365
- * @param {CodeceptJS.LocatorOrString} field checkbox located by label | name | CSS | XPath | strict locator.
1366
- * @param {?CodeceptJS.LocatorOrString} [context=null] (optional, `null` by default) element located by CSS | XPath | strict locator.
1367
- * @returns {void} automatically synchronized promise through #recorder
1368
- *
1369
- * Appium: not tested
1370
- */
1371
- async uncheckOption(field, context = null) {
1372
- const clickMethod = this.browser.isMobile && !this.browser.isW3C ? 'touchClick' : 'elementClick';
1373
- const locateFn = prepareLocateFn.call(this, context);
1374
-
1375
- const res = await findCheckable.call(this, field, locateFn);
1376
-
1377
- assertElementExists(res, field, 'Checkable');
1378
- const elem = usingFirstElement(res);
1379
- const elementId = getElementId(elem);
1380
- highlightActiveElement.call(this, elem);
1381
-
1382
- const isSelected = await this.browser.isElementSelected(elementId);
1383
- if (!isSelected) return Promise.resolve(true);
1384
- return this.browser[clickMethod](elementId);
1385
- }
1386
-
1387
- /**
1388
- * Retrieves all texts from an element located by CSS or XPath and returns it to test.
1389
- * Resumes test execution, so **should be used inside async with `await`** operator.
1390
- *
1391
- * ```js
1392
- * let pins = await I.grabTextFromAll('#pin li');
1393
- * ```
1394
- *
1395
- * @param {CodeceptJS.LocatorOrString} locator element located by CSS|XPath|strict locator.
1396
- * @returns {Promise<string[]>} attribute value
1397
- *
1398
- *
1399
- */
1400
- async grabTextFromAll(locator) {
1401
- const res = await this._locate(locator, true);
1402
- const val = await forEachAsync(res, el => this.browser.getElementText(getElementId(el)));
1403
- this.debugSection('GrabText', String(val));
1404
- return val;
1405
- }
1406
-
1407
- /**
1408
- * Retrieves a text from an element located by CSS or XPath and returns it to test.
1409
- * Resumes test execution, so **should be used inside async with `await`** operator.
1410
- *
1411
- * ```js
1412
- * let pin = await I.grabTextFrom('#pin');
1413
- * ```
1414
- * If multiple elements found returns first element.
1415
- *
1416
- * @param {CodeceptJS.LocatorOrString} locator element located by CSS|XPath|strict locator.
1417
- * @returns {Promise<string>} attribute value
1418
- *
1419
- *
1420
- */
1421
- async grabTextFrom(locator) {
1422
- const texts = await this.grabTextFromAll(locator);
1423
- assertElementExists(texts, locator);
1424
- if (texts.length > 1) {
1425
- this.debugSection('GrabText', `Using first element out of ${texts.length}`);
1426
- }
1427
-
1428
- return texts[0];
1429
- }
1430
-
1431
- /**
1432
- * Retrieves all the innerHTML from elements located by CSS or XPath and returns it to test.
1433
- * Resumes test execution, so **should be used inside async function with `await`** operator.
1434
- *
1435
- * ```js
1436
- * let postHTMLs = await I.grabHTMLFromAll('.post');
1437
- * ```
1438
- *
1439
- * @param {CodeceptJS.LocatorOrString} element located by CSS|XPath|strict locator.
1440
- * @returns {Promise<string[]>} HTML code for an element
1441
- *
1442
- *
1443
- */
1444
- async grabHTMLFromAll(locator) {
1445
- const elems = await this._locate(locator, true);
1446
- const html = await forEachAsync(elems, elem => elem.getHTML(false));
1447
- this.debugSection('GrabHTML', String(html));
1448
- return html;
1449
- }
1450
-
1451
- /**
1452
- * Retrieves the innerHTML from an element located by CSS or XPath and returns it to test.
1453
- * Resumes test execution, so **should be used inside async function with `await`** operator.
1454
- * If more than one element is found - HTML of first element is returned.
1455
- *
1456
- * ```js
1457
- * let postHTML = await I.grabHTMLFrom('#post');
1458
- * ```
1459
- *
1460
- * @param {CodeceptJS.LocatorOrString} element located by CSS|XPath|strict locator.
1461
- * @returns {Promise<string>} HTML code for an element
1462
- *
1463
- *
1464
- */
1465
- async grabHTMLFrom(locator) {
1466
- const html = await this.grabHTMLFromAll(locator);
1467
- assertElementExists(html, locator);
1468
- if (html.length > 1) {
1469
- this.debugSection('GrabHTML', `Using first element out of ${html.length}`);
1470
- }
1471
-
1472
- return html[0];
1473
- }
1474
-
1475
- /**
1476
- * Retrieves an array of value from a form located by CSS or XPath and returns it to test.
1477
- * Resumes test execution, so **should be used inside async function with `await`** operator.
1478
- *
1479
- * ```js
1480
- * let inputs = await I.grabValueFromAll('//form/input');
1481
- * ```
1482
- * @param {CodeceptJS.LocatorOrString} locator field located by label|name|CSS|XPath|strict locator.
1483
- * @returns {Promise<string[]>} attribute value
1484
- *
1485
- *
1486
- */
1487
- async grabValueFromAll(locator) {
1488
- const res = await this._locate(locator, true);
1489
- const val = await forEachAsync(res, el => el.getValue());
1490
- this.debugSection('GrabValue', String(val));
1491
-
1492
- return val;
1493
- }
1494
-
1495
- /**
1496
- * Retrieves a value from a form element located by CSS or XPath and returns it to test.
1497
- * Resumes test execution, so **should be used inside async function with `await`** operator.
1498
- * If more than one element is found - value of first element is returned.
1499
- *
1500
- * ```js
1501
- * let email = await I.grabValueFrom('input[name=email]');
1502
- * ```
1503
- * @param {CodeceptJS.LocatorOrString} locator field located by label|name|CSS|XPath|strict locator.
1504
- * @returns {Promise<string>} attribute value
1505
- *
1506
- *
1507
- */
1508
- async grabValueFrom(locator) {
1509
- const values = await this.grabValueFromAll(locator);
1510
- assertElementExists(values, locator);
1511
- if (values.length > 1) {
1512
- this.debugSection('GrabValue', `Using first element out of ${values.length}`);
1513
- }
1514
-
1515
- return values[0];
1516
- }
1517
-
1518
- /**
1519
- * Grab array of CSS properties for given locator
1520
- * Resumes test execution, so **should be used inside an async function with `await`** operator.
1521
- *
1522
- * ```js
1523
- * const values = await I.grabCssPropertyFromAll('h3', 'font-weight');
1524
- * ```
1525
- *
1526
- * @param {CodeceptJS.LocatorOrString} locator element located by CSS|XPath|strict locator.
1527
- * @param {string} cssProperty CSS property name.
1528
- * @returns {Promise<string[]>} CSS value
1529
- *
1530
- */
1531
- async grabCssPropertyFromAll(locator, cssProperty) {
1532
- const res = await this._locate(locator, true);
1533
- const val = await forEachAsync(res, async el => this.browser.getElementCSSValue(getElementId(el), cssProperty));
1534
- this.debugSection('Grab', String(val));
1535
- return val;
1536
- }
1537
-
1538
- /**
1539
- * Grab CSS property for given locator
1540
- * Resumes test execution, so **should be used inside an async function with `await`** operator.
1541
- * If more than one element is found - value of first element is returned.
1542
- *
1543
- * ```js
1544
- * const value = await I.grabCssPropertyFrom('h3', 'font-weight');
1545
- * ```
1546
- *
1547
- * @param {CodeceptJS.LocatorOrString} locator element located by CSS|XPath|strict locator.
1548
- * @param {string} cssProperty CSS property name.
1549
- * @returns {Promise<string>} CSS value
1550
- *
1551
- */
1552
- async grabCssPropertyFrom(locator, cssProperty) {
1553
- const cssValues = await this.grabCssPropertyFromAll(locator, cssProperty);
1554
- assertElementExists(cssValues, locator);
1555
-
1556
- if (cssValues.length > 1) {
1557
- this.debugSection('GrabCSS', `Using first element out of ${cssValues.length}`);
1558
- }
1559
-
1560
- return cssValues[0];
1561
- }
1562
-
1563
- /**
1564
- * Retrieves an array of attributes from elements located by CSS or XPath and returns it to test.
1565
- * Resumes test execution, so **should be used inside async with `await`** operator.
1566
- *
1567
- * ```js
1568
- * let hints = await I.grabAttributeFromAll('.tooltip', 'title');
1569
- * ```
1570
- * @param {CodeceptJS.LocatorOrString} locator element located by CSS|XPath|strict locator.
1571
- * @param {string} attr attribute name.
1572
- * @returns {Promise<string[]>} attribute value
1573
- *
1574
- */
1575
- async grabAttributeFromAll(locator, attr) {
1576
- const res = await this._locate(locator, true);
1577
- const val = await forEachAsync(res, async el => el.getAttribute(attr));
1578
- this.debugSection('GrabAttribute', String(val));
1579
- return val;
1580
- }
1581
-
1582
- /**
1583
- * Retrieves an attribute from an element located by CSS or XPath and returns it to test.
1584
- * Resumes test execution, so **should be used inside async with `await`** operator.
1585
- * If more than one element is found - attribute of first element is returned.
1586
- *
1587
- * ```js
1588
- * let hint = await I.grabAttributeFrom('#tooltip', 'title');
1589
- * ```
1590
- * @param {CodeceptJS.LocatorOrString} locator element located by CSS|XPath|strict locator.
1591
- * @param {string} attr attribute name.
1592
- * @returns {Promise<string>} attribute value
1593
- *
1594
- */
1595
- async grabAttributeFrom(locator, attr) {
1596
- const attrs = await this.grabAttributeFromAll(locator, attr);
1597
- assertElementExists(attrs, locator);
1598
- if (attrs.length > 1) {
1599
- this.debugSection('GrabAttribute', `Using first element out of ${attrs.length}`);
1600
- }
1601
- return attrs[0];
1602
- }
1603
-
1604
- /**
1605
- * Checks that title contains text.
1606
- *
1607
- * ```js
1608
- * I.seeInTitle('Home Page');
1609
- * ```
1610
- *
1611
- * @param {string} text text value to check.
1612
- * @returns {void} automatically synchronized promise through #recorder
1613
- *
1614
- */
1615
- async seeInTitle(text) {
1616
- const title = await this.browser.getTitle();
1617
- return stringIncludes('web page title').assert(text, title);
1618
- }
1619
-
1620
- /**
1621
- * Checks that title is equal to provided one.
1622
- *
1623
- * ```js
1624
- * I.seeTitleEquals('Test title.');
1625
- * ```
1626
- *
1627
- * @param {string} text value to check.
1628
- * @returns {void} automatically synchronized promise through #recorder
1629
- *
1630
- */
1631
- async seeTitleEquals(text) {
1632
- const title = await this.browser.getTitle();
1633
- return assert.equal(title, text, `expected web page title to be ${text}, but found ${title}`);
1634
- }
1635
-
1636
- /**
1637
- * Checks that title does not contain text.
1638
- *
1639
- * ```js
1640
- * I.dontSeeInTitle('Error');
1641
- * ```
1642
- *
1643
- * @param {string} text value to check.
1644
- * @returns {void} automatically synchronized promise through #recorder
1645
- *
1646
- */
1647
- async dontSeeInTitle(text) {
1648
- const title = await this.browser.getTitle();
1649
- return stringIncludes('web page title').negate(text, title);
1650
- }
1651
-
1652
- /**
1653
- * Retrieves a page title and returns it to test.
1654
- * Resumes test execution, so **should be used inside async with `await`** operator.
1655
- *
1656
- * ```js
1657
- * let title = await I.grabTitle();
1658
- * ```
1659
- *
1660
- * @returns {Promise<string>} title
1661
- */
1662
- async grabTitle() {
1663
- const title = await this.browser.getTitle();
1664
- this.debugSection('Title', title);
1665
- return title;
1666
- }
1667
-
1668
- /**
1669
- * Checks that a page contains a visible text.
1670
- * Use context parameter to narrow down the search.
1671
- *
1672
- * ```js
1673
- * I.see('Welcome'); // text welcome on a page
1674
- * I.see('Welcome', '.content'); // text inside .content div
1675
- * I.see('Register', {css: 'form.register'}); // use strict locator
1676
- * ```
1677
- * @param {string} text expected on page.
1678
- * @param {?CodeceptJS.LocatorOrString} [context=null] (optional, `null` by default) element located by CSS|Xpath|strict locator in which to search for text.
1679
- * @returns {void} automatically synchronized promise through #recorder
1680
- *
1681
- *
1682
- * {{ react }}
1683
- */
1684
- async see(text, context = null) {
1685
- return proceedSee.call(this, 'assert', text, context);
1686
- }
1687
-
1688
- /**
1689
- * Checks that text is equal to provided one.
1690
- *
1691
- * ```js
1692
- * I.seeTextEquals('text', 'h1');
1693
- * ```
1694
- *
1695
- * @param {string} text element value to check.
1696
- * @param {CodeceptJS.LocatorOrString?} [context=null] element located by CSS|XPath|strict locator.
1697
- * @returns {void} automatically synchronized promise through #recorder
1698
- *
1699
- */
1700
- async seeTextEquals(text, context = null) {
1701
- return proceedSee.call(this, 'assert', text, context, true);
1702
- }
1703
-
1704
- /**
1705
- * Opposite to `see`. Checks that a text is not present on a page.
1706
- * Use context parameter to narrow down the search.
1707
- *
1708
- * ```js
1709
- * I.dontSee('Login'); // assume we are already logged in.
1710
- * I.dontSee('Login', '.nav'); // no login inside .nav element
1711
- * ```
1712
- *
1713
- * @param {string} text which is not present.
1714
- * @param {CodeceptJS.LocatorOrString} [context] (optional) element located by CSS|XPath|strict locator in which to perfrom search.
1715
- * @returns {void} automatically synchronized promise through #recorder
1716
- *
1717
- *
1718
- * {{ react }}
1719
- */
1720
- async dontSee(text, context = null) {
1721
- return proceedSee.call(this, 'negate', text, context);
1722
- }
1723
-
1724
- /**
1725
- * Checks that the given input field or textarea equals to given value.
1726
- * For fuzzy locators, fields are matched by label text, the "name" attribute, CSS, and XPath.
1727
- *
1728
- * ```js
1729
- * I.seeInField('Username', 'davert');
1730
- * I.seeInField({css: 'form textarea'},'Type your comment here');
1731
- * I.seeInField('form input[type=hidden]','hidden_value');
1732
- * I.seeInField('#searchform input','Search');
1733
- * ```
1734
- * @param {CodeceptJS.LocatorOrString} field located by label|name|CSS|XPath|strict locator.
1735
- * @param {CodeceptJS.StringOrSecret} value value to check.
1736
- * @returns {void} automatically synchronized promise through #recorder
1737
- *
1738
- *
1739
- */
1740
- async seeInField(field, value) {
1741
- const _value = (typeof value === 'boolean') ? value : value.toString();
1742
- return proceedSeeField.call(this, 'assert', field, _value);
1743
- }
1744
-
1745
- /**
1746
- * Checks that value of input field or textarea doesn't equal to given value
1747
- * Opposite to `seeInField`.
1748
- *
1749
- * ```js
1750
- * I.dontSeeInField('email', 'user@user.com'); // field by name
1751
- * I.dontSeeInField({ css: 'form input.email' }, 'user@user.com'); // field by CSS
1752
- * ```
1753
- *
1754
- * @param {CodeceptJS.LocatorOrString} field located by label|name|CSS|XPath|strict locator.
1755
- * @param {CodeceptJS.StringOrSecret} value value to check.
1756
- * @returns {void} automatically synchronized promise through #recorder
1757
- *
1758
- *
1759
- */
1760
- async dontSeeInField(field, value) {
1761
- const _value = (typeof value === 'boolean') ? value : value.toString();
1762
- return proceedSeeField.call(this, 'negate', field, _value);
1763
- }
1764
-
1765
- /**
1766
- * Verifies that the specified checkbox is checked.
1767
- *
1768
- * ```js
1769
- * I.seeCheckboxIsChecked('Agree');
1770
- * I.seeCheckboxIsChecked('#agree'); // I suppose user agreed to terms
1771
- * I.seeCheckboxIsChecked({css: '#signup_form input[type=checkbox]'});
1772
- * ```
1773
- *
1774
- * @param {CodeceptJS.LocatorOrString} field located by label|name|CSS|XPath|strict locator.
1775
- * @returns {void} automatically synchronized promise through #recorder
1776
- *
1777
- * Appium: not tested
1778
- */
1779
- async seeCheckboxIsChecked(field) {
1780
- return proceedSeeCheckbox.call(this, 'assert', field);
1781
- }
1782
-
1783
- /**
1784
- * Verifies that the specified checkbox is not checked.
1785
- *
1786
- * ```js
1787
- * I.dontSeeCheckboxIsChecked('#agree'); // located by ID
1788
- * I.dontSeeCheckboxIsChecked('I agree to terms'); // located by label
1789
- * I.dontSeeCheckboxIsChecked('agree'); // located by name
1790
- * ```
1791
- *
1792
- * @param {CodeceptJS.LocatorOrString} field located by label|name|CSS|XPath|strict locator.
1793
- * @returns {void} automatically synchronized promise through #recorder
1794
- *
1795
- * Appium: not tested
1796
- */
1797
- async dontSeeCheckboxIsChecked(field) {
1798
- return proceedSeeCheckbox.call(this, 'negate', field);
1799
- }
1800
-
1801
- /**
1802
- * Checks that a given Element is visible
1803
- * Element is located by CSS or XPath.
1804
- *
1805
- * ```js
1806
- * I.seeElement('#modal');
1807
- * ```
1808
- * @param {CodeceptJS.LocatorOrString} locator located by CSS|XPath|strict locator.
1809
- * @returns {void} automatically synchronized promise through #recorder
1810
- *
1811
- * {{ react }}
1812
- *
1813
- */
1814
- async seeElement(locator) {
1815
- const res = await this._locate(locator, true);
1816
- assertElementExists(res, locator);
1817
- const selected = await forEachAsync(res, async el => el.isDisplayed());
1818
- return truth(`elements of ${(new Locator(locator))}`, 'to be seen').assert(selected);
1819
- }
1820
-
1821
- /**
1822
- * Opposite to `seeElement`. Checks that element is not visible (or in DOM)
1823
- *
1824
- * ```js
1825
- * I.dontSeeElement('.modal'); // modal is not shown
1826
- * ```
1827
- *
1828
- * @param {CodeceptJS.LocatorOrString} locator located by CSS|XPath|Strict locator.
1829
- * @returns {void} automatically synchronized promise through #recorder
1830
- *
1831
- * {{ react }}
1832
- */
1833
- async dontSeeElement(locator) {
1834
- const res = await this._locate(locator, false);
1835
- if (!res || res.length === 0) {
1836
- return truth(`elements of ${(new Locator(locator))}`, 'to be seen').negate(false);
1837
- }
1838
- const selected = await forEachAsync(res, async el => el.isDisplayed());
1839
- return truth(`elements of ${(new Locator(locator))}`, 'to be seen').negate(selected);
1840
- }
1841
-
1842
- /**
1843
- * Checks that a given Element is present in the DOM
1844
- * Element is located by CSS or XPath.
1845
- *
1846
- * ```js
1847
- * I.seeElementInDOM('#modal');
1848
- * ```
1849
- * @param {CodeceptJS.LocatorOrString} locator element located by CSS|XPath|strict locator.
1850
- * @returns {void} automatically synchronized promise through #recorder
1851
- *
1852
- *
1853
- */
1854
- async seeElementInDOM(locator) {
1855
- const res = await this._res(locator);
1856
- return empty('elements').negate(res);
1857
- }
1858
-
1859
- /**
1860
- * Opposite to `seeElementInDOM`. Checks that element is not on page.
1861
- *
1862
- * ```js
1863
- * I.dontSeeElementInDOM('.nav'); // checks that element is not on page visible or not
1864
- * ```
1865
- *
1866
- * @param {CodeceptJS.LocatorOrString} locator located by CSS|XPath|Strict locator.
1867
- * @returns {void} automatically synchronized promise through #recorder
1868
- *
1869
- *
1870
- */
1871
- async dontSeeElementInDOM(locator) {
1872
- const res = await this._res(locator);
1873
- return empty('elements').assert(res);
1874
- }
1875
-
1876
- /**
1877
- * Checks that the current page contains the given string in its raw source code.
1878
- *
1879
- * ```js
1880
- * I.seeInSource('<h1>Green eggs &amp; ham</h1>');
1881
- * ```
1882
- * @param {string} text value to check.
1883
- * @returns {void} automatically synchronized promise through #recorder
1884
- *
1885
- *
1886
- */
1887
- async seeInSource(text) {
1888
- const source = await this.browser.getPageSource();
1889
- return stringIncludes('HTML source of a page').assert(text, source);
1890
- }
1891
-
1892
- /**
1893
- * Retrieves page source and returns it to test.
1894
- * Resumes test execution, so **should be used inside async function with `await`** operator.
1895
- *
1896
- * ```js
1897
- * let pageSource = await I.grabSource();
1898
- * ```
1899
- *
1900
- * @returns {Promise<string>} source code
1901
- *
1902
- */
1903
- async grabSource() {
1904
- return this.browser.getPageSource();
1905
- }
1906
-
1907
- /**
1908
- * Get JS log from browser. Log buffer is reset after each request.
1909
- * Resumes test execution, so **should be used inside an async function with `await`** operator.
1910
- *
1911
- * ```js
1912
- * let logs = await I.grabBrowserLogs();
1913
- * console.log(JSON.stringify(logs))
1914
- * ```
1915
- *
1916
- * @returns {Promise<object[]>|undefined} all browser logs
1917
- *
1918
- */
1919
- async grabBrowserLogs() {
1920
- if (this.browser.isW3C) {
1921
- this.debug('Logs not available in W3C specification');
1922
- return;
1923
- }
1924
- return this.browser.getLogs('browser');
1925
- }
1926
-
1927
- /**
1928
- * Get current URL from browser.
1929
- * Resumes test execution, so should be used inside an async function.
1930
- *
1931
- * ```js
1932
- * let url = await I.grabCurrentUrl();
1933
- * console.log(`Current URL is [${url}]`);
1934
- * ```
1935
- *
1936
- * @returns {Promise<string>} current URL
1937
- */
1938
- async grabCurrentUrl() {
1939
- const res = await this.browser.getUrl();
1940
- this.debugSection('Url', res);
1941
- return res;
1942
- }
1943
-
1944
- /**
1945
- * Checks that the current page does not contains the given string in its raw source code.
1946
- *
1947
- * ```js
1948
- * I.dontSeeInSource('<!--'); // no comments in source
1949
- * ```
1950
- *
1951
- * @param {string} value to check.
1952
- * @returns {void} automatically synchronized promise through #recorder
1953
- *
1954
- */
1955
- async dontSeeInSource(text) {
1956
- const source = await this.browser.getPageSource();
1957
- return stringIncludes('HTML source of a page').negate(text, source);
1958
- }
1959
-
1960
- /**
1961
- * Asserts that an element appears a given number of times in the DOM.
1962
- * Element is located by label or name or CSS or XPath.
1963
- *
1964
- *
1965
- * ```js
1966
- * I.seeNumberOfElements('#submitBtn', 1);
1967
- * ```
1968
- *
1969
- * @param {CodeceptJS.LocatorOrString} locator element located by CSS|XPath|strict locator.
1970
- * @param {number} num number of elements.
1971
- * @returns {void} automatically synchronized promise through #recorder
1972
- *
1973
- * {{ react }}
1974
- */
1975
- async seeNumberOfElements(locator, num) {
1976
- const res = await this._locate(locator);
1977
- return assert.equal(res.length, num, `expected number of elements (${(new Locator(locator))}) is ${num}, but found ${res.length}`);
1978
- }
1979
-
1980
- /**
1981
- * Asserts that an element is visible a given number of times.
1982
- * Element is located by CSS or XPath.
1983
- *
1984
- * ```js
1985
- * I.seeNumberOfVisibleElements('.buttons', 3);
1986
- * ```
1987
- *
1988
- * @param {CodeceptJS.LocatorOrString} locator element located by CSS|XPath|strict locator.
1989
- * @param {number} num number of elements.
1990
- * @returns {void} automatically synchronized promise through #recorder
1991
- *
1992
- * {{ react }}
1993
- */
1994
- async seeNumberOfVisibleElements(locator, num) {
1995
- const res = await this.grabNumberOfVisibleElements(locator);
1996
- return assert.equal(res, num, `expected number of visible elements (${(new Locator(locator))}) is ${num}, but found ${res}`);
1997
- }
1998
-
1999
- /**
2000
- * Checks that all elements with given locator have given CSS properties.
2001
- *
2002
- * ```js
2003
- * I.seeCssPropertiesOnElements('h3', { 'font-weight': "bold"});
2004
- * ```
2005
- *
2006
- * @param {CodeceptJS.LocatorOrString} locator located by CSS|XPath|strict locator.
2007
- * @param {object} cssProperties object with CSS properties and their values to check.
2008
- * @returns {void} automatically synchronized promise through #recorder
2009
- *
2010
- */
2011
- async seeCssPropertiesOnElements(locator, cssProperties) {
2012
- const res = await this._locate(locator);
2013
- assertElementExists(res, locator);
2014
- const elemAmount = res.length;
2015
-
2016
- let props = await forEachAsync(res, async (el) => {
2017
- return forEachAsync(Object.keys(cssProperties), async (prop) => {
2018
- const propValue = await this.browser.getElementCSSValue(getElementId(el), prop);
2019
- if (isColorProperty(prop) && propValue && propValue.value) {
2020
- return convertColorToRGBA(propValue.value);
2021
- }
2022
- return propValue;
2023
- });
2024
- });
2025
-
2026
- const cssPropertiesCamelCase = convertCssPropertiesToCamelCase(cssProperties);
2027
-
2028
- const values = Object.keys(cssPropertiesCamelCase).map(key => cssPropertiesCamelCase[key]);
2029
- if (!Array.isArray(props)) props = [props];
2030
- let chunked = chunkArray(props, values.length);
2031
- chunked = chunked.filter((val) => {
2032
- for (let i = 0; i < val.length; ++i) {
2033
- const _acutal = Number.isNaN(val[i]) || (typeof values[i]) === 'string' ? val[i] : Number.parseInt(val[i], 10);
2034
- const _expected = Number.isNaN(values[i]) || (typeof values[i]) === 'string' ? values[i] : Number.parseInt(values[i], 10);
2035
- if (_acutal !== _expected) return false;
2036
- }
2037
- return true;
2038
- });
2039
- return assert.ok(
2040
- chunked.length === elemAmount,
2041
- `expected all elements (${(new Locator(locator))}) to have CSS property ${JSON.stringify(cssProperties)}`,
2042
- );
2043
- }
2044
-
2045
- /**
2046
- * Checks that all elements with given locator have given attributes.
2047
- *
2048
- * ```js
2049
- * I.seeAttributesOnElements('//form', { method: "post"});
2050
- * ```
2051
- *
2052
- * @param {CodeceptJS.LocatorOrString} locator located by CSS|XPath|strict locator.
2053
- * @param {object} attributes attributes and their values to check.
2054
- * @returns {void} automatically synchronized promise through #recorder
2055
- *
2056
- */
2057
- async seeAttributesOnElements(locator, attributes) {
2058
- const res = await this._locate(locator);
2059
- assertElementExists(res, locator);
2060
- const elemAmount = res.length;
2061
-
2062
- let attrs = await forEachAsync(res, async (el) => {
2063
- return forEachAsync(Object.keys(attributes), async attr => el.getAttribute(attr));
2064
- });
2065
-
2066
- const values = Object.keys(attributes).map(key => attributes[key]);
2067
- if (!Array.isArray(attrs)) attrs = [attrs];
2068
- let chunked = chunkArray(attrs, values.length);
2069
- chunked = chunked.filter((val) => {
2070
- for (let i = 0; i < val.length; ++i) {
2071
- const _acutal = Number.isNaN(val[i]) || (typeof values[i]) === 'string' ? val[i] : Number.parseInt(val[i], 10);
2072
- const _expected = Number.isNaN(values[i]) || (typeof values[i]) === 'string' ? values[i] : Number.parseInt(values[i], 10);
2073
- if (_acutal !== _expected) return false;
2074
- }
2075
- return true;
2076
- });
2077
- return assert.ok(
2078
- chunked.length === elemAmount,
2079
- `expected all elements (${(new Locator(locator))}) to have attributes ${JSON.stringify(attributes)}`,
2080
- );
2081
- }
2082
-
2083
- /**
2084
- * Grab number of visible elements by locator.
2085
- * Resumes test execution, so **should be used inside async function with `await`** operator.
2086
- *
2087
- * ```js
2088
- * let numOfElements = await I.grabNumberOfVisibleElements('p');
2089
- * ```
2090
- *
2091
- * @param {CodeceptJS.LocatorOrString} locator located by CSS|XPath|strict locator.
2092
- * @returns {Promise<number>} number of visible elements
2093
- */
2094
- async grabNumberOfVisibleElements(locator) {
2095
- const res = await this._locate(locator);
2096
-
2097
- let selected = await forEachAsync(res, async el => el.isDisplayed());
2098
- if (!Array.isArray(selected)) selected = [selected];
2099
- selected = selected.filter(val => val === true);
2100
- return selected.length;
2101
- }
2102
-
2103
- /**
2104
- * Checks that current url contains a provided fragment.
2105
- *
2106
- * ```js
2107
- * I.seeInCurrentUrl('/register'); // we are on registration page
2108
- * ```
2109
- *
2110
- * @param {string} url a fragment to check
2111
- * @returns {void} automatically synchronized promise through #recorder
2112
- *
2113
- *
2114
- */
2115
- async seeInCurrentUrl(url) {
2116
- const res = await this.browser.getUrl();
2117
- return stringIncludes('url').assert(url, decodeUrl(res));
2118
- }
2119
-
2120
- /**
2121
- * Checks that current url does not contain a provided fragment.
2122
- *
2123
- * @param {string} url value to check.
2124
- * @returns {void} automatically synchronized promise through #recorder
2125
- *
2126
- *
2127
- */
2128
- async dontSeeInCurrentUrl(url) {
2129
- const res = await this.browser.getUrl();
2130
- return stringIncludes('url').negate(url, decodeUrl(res));
2131
- }
2132
-
2133
- /**
2134
- * Checks that current url is equal to provided one.
2135
- * If a relative url provided, a configured url will be prepended to it.
2136
- * So both examples will work:
2137
- *
2138
- * ```js
2139
- * I.seeCurrentUrlEquals('/register');
2140
- * I.seeCurrentUrlEquals('http://my.site.com/register');
2141
- * ```
2142
- *
2143
- * @param {string} url value to check.
2144
- * @returns {void} automatically synchronized promise through #recorder
2145
- *
2146
- *
2147
- */
2148
- async seeCurrentUrlEquals(url) {
2149
- const res = await this.browser.getUrl();
2150
- return urlEquals(this.options.url).assert(url, decodeUrl(res));
2151
- }
2152
-
2153
- /**
2154
- * Checks that current url is not equal to provided one.
2155
- * If a relative url provided, a configured url will be prepended to it.
2156
- *
2157
- * ```js
2158
- * I.dontSeeCurrentUrlEquals('/login'); // relative url are ok
2159
- * I.dontSeeCurrentUrlEquals('http://mysite.com/login'); // absolute urls are also ok
2160
- * ```
2161
- *
2162
- * @param {string} url value to check.
2163
- * @returns {void} automatically synchronized promise through #recorder
2164
- *
2165
- *
2166
- */
2167
- async dontSeeCurrentUrlEquals(url) {
2168
- const res = await this.browser.getUrl();
2169
- return urlEquals(this.options.url).negate(url, decodeUrl(res));
2170
- }
2171
-
2172
- /**
2173
- * Executes sync script on a page.
2174
- * Pass arguments to function as additional parameters.
2175
- * Will return execution result to a test.
2176
- * In this case you should use async function and await to receive results.
2177
- *
2178
- * Example with jQuery DatePicker:
2179
- *
2180
- * ```js
2181
- * // change date of jQuery DatePicker
2182
- * I.executeScript(function() {
2183
- * // now we are inside browser context
2184
- * $('date').datetimepicker('setDate', new Date());
2185
- * });
2186
- * ```
2187
- * Can return values. Don't forget to use `await` to get them.
2188
- *
2189
- * ```js
2190
- * let date = await I.executeScript(function(el) {
2191
- * // only basic types can be returned
2192
- * return $(el).datetimepicker('getDate').toString();
2193
- * }, '#date'); // passing jquery selector
2194
- * ```
2195
- *
2196
- * @param {string|function} fn function to be executed in browser context.
2197
- * @param {...any} args to be passed to function.
2198
- * @returns {Promise<any>} script return value
2199
- *
2200
- *
2201
- *
2202
- * Wraps [execute](http://webdriver.io/api/protocol/execute.html) command.
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 {LocatorOrString} locator located by CSS|XPath|strict locator.
2250
- * @param {ScrollIntoViewOptions} 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 {CodeceptJS.LocatorOrString} 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 {CodeceptJS.LocatorOrString} 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 {CodeceptJS.LocatorOrString} 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
- * Sets cookie(s).
2406
- *
2407
- * Can be a single cookie object or an array of cookies:
2408
- *
2409
- * ```js
2410
- * I.setCookie({name: 'auth', value: true});
2411
- *
2412
- * // as array
2413
- * I.setCookie([
2414
- * {name: 'auth', value: true},
2415
- * {name: 'agree', value: true}
2416
- * ]);
2417
- * ```
2418
- *
2419
- * @param {Cookie|Array<Cookie>} cookie a cookie object or array of cookie objects.
2420
- * @returns {void} automatically synchronized promise through #recorder
2421
- *
2422
- *
2423
- *
2424
- * Uses Selenium's JSON [cookie
2425
- * format](https://code.google.com/p/selenium/wiki/JsonWireProtocol#Cookie_JSON_Object).
2426
- */
2427
- async setCookie(cookie) {
2428
- return this.browser.setCookies(cookie);
2429
- }
2430
-
2431
- /**
2432
- * Clears a cookie by name,
2433
- * if none provided clears all cookies.
2434
- *
2435
- * ```js
2436
- * I.clearCookie();
2437
- * I.clearCookie('test'); // Playwright currently doesn't support clear a particular cookie name
2438
- * ```
2439
- *
2440
- * @param {?string} [cookie=null] (optional, `null` by default) cookie name
2441
- *
2442
- */
2443
- async clearCookie(cookie) {
2444
- return this.browser.deleteCookies(cookie);
2445
- }
2446
-
2447
- /**
2448
- * Checks that cookie with given name exists.
2449
- *
2450
- * ```js
2451
- * I.seeCookie('Auth');
2452
- * ```
2453
- *
2454
- * @param {string} name cookie name.
2455
- * @returns {void} automatically synchronized promise through #recorder
2456
- *
2457
- */
2458
- async seeCookie(name) {
2459
- const cookie = await this.browser.getCookies([name]);
2460
- return truth(`cookie ${name}`, 'to be set').assert(cookie);
2461
- }
2462
-
2463
- /**
2464
- * Checks that cookie with given name does not exist.
2465
- *
2466
- * ```js
2467
- * I.dontSeeCookie('auth'); // no auth cookie
2468
- * ```
2469
- *
2470
- * @param {string} name cookie name.
2471
- * @returns {void} automatically synchronized promise through #recorder
2472
- *
2473
- */
2474
- async dontSeeCookie(name) {
2475
- const cookie = await this.browser.getCookies([name]);
2476
- return truth(`cookie ${name}`, 'to be set').negate(cookie);
2477
- }
2478
-
2479
- /**
2480
- * Gets a cookie object by name.
2481
- * If none provided gets all cookies.
2482
- * Resumes test execution, so **should be used inside async function with `await`** operator.
2483
- *
2484
- * ```js
2485
- * let cookie = await I.grabCookie('auth');
2486
- * assert(cookie.value, '123456');
2487
- * ```
2488
- *
2489
- * @param {?string} [name=null] cookie name.
2490
- * @returns {any} attribute value
2491
- *
2492
- */
2493
- async grabCookie(name) {
2494
- if (!name) return this.browser.getCookies();
2495
- const cookie = await this.browser.getCookies([name]);
2496
- this.debugSection('Cookie', JSON.stringify(cookie));
2497
- return cookie[0];
2498
- }
2499
-
2500
- /**
2501
- * Accepts the active JavaScript native popup window, as created by window.alert|window.confirm|window.prompt.
2502
- * Don't confuse popups with modal windows, as created by [various
2503
- * libraries](http://jster.net/category/windows-modals-popups).
2504
- */
2505
- async acceptPopup() {
2506
- return this.browser.getAlertText().then((res) => {
2507
- if (res !== null) {
2508
- return this.browser.acceptAlert();
2509
- }
2510
- });
2511
- }
2512
-
2513
- /**
2514
- * Dismisses the active JavaScript popup, as created by window.alert|window.confirm|window.prompt.
2515
- *
2516
- */
2517
- async cancelPopup() {
2518
- return this.browser.getAlertText().then((res) => {
2519
- if (res !== null) {
2520
- return this.browser.dismissAlert();
2521
- }
2522
- });
2523
- }
2524
-
2525
- /**
2526
- * Checks that the active JavaScript popup, as created by `window.alert|window.confirm|window.prompt`, contains the
2527
- * given string.
2528
- *
2529
- * @param {string} text value to check.
2530
- */
2531
- async seeInPopup(text) {
2532
- return this.browser.getAlertText().then((res) => {
2533
- if (res === null) {
2534
- throw new Error('Popup is not opened');
2535
- }
2536
- stringIncludes('text in popup').assert(text, res);
2537
- });
2538
- }
2539
-
2540
- /**
2541
- * Grab the text within the popup. If no popup is visible then it will return null.
2542
- * ```js
2543
- * await I.grabPopupText();
2544
- * ```
2545
- * @returns {Promise<string>}
2546
- *
2547
- */
2548
- async grabPopupText() {
2549
- try {
2550
- return await this.browser.getAlertText();
2551
- } catch (err) {
2552
- this.debugSection('Popup', 'Error getting text from popup');
2553
- }
2554
- }
2555
-
2556
- /**
2557
- * Presses a key in the browser and leaves it in a down state.
2558
- *
2559
- * To make combinations with modifier key and user operation (e.g. `'Control'` + [`click`](#click)).
2560
- *
2561
- * ```js
2562
- * I.pressKeyDown('Control');
2563
- * I.click('#element');
2564
- * I.pressKeyUp('Control');
2565
- * ```
2566
- *
2567
- * @param {string} key name of key to press down.
2568
- * @returns {void} automatically synchronized promise through #recorder
2569
- *
2570
- */
2571
- async pressKeyDown(key) {
2572
- key = getNormalizedKey.call(this, key);
2573
- if (!this.browser.isW3C) {
2574
- return this.browser.sendKeys([key]);
2575
- }
2576
- return this.browser.performActions([{
2577
- type: 'key',
2578
- id: 'keyboard',
2579
- actions: [{
2580
- type: 'keyDown',
2581
- value: key,
2582
- }],
2583
- }]);
2584
- }
2585
-
2586
- /**
2587
- * Releases a key in the browser which was previously set to a down state.
2588
- *
2589
- * To make combinations with modifier key and user operation (e.g. `'Control'` + [`click`](#click)).
2590
- *
2591
- * ```js
2592
- * I.pressKeyDown('Control');
2593
- * I.click('#element');
2594
- * I.pressKeyUp('Control');
2595
- * ```
2596
- *
2597
- * @param {string} key name of key to release.
2598
- * @returns {void} automatically synchronized promise through #recorder
2599
- *
2600
- */
2601
- async pressKeyUp(key) {
2602
- key = getNormalizedKey.call(this, key);
2603
- if (!this.browser.isW3C) {
2604
- return this.browser.sendKeys([key]);
2605
- }
2606
- return this.browser.performActions([{
2607
- type: 'key',
2608
- id: 'keyboard',
2609
- actions: [{
2610
- type: 'keyUp',
2611
- value: key,
2612
- }],
2613
- }]);
2614
- }
2615
-
2616
- /**
2617
- * Presses a key in the browser (on a focused element).
2618
- *
2619
- * _Hint:_ For populating text field or textarea, it is recommended to use [`fillField`](#fillfield).
2620
- *
2621
- * ```js
2622
- * I.pressKey('Backspace');
2623
- * ```
2624
- *
2625
- * 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.
2626
- *
2627
- * ```js
2628
- * I.pressKey(['Control', 'Z']);
2629
- * ```
2630
- *
2631
- * For specifying operation modifier key based on operating system it is suggested to use `'CommandOrControl'`.
2632
- * This will press `'Command'` (also known as `'Meta'`) on macOS machines and `'Control'` on non-macOS machines.
2633
- *
2634
- * ```js
2635
- * I.pressKey(['CommandOrControl', 'Z']);
2636
- * ```
2637
- *
2638
- * Some of the supported key names are:
2639
- * - `'AltLeft'` or `'Alt'`
2640
- * - `'AltRight'`
2641
- * - `'ArrowDown'`
2642
- * - `'ArrowLeft'`
2643
- * - `'ArrowRight'`
2644
- * - `'ArrowUp'`
2645
- * - `'Backspace'`
2646
- * - `'Clear'`
2647
- * - `'ControlLeft'` or `'Control'`
2648
- * - `'ControlRight'`
2649
- * - `'Command'`
2650
- * - `'CommandOrControl'`
2651
- * - `'Delete'`
2652
- * - `'End'`
2653
- * - `'Enter'`
2654
- * - `'Escape'`
2655
- * - `'F1'` to `'F12'`
2656
- * - `'Home'`
2657
- * - `'Insert'`
2658
- * - `'MetaLeft'` or `'Meta'`
2659
- * - `'MetaRight'`
2660
- * - `'Numpad0'` to `'Numpad9'`
2661
- * - `'NumpadAdd'`
2662
- * - `'NumpadDecimal'`
2663
- * - `'NumpadDivide'`
2664
- * - `'NumpadMultiply'`
2665
- * - `'NumpadSubtract'`
2666
- * - `'PageDown'`
2667
- * - `'PageUp'`
2668
- * - `'Pause'`
2669
- * - `'Return'`
2670
- * - `'ShiftLeft'` or `'Shift'`
2671
- * - `'ShiftRight'`
2672
- * - `'Space'`
2673
- * - `'Tab'`
2674
- *
2675
- * @param {string|string[]} key key or array of keys to press.
2676
- * @returns {void} automatically synchronized promise through #recorder
2677
- *
2678
- *
2679
- * _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.
2680
- */
2681
- async pressKey(key) {
2682
- const modifiers = [];
2683
- if (Array.isArray(key)) {
2684
- for (let k of key) {
2685
- k = getNormalizedKey.call(this, k);
2686
- if (isModifierKey(k)) {
2687
- modifiers.push(k);
2688
- } else {
2689
- key = k;
2690
- break;
2691
- }
2692
- }
2693
- } else {
2694
- key = getNormalizedKey.call(this, key);
2695
- }
2696
- for (const modifier of modifiers) {
2697
- await this.pressKeyDown(modifier);
2698
- }
2699
- if (!this.browser.isW3C) {
2700
- await this.browser.sendKeys([key]);
2701
- } else {
2702
- await this.browser.performActions([{
2703
- type: 'key',
2704
- id: 'keyboard',
2705
- actions: [{
2706
- type: 'keyDown',
2707
- value: key,
2708
- }, {
2709
- type: 'keyUp',
2710
- value: key,
2711
- }],
2712
- }]);
2713
- }
2714
- for (const modifier of modifiers) {
2715
- await this.pressKeyUp(modifier);
2716
- }
2717
- }
2718
-
2719
- /**
2720
- * Types out the given text into an active field.
2721
- * To slow down typing use a second parameter, to set interval between key presses.
2722
- * _Note:_ Should be used when [`fillField`](#fillfield) is not an option.
2723
- *
2724
- * ```js
2725
- * // passing in a string
2726
- * I.type('Type this out.');
2727
- *
2728
- * // typing values with a 100ms interval
2729
- * I.type('4141555311111111', 100);
2730
- *
2731
- * // passing in an array
2732
- * I.type(['T', 'E', 'X', 'T']);
2733
- *
2734
- * // passing a secret
2735
- * I.type(secret('123456'));
2736
- * ```
2737
- *
2738
- * @param {string|string[]} key or array of keys to type.
2739
- * @param {?number} [delay=null] (optional) delay in ms between key presses
2740
- * @returns {void} automatically synchronized promise through #recorder
2741
- *
2742
- */
2743
- async type(keys, delay = null) {
2744
- if (!Array.isArray(keys)) {
2745
- keys = keys.toString();
2746
- keys = keys.split('');
2747
- }
2748
- if (delay) {
2749
- for (const key of keys) {
2750
- await this.browser.keys(key);
2751
- await this.wait(delay / 1000);
2752
- }
2753
- return;
2754
- }
2755
- await this.browser.keys(keys);
2756
- }
2757
-
2758
- /**
2759
- * Resize the current window to provided width and height.
2760
- * First parameter can be set to `maximize`.
2761
- *
2762
- * @param {number} width width in pixels or `maximize`.
2763
- * @param {number} height height in pixels.
2764
- * @returns {void} automatically synchronized promise through #recorder
2765
- *
2766
- * Appium: not tested in web, in apps doesn't work
2767
- */
2768
- async resizeWindow(width, height) {
2769
- return this._resizeBrowserWindow(this.browser, width, height);
2770
- }
2771
-
2772
- async _resizeBrowserWindow(browser, width, height) {
2773
- if (width === 'maximize') {
2774
- const size = await browser.maximizeWindow();
2775
- this.debugSection('Window Size', size);
2776
- return;
2777
- }
2778
- if (browser.isW3C) {
2779
- return browser.setWindowRect(null, null, parseInt(width, 10), parseInt(height, 10));
2780
- }
2781
- return browser.setWindowSize(parseInt(width, 10), parseInt(height, 10));
2782
- }
2783
-
2784
- async _resizeWindowIfNeeded(browser, windowSize) {
2785
- if (this.isWeb && windowSize === 'maximize') {
2786
- await this._resizeBrowserWindow(browser, 'maximize');
2787
- } else if (this.isWeb && windowSize && windowSize.indexOf('x') > 0) {
2788
- const dimensions = windowSize.split('x');
2789
- await this._resizeBrowserWindow(browser, dimensions[0], dimensions[1]);
2790
- }
2791
- }
2792
-
2793
- /**
2794
- * Calls [focus](https://developer.mozilla.org/en-US/docs/Web/API/HTMLElement/focus) on the matching element.
2795
- *
2796
- * Examples:
2797
- *
2798
- * ```js
2799
- * I.dontSee('#add-to-cart-btn');
2800
- * I.focus('#product-tile')
2801
- * I.see('#add-to-cart-bnt');
2802
- * ```
2803
- *
2804
- * @param {CodeceptJS.LocatorOrString} locator field located by label|name|CSS|XPath|strict locator.
2805
- * @param {any} [options] Playwright only: [Additional options](https://playwright.dev/docs/api/class-locator#locator-focus) for available options object as 2nd argument.
2806
- * @returns {void} automatically synchronized promise through #recorder
2807
- *
2808
- *
2809
- */
2810
- async focus(locator) {
2811
- const els = await this._locate(locator);
2812
- assertElementExists(els, locator, 'Element to focus');
2813
- const el = usingFirstElement(els);
2814
-
2815
- await focusElement(el, this.browser);
2816
- }
2817
-
2818
- /**
2819
- * Remove focus from a text input, button, etc.
2820
- * Calls [blur](https://developer.mozilla.org/en-US/docs/Web/API/HTMLElement/focus) on the element.
2821
- *
2822
- * Examples:
2823
- *
2824
- * ```js
2825
- * I.blur('.text-area')
2826
- * ```
2827
- * ```js
2828
- * //element `#product-tile` is focused
2829
- * I.see('#add-to-cart-btn');
2830
- * I.blur('#product-tile')
2831
- * I.dontSee('#add-to-cart-btn');
2832
- * ```
2833
- *
2834
- * @param {CodeceptJS.LocatorOrString} locator field located by label|name|CSS|XPath|strict locator.
2835
- * @param {any} [options] Playwright only: [Additional options](https://playwright.dev/docs/api/class-locator#locator-blur) for available options object as 2nd argument.
2836
- * @returns {void} automatically synchronized promise through #recorder
2837
- *
2838
- *
2839
- */
2840
- async blur(locator) {
2841
- const els = await this._locate(locator);
2842
- assertElementExists(els, locator, 'Element to blur');
2843
- const el = usingFirstElement(els);
2844
-
2845
- await blurElement(el, this.browser);
2846
- }
2847
-
2848
- /**
2849
- * Drag an item to a destination element.
2850
- *
2851
- * ```js
2852
- * I.dragAndDrop('#dragHandle', '#container');
2853
- * ```
2854
- *
2855
- * @param {LocatorOrString} srcElement located by CSS|XPath|strict locator.
2856
- * @param {LocatorOrString} destElement located by CSS|XPath|strict locator.
2857
- * @returns {void} automatically synchronized promise through #recorder
2858
- *
2859
- * Appium: not tested
2860
- */
2861
- async dragAndDrop(srcElement, destElement) {
2862
- let sourceEl = await this._locate(srcElement);
2863
- assertElementExists(sourceEl, srcElement);
2864
- sourceEl = usingFirstElement(sourceEl);
2865
-
2866
- let destEl = await this._locate(destElement);
2867
- assertElementExists(destEl, destElement);
2868
- destEl = usingFirstElement(destEl);
2869
-
2870
- return sourceEl.dragAndDrop(destEl);
2871
- }
2872
-
2873
- /**
2874
- * Drag the scrubber of a slider to a given position
2875
- * For fuzzy locators, fields are matched by label text, the "name" attribute, CSS, and XPath.
2876
- *
2877
- * ```js
2878
- * I.dragSlider('#slider', 30);
2879
- * I.dragSlider('#slider', -70);
2880
- * ```
2881
- *
2882
- * @param {CodeceptJS.LocatorOrString} locator located by label|name|CSS|XPath|strict locator.
2883
- * @param {number} offsetX position to drag.
2884
- * @returns {void} automatically synchronized promise through #recorder
2885
- *
2886
- */
2887
- async dragSlider(locator, offsetX = 0) {
2888
- const browser = this.browser;
2889
- await this.moveCursorTo(locator);
2890
-
2891
- // for chrome
2892
- if (browser.isW3C) {
2893
- const xOffset = await this.grabElementBoundingRect(locator, 'x');
2894
- const yOffset = await this.grabElementBoundingRect(locator, 'y');
2895
-
2896
- return browser.performActions([{
2897
- type: 'pointer',
2898
- id: 'pointer1',
2899
- parameters: { pointerType: 'mouse' },
2900
- actions: [
2901
- {
2902
- type: 'pointerMove', origin: 'pointer', duration: 1000, x: xOffset, y: yOffset,
2903
- },
2904
- { type: 'pointerDown', button: 0 },
2905
- {
2906
- type: 'pointerMove', origin: 'pointer', duration: 1000, x: offsetX, y: 0,
2907
- },
2908
- { type: 'pointerUp', button: 0 },
2909
- ],
2910
- },
2911
- ]);
2912
- }
2913
-
2914
- await browser.buttonDown(0);
2915
- await browser.moveToElement(null, offsetX, 0);
2916
- await browser.buttonUp(0);
2917
- }
2918
-
2919
- /**
2920
- * Get all Window Handles.
2921
- * Useful for referencing a specific handle when calling `I.switchToWindow(handle)`
2922
- *
2923
- * ```js
2924
- * const windows = await I.grabAllWindowHandles();
2925
- * ```
2926
- * @returns {Promise<string[]>}
2927
- *
2928
- */
2929
- async grabAllWindowHandles() {
2930
- return this.browser.getWindowHandles();
2931
- }
2932
-
2933
- /**
2934
- * Get the current Window Handle.
2935
- * Useful for referencing it when calling `I.switchToWindow(handle)`
2936
- * ```js
2937
- * const window = await I.grabCurrentWindowHandle();
2938
- * ```
2939
- * @returns {Promise<string>}
2940
- *
2941
- */
2942
- async grabCurrentWindowHandle() {
2943
- return this.browser.getWindowHandle();
2944
- }
2945
-
2946
- /**
2947
- * Switch to the window with a specified handle.
2948
- *
2949
- * ```js
2950
- * const windows = await I.grabAllWindowHandles();
2951
- * // ... do something
2952
- * await I.switchToWindow( windows[0] );
2953
- *
2954
- * const window = await I.grabCurrentWindowHandle();
2955
- * // ... do something
2956
- * await I.switchToWindow( window );
2957
- * ```
2958
- * @param {string} window name of window handle.
2959
- */
2960
- async switchToWindow(window) {
2961
- await this.browser.switchToWindow(window);
2962
- }
2963
-
2964
- /**
2965
- * Close all tabs except for the current one.
2966
- *
2967
- *
2968
- * ```js
2969
- * I.closeOtherTabs();
2970
- * ```
2971
- *
2972
- * @returns {void} automatically synchronized promise through #recorder
2973
- *
2974
- */
2975
- async closeOtherTabs() {
2976
- const handles = await this.browser.getWindowHandles();
2977
- const currentHandle = await this.browser.getWindowHandle();
2978
- const otherHandles = handles.filter(handle => handle !== currentHandle);
2979
-
2980
- await forEachAsync(otherHandles, async (handle) => {
2981
- await this.browser.switchToWindow(handle);
2982
- await this.browser.closeWindow();
2983
- });
2984
- await this.browser.switchToWindow(currentHandle);
2985
- }
2986
-
2987
- /**
2988
- * Pauses execution for a number of seconds.
2989
- *
2990
- * ```js
2991
- * I.wait(2); // wait 2 secs
2992
- * ```
2993
- *
2994
- * @param {number} sec number of second to wait.
2995
- * @returns {void} automatically synchronized promise through #recorder
2996
- *
2997
- */
2998
- async wait(sec) {
2999
- return new Promise(resolve => {
3000
- setTimeout(resolve, sec * 1000);
3001
- });
3002
- }
3003
-
3004
- /**
3005
- * Waits for element to become enabled (by default waits for 1sec).
3006
- * Element can be located by CSS or XPath.
3007
- *
3008
- * @param {CodeceptJS.LocatorOrString} locator element located by CSS|XPath|strict locator.
3009
- * @param {number} [sec=1] (optional) time in seconds to wait, 1 by default.
3010
- * @returns {void} automatically synchronized promise through #recorder
3011
- *
3012
- */
3013
- async waitForEnabled(locator, sec = null) {
3014
- const aSec = sec || this.options.waitForTimeoutInSeconds;
3015
-
3016
- return this.browser.waitUntil(async () => {
3017
- const res = await this._res(locator);
3018
- if (!res || res.length === 0) {
3019
- return false;
3020
- }
3021
- const selected = await forEachAsync(res, async el => this.browser.isElementEnabled(getElementId(el)));
3022
- if (Array.isArray(selected)) {
3023
- return selected.filter(val => val === true).length > 0;
3024
- }
3025
- return selected;
3026
- }, {
3027
- timeout: aSec * 1000,
3028
- timeoutMsg: `element (${new Locator(locator)}) still not enabled after ${aSec} sec`,
3029
- });
3030
- }
3031
-
3032
- /**
3033
- * Waits for element to be present on page (by default waits for 1sec).
3034
- * Element can be located by CSS or XPath.
3035
- *
3036
- * ```js
3037
- * I.waitForElement('.btn.continue');
3038
- * I.waitForElement('.btn.continue', 5); // wait for 5 secs
3039
- * ```
3040
- *
3041
- * @param {CodeceptJS.LocatorOrString} locator element located by CSS|XPath|strict locator.
3042
- * @param {number} [sec] (optional, `1` by default) time in seconds to wait
3043
- * @returns {void} automatically synchronized promise through #recorder
3044
- *
3045
- */
3046
- async waitForElement(locator, sec = null) {
3047
- const aSec = sec || this.options.waitForTimeoutInSeconds;
3048
-
3049
- return this.browser.waitUntil(async () => {
3050
- const res = await this._res(locator);
3051
- return res && res.length;
3052
- }, { timeout: aSec * 1000, timeoutMsg: `element (${(new Locator(locator))}) still not present on page after ${aSec} sec` });
3053
- }
3054
-
3055
- /**
3056
- * Waits for element to be clickable (by default waits for 1sec).
3057
- * Element can be located by CSS or XPath.
3058
- *
3059
- * ```js
3060
- * I.waitForClickable('.btn.continue');
3061
- * I.waitForClickable('.btn.continue', 5); // wait for 5 secs
3062
- * ```
3063
- *
3064
- * @param {CodeceptJS.LocatorOrString} locator element located by CSS|XPath|strict locator.
3065
- * @param {number} [sec] (optional, `1` by default) time in seconds to wait
3066
- * @returns {void} automatically synchronized promise through #recorder
3067
- *
3068
- */
3069
- async waitForClickable(locator, waitTimeout) {
3070
- waitTimeout = waitTimeout || this.options.waitForTimeoutInSeconds;
3071
- let res = await this._locate(locator);
3072
- res = usingFirstElement(res);
3073
- assertElementExists(res, locator);
3074
-
3075
- return res.waitForClickable({
3076
- timeout: waitTimeout * 1000,
3077
- timeoutMsg: `element ${res.selector} still not clickable after ${waitTimeout} sec`,
3078
- });
3079
- }
3080
-
3081
- /**
3082
- * Waiting for the part of the URL to match the expected. Useful for SPA to understand that page was changed.
3083
- *
3084
- * ```js
3085
- * I.waitInUrl('/info', 2);
3086
- * ```
3087
- *
3088
- * @param {string} urlPart value to check.
3089
- * @param {number} [sec=1] (optional, `1` by default) time in seconds to wait
3090
- * @returns {void} automatically synchronized promise through #recorder
3091
- *
3092
- */
3093
- async waitInUrl(urlPart, sec = null) {
3094
- const client = this.browser;
3095
- const aSec = sec || this.options.waitForTimeoutInSeconds;
3096
- let currUrl = '';
3097
-
3098
- return client
3099
- .waitUntil(function () {
3100
- return this.getUrl().then((res) => {
3101
- currUrl = decodeUrl(res);
3102
- return currUrl.indexOf(urlPart) > -1;
3103
- });
3104
- }, { timeout: aSec * 1000 }).catch((e) => {
3105
- if (e.message.indexOf('timeout')) {
3106
- throw new Error(`expected url to include ${urlPart}, but found ${currUrl}`);
3107
- }
3108
- throw e;
3109
- });
3110
- }
3111
-
3112
- /**
3113
- * Waits for the entire URL to match the expected
3114
- *
3115
- * ```js
3116
- * I.waitUrlEquals('/info', 2);
3117
- * I.waitUrlEquals('http://127.0.0.1:8000/info');
3118
- * ```
3119
- *
3120
- * @param {string} urlPart value to check.
3121
- * @param {number} [sec=1] (optional, `1` by default) time in seconds to wait
3122
- * @returns {void} automatically synchronized promise through #recorder
3123
- *
3124
- */
3125
- async waitUrlEquals(urlPart, sec = null) {
3126
- const aSec = sec || this.options.waitForTimeoutInSeconds;
3127
- const baseUrl = this.options.url;
3128
- if (urlPart.indexOf('http') < 0) {
3129
- urlPart = baseUrl + urlPart;
3130
- }
3131
- let currUrl = '';
3132
- return this.browser.waitUntil(function () {
3133
- return this.getUrl().then((res) => {
3134
- currUrl = decodeUrl(res);
3135
- return currUrl === urlPart;
3136
- });
3137
- }, aSec * 1000).catch((e) => {
3138
- if (e.message.indexOf('timeout')) {
3139
- throw new Error(`expected url to be ${urlPart}, but found ${currUrl}`);
3140
- }
3141
- throw e;
3142
- });
3143
- }
3144
-
3145
- /**
3146
- * Waits for a text to appear (by default waits for 1sec).
3147
- * Element can be located by CSS or XPath.
3148
- * Narrow down search results by providing context.
3149
- *
3150
- * ```js
3151
- * I.waitForText('Thank you, form has been submitted');
3152
- * I.waitForText('Thank you, form has been submitted', 5, '#modal');
3153
- * ```
3154
- *
3155
- * @param {string }text to wait for.
3156
- * @param {number} [sec=1] (optional, `1` by default) time in seconds to wait
3157
- * @param {CodeceptJS.LocatorOrString} [context] (optional) element located by CSS|XPath|strict locator.
3158
- * @returns {void} automatically synchronized promise through #recorder
3159
- *
3160
- *
3161
- */
3162
- async waitForText(text, sec = null, context = null) {
3163
- const aSec = sec || this.options.waitForTimeoutInSeconds;
3164
- const _context = context || this.root;
3165
-
3166
- return this.browser.waitUntil(async () => {
3167
- const res = await this.$$(withStrictLocator.call(this, _context));
3168
- if (!res || res.length === 0) return false;
3169
- const selected = await forEachAsync(res, async el => this.browser.getElementText(getElementId(el)));
3170
- if (Array.isArray(selected)) {
3171
- return selected.filter(part => part.indexOf(text) >= 0).length > 0;
3172
- }
3173
- return selected.indexOf(text) >= 0;
3174
- }, {
3175
- timeout: aSec * 1000,
3176
- timeoutMsg: `element (${_context}) is not in DOM or there is no element(${_context}) with text "${text}" after ${aSec} sec`,
3177
- });
3178
- }
3179
-
3180
- /**
3181
- * Waits for the specified value to be in value attribute.
3182
- *
3183
- * ```js
3184
- * I.waitForValue('//input', "GoodValue");
3185
- * ```
3186
- *
3187
- * @param {LocatorOrString} field input field.
3188
- * @param {string }value expected value.
3189
- * @param {number} [sec=1] (optional, `1` by default) time in seconds to wait
3190
- * @returns {void} automatically synchronized promise through #recorder
3191
- *
3192
- */
3193
- async waitForValue(field, value, sec = null) {
3194
- const client = this.browser;
3195
- const aSec = sec || this.options.waitForTimeoutInSeconds;
3196
-
3197
- return client.waitUntil(async () => {
3198
- const res = await findFields.call(this, field);
3199
- if (!res || res.length === 0) return false;
3200
- const selected = await forEachAsync(res, async el => el.getValue());
3201
- if (Array.isArray(selected)) {
3202
- return selected.filter(part => part.indexOf(value) >= 0).length > 0;
3203
- }
3204
- return selected.indexOf(value) >= 0;
3205
- }, {
3206
- timeout: aSec * 1000,
3207
- timeoutMsg: `element (${field}) is not in DOM or there is no element(${field}) with value "${value}" after ${aSec} sec`,
3208
- });
3209
- }
3210
-
3211
- /**
3212
- * Waits for an element to become visible on a page (by default waits for 1sec).
3213
- * Element can be located by CSS or XPath.
3214
- *
3215
- * ```js
3216
- * I.waitForVisible('#popup');
3217
- * ```
3218
- *
3219
- * @param {CodeceptJS.LocatorOrString} locator element located by CSS|XPath|strict locator.
3220
- * @param {number} [sec=1] (optional, `1` by default) time in seconds to wait
3221
- * @returns {void} automatically synchronized promise through #recorder
3222
- *
3223
- *
3224
- */
3225
- async waitForVisible(locator, sec = null) {
3226
- const aSec = sec || this.options.waitForTimeoutInSeconds;
3227
-
3228
- return this.browser.waitUntil(async () => {
3229
- const res = await this._res(locator);
3230
- if (!res || res.length === 0) return false;
3231
- const selected = await forEachAsync(res, async el => el.isDisplayed());
3232
- if (Array.isArray(selected)) {
3233
- return selected.filter(val => val === true).length > 0;
3234
- }
3235
- return selected;
3236
- }, { timeout: aSec * 1000, timeoutMsg: `element (${new Locator(locator)}) still not visible after ${aSec} sec` });
3237
- }
3238
-
3239
- /**
3240
- * Waits for a specified number of elements on the page.
3241
- *
3242
- * ```js
3243
- * I.waitNumberOfVisibleElements('a', 3);
3244
- * ```
3245
- *
3246
- * @param {CodeceptJS.LocatorOrString} locator element located by CSS|XPath|strict locator.
3247
- * @param {number} num number of elements.
3248
- * @param {number} [sec=1] (optional, `1` by default) time in seconds to wait
3249
- * @returns {void} automatically synchronized promise through #recorder
3250
- *
3251
- */
3252
- async waitNumberOfVisibleElements(locator, num, sec = null) {
3253
- const aSec = sec || this.options.waitForTimeoutInSeconds;
3254
-
3255
- return this.browser.waitUntil(async () => {
3256
- const res = await this._res(locator);
3257
- if (!res || res.length === 0) return false;
3258
- let selected = await forEachAsync(res, async el => el.isDisplayed());
3259
-
3260
- if (!Array.isArray(selected)) selected = [selected];
3261
- selected = selected.filter(val => val === true);
3262
- return selected.length === num;
3263
- }, { timeout: aSec * 1000, timeoutMsg: `The number of elements (${new Locator(locator)}) is not ${num} after ${aSec} sec` });
3264
- }
3265
-
3266
- /**
3267
- * Waits for an element to be removed or become invisible on a page (by default waits for 1sec).
3268
- * Element can be located by CSS or XPath.
3269
- *
3270
- * ```js
3271
- * I.waitForInvisible('#popup');
3272
- * ```
3273
- *
3274
- * @param {CodeceptJS.LocatorOrString} locator element located by CSS|XPath|strict locator.
3275
- * @param {number} [sec=1] (optional, `1` by default) time in seconds to wait
3276
- * @returns {void} automatically synchronized promise through #recorder
3277
- *
3278
- */
3279
- async waitForInvisible(locator, sec = null) {
3280
- const aSec = sec || this.options.waitForTimeoutInSeconds;
3281
-
3282
- return this.browser.waitUntil(async () => {
3283
- const res = await this._res(locator);
3284
- if (!res || res.length === 0) return true;
3285
- const selected = await forEachAsync(res, async el => el.isDisplayed());
3286
- return !selected.length;
3287
- }, { timeout: aSec * 1000, timeoutMsg: `element (${new Locator(locator)}) still visible after ${aSec} sec` });
3288
- }
3289
-
3290
- /**
3291
- * Waits for an element to hide (by default waits for 1sec).
3292
- * Element can be located by CSS or XPath.
3293
- *
3294
- * ```js
3295
- * I.waitToHide('#popup');
3296
- * ```
3297
- *
3298
- * @param {CodeceptJS.LocatorOrString} locator element located by CSS|XPath|strict locator.
3299
- * @param {number} [sec=1] (optional, `1` by default) time in seconds to wait
3300
- * @returns {void} automatically synchronized promise through #recorder
3301
- *
3302
- */
3303
- async waitToHide(locator, sec = null) {
3304
- return this.waitForInvisible(locator, sec);
3305
- }
3306
-
3307
- /**
3308
- * Waits for an element to become not attached to the DOM on a page (by default waits for 1sec).
3309
- * Element can be located by CSS or XPath.
3310
- *
3311
- * ```js
3312
- * I.waitForDetached('#popup');
3313
- * ```
3314
- *
3315
- * @param {CodeceptJS.LocatorOrString} locator element located by CSS|XPath|strict locator.
3316
- * @param {number} [sec=1] (optional, `1` by default) time in seconds to wait
3317
- * @returns {void} automatically synchronized promise through #recorder
3318
- *
3319
- */
3320
- async waitForDetached(locator, sec = null) {
3321
- const aSec = sec || this.options.waitForTimeoutInSeconds;
3322
-
3323
- return this.browser.waitUntil(async () => {
3324
- const res = await this._res(locator);
3325
- if (!res || res.length === 0) {
3326
- return true;
3327
- }
3328
- return false;
3329
- }, { timeout: aSec * 1000, timeoutMsg: `element (${new Locator(locator)}) still on page after ${aSec} sec` });
3330
- }
3331
-
3332
- /**
3333
- * Waits for a function to return true (waits for 1 sec by default).
3334
- * Running in browser context.
3335
- *
3336
- * ```js
3337
- * I.waitForFunction(fn[, [args[, timeout]])
3338
- * ```
3339
- *
3340
- * ```js
3341
- * I.waitForFunction(() => window.requests == 0);
3342
- * I.waitForFunction(() => window.requests == 0, 5); // waits for 5 sec
3343
- * I.waitForFunction((count) => window.requests == count, [3], 5) // pass args and wait for 5 sec
3344
- * ```
3345
- *
3346
- * @param {string|function} fn to be executed in browser context.
3347
- * @param {any[]|number} [argsOrSec] (optional, `1` by default) arguments for function or seconds.
3348
- * @param {number} [sec] (optional, `1` by default) time in seconds to wait
3349
- * @returns {void} automatically synchronized promise through #recorder
3350
- *
3351
- */
3352
- async waitForFunction(fn, argsOrSec = null, sec = null) {
3353
- let args = [];
3354
- if (argsOrSec) {
3355
- if (Array.isArray(argsOrSec)) {
3356
- args = argsOrSec;
3357
- } else if (typeof argsOrSec === 'number') {
3358
- sec = argsOrSec;
3359
- }
3360
- }
3361
-
3362
- const aSec = sec || this.options.waitForTimeoutInSeconds;
3363
-
3364
- return this.browser.waitUntil(async () => this.browser.execute(fn, ...args), { timeout: aSec * 1000, timeoutMsg: '' });
3365
- }
3366
-
3367
- /**
3368
- * Switches frame or in case of null locator reverts to parent.
3369
- *
3370
- * ```js
3371
- * I.switchTo('iframe'); // switch to first iframe
3372
- * I.switchTo(); // switch back to main page
3373
- * ```
3374
- *
3375
- * @param {?CodeceptJS.LocatorOrString} [locator=null] (optional, `null` by default) element located by CSS|XPath|strict locator.
3376
- * @returns {void} automatically synchronized promise through #recorder
3377
- *
3378
- */
3379
- async switchTo(locator) {
3380
- this.browser.isInsideFrame = true;
3381
- if (Number.isInteger(locator)) {
3382
- return this.browser.switchToFrame(locator);
3383
- }
3384
- if (!locator) {
3385
- return this.browser.switchToFrame(null);
3386
- }
3387
-
3388
- let res = await this._locate(locator, true);
3389
- assertElementExists(res, locator);
3390
- res = usingFirstElement(res);
3391
- return this.browser.switchToFrame(res);
3392
- }
3393
-
3394
- /**
3395
- * Switch focus to a particular tab by its number. It waits tabs loading and then switch tab.
3396
- *
3397
- * ```js
3398
- * I.switchToNextTab();
3399
- * I.switchToNextTab(2);
3400
- * ```
3401
- *
3402
- * @param {number} [num] (optional) number of tabs to switch forward, default: 1.
3403
- * @param {number | null} [sec] (optional) time in seconds to wait.
3404
- * @returns {void} automatically synchronized promise through #recorder
3405
- *
3406
- */
3407
- async switchToNextTab(num = 1, sec = null) {
3408
- const aSec = sec || this.options.waitForTimeoutInSeconds;
3409
- let target;
3410
- const current = await this.browser.getWindowHandle();
3411
-
3412
- await this.browser.waitUntil(async () => {
3413
- await this.browser.getWindowHandles().then((handles) => {
3414
- if (handles.indexOf(current) + num + 1 <= handles.length) {
3415
- target = handles[handles.indexOf(current) + num];
3416
- }
3417
- });
3418
- return target;
3419
- }, { timeout: aSec * 1000, timeoutMsg: `There is no ability to switch to next tab with offset ${num}` });
3420
- return this.browser.switchToWindow(target);
3421
- }
3422
-
3423
- /**
3424
- * Switch focus to a particular tab by its number. It waits tabs loading and then switch tab.
3425
- *
3426
- * ```js
3427
- * I.switchToPreviousTab();
3428
- * I.switchToPreviousTab(2);
3429
- * ```
3430
- *
3431
- * @param {number} [num] (optional) number of tabs to switch backward, default: 1.
3432
- * @param {number?} [sec] (optional) time in seconds to wait.
3433
- * @returns {void} automatically synchronized promise through #recorder
3434
- *
3435
- */
3436
- async switchToPreviousTab(num = 1, sec = null) {
3437
- const aSec = sec || this.options.waitForTimeoutInSeconds;
3438
- const current = await this.browser.getWindowHandle();
3439
- let target;
3440
-
3441
- await this.browser.waitUntil(async () => {
3442
- await this.browser.getWindowHandles().then((handles) => {
3443
- if (handles.indexOf(current) - num > -1) {
3444
- target = handles[handles.indexOf(current) - num];
3445
- }
3446
- });
3447
- return target;
3448
- }, { timeout: aSec * 1000, timeoutMsg: `There is no ability to switch to previous tab with offset ${num}` });
3449
- return this.browser.switchToWindow(target);
3450
- }
3451
-
3452
- /**
3453
- * Close current tab.
3454
- *
3455
- * ```js
3456
- * I.closeCurrentTab();
3457
- * ```
3458
- *
3459
- * @returns {void} automatically synchronized promise through #recorder
3460
- *
3461
- */
3462
- async closeCurrentTab() {
3463
- await this.browser.closeWindow();
3464
- const handles = await this.browser.getWindowHandles();
3465
- if (handles[0]) await this.browser.switchToWindow(handles[0]);
3466
- }
3467
-
3468
- /**
3469
- * Open new tab and switch to it.
3470
- *
3471
- * ```js
3472
- * I.openNewTab();
3473
- * ```
3474
- *
3475
- * @returns {void} automatically synchronized promise through #recorder
3476
- *
3477
- */
3478
- async openNewTab(url = 'about:blank', windowName = null) {
3479
- const client = this.browser;
3480
- const crypto = require('crypto');
3481
- if (windowName == null) {
3482
- windowName = crypto.randomBytes(32).toString('hex');
3483
- }
3484
- return client.newWindow(url, windowName);
3485
- }
3486
-
3487
- /**
3488
- * Grab number of open tabs.
3489
- * Resumes test execution, so **should be used inside async function with `await`** operator.
3490
- *
3491
- * ```js
3492
- * let tabs = await I.grabNumberOfOpenTabs();
3493
- * ```
3494
- *
3495
- * @returns {Promise<number>} number of open tabs
3496
- *
3497
- */
3498
- async grabNumberOfOpenTabs() {
3499
- const pages = await this.browser.getWindowHandles();
3500
- this.debugSection('Tabs', `Total ${pages.length}`);
3501
- return pages.length;
3502
- }
3503
-
3504
- /**
3505
- * Reload the current page.
3506
- *
3507
- * ```js
3508
- * I.refreshPage();
3509
- * ```
3510
- * @returns {void} automatically synchronized promise through #recorder
3511
- *
3512
- */
3513
- async refreshPage() {
3514
- const client = this.browser;
3515
- return client.refresh();
3516
- }
3517
-
3518
- /**
3519
- * Scroll page to the top.
3520
- *
3521
- * ```js
3522
- * I.scrollPageToTop();
3523
- * ```
3524
- * @returns {void} automatically synchronized promise through #recorder
3525
- *
3526
- */
3527
- scrollPageToTop() {
3528
- const client = this.browser;
3529
- /* eslint-disable prefer-arrow-callback */
3530
- return client.execute(function () {
3531
- window.scrollTo(0, 0);
3532
- });
3533
- /* eslint-enable */
3534
- }
3535
-
3536
- /**
3537
- * Scroll page to the bottom.
3538
- *
3539
- * ```js
3540
- * I.scrollPageToBottom();
3541
- * ```
3542
- * @returns {void} automatically synchronized promise through #recorder
3543
- *
3544
- */
3545
- scrollPageToBottom() {
3546
- const client = this.browser;
3547
- /* eslint-disable prefer-arrow-callback, comma-dangle */
3548
- return client.execute(function () {
3549
- const body = document.body;
3550
- const html = document.documentElement;
3551
- window.scrollTo(0, Math.max(
3552
- body.scrollHeight,
3553
- body.offsetHeight,
3554
- html.clientHeight,
3555
- html.scrollHeight,
3556
- html.offsetHeight
3557
- ));
3558
- });
3559
- /* eslint-enable */
3560
- }
3561
-
3562
- /**
3563
- * Retrieves a page scroll position and returns it to test.
3564
- * Resumes test execution, so **should be used inside an async function with `await`** operator.
3565
- *
3566
- * ```js
3567
- * let { x, y } = await I.grabPageScrollPosition();
3568
- * ```
3569
- *
3570
- * @returns {Promise<PageScrollPosition>} scroll position
3571
- *
3572
- */
3573
- async grabPageScrollPosition() {
3574
- /* eslint-disable comma-dangle */
3575
- function getScrollPosition() {
3576
- return {
3577
- x: window.pageXOffset,
3578
- y: window.pageYOffset
3579
- };
3580
- }
3581
- /* eslint-enable comma-dangle */
3582
- return this.executeScript(getScrollPosition);
3583
- }
3584
-
3585
- /**
3586
- * Set the current geo location
3587
- *
3588
- *
3589
- * ```js
3590
- * I.setGeoLocation(121.21, 11.56);
3591
- * I.setGeoLocation(121.21, 11.56, 10);
3592
- * ```
3593
- *
3594
- * @param {number} latitude to set.
3595
- * @param {number} longitude to set
3596
- * @param {number=} altitude (optional, null by default) to set
3597
- * @returns {void} automatically synchronized promise through #recorder
3598
- *
3599
- */
3600
- async setGeoLocation(latitude, longitude, altitude = null) {
3601
- if (altitude) {
3602
- return this.browser.setGeoLocation({ latitude, longitude });
3603
- }
3604
- return this.browser.setGeoLocation({ latitude, longitude, altitude });
3605
- }
3606
-
3607
- /**
3608
- * Return the current geo location
3609
- * Resumes test execution, so **should be used inside async function with `await`** operator.
3610
- *
3611
- * ```js
3612
- * let geoLocation = await I.grabGeoLocation();
3613
- * ```
3614
- *
3615
- * @returns {Promise<{ latitude: number, longitude: number, altitude: number }>}
3616
- *
3617
- */
3618
- async grabGeoLocation() {
3619
- return this.browser.getGeoLocation();
3620
- }
3621
-
3622
- /**
3623
- * Grab the width, height, location of given locator.
3624
- * Provide `width` or `height`as second param to get your desired prop.
3625
- * Resumes test execution, so **should be used inside an async function with `await`** operator.
3626
- *
3627
- * Returns an object with `x`, `y`, `width`, `height` keys.
3628
- *
3629
- * ```js
3630
- * const value = await I.grabElementBoundingRect('h3');
3631
- * // value is like { x: 226.5, y: 89, width: 527, height: 220 }
3632
- * ```
3633
- *
3634
- * To get only one metric use second parameter:
3635
- *
3636
- * ```js
3637
- * const width = await I.grabElementBoundingRect('h3', 'width');
3638
- * // width == 527
3639
- * ```
3640
- * @param {LocatorOrString} locator element located by CSS|XPath|strict locator.
3641
- * @param {string=} elementSize x, y, width or height of the given element.
3642
- * @returns {Promise<DOMRect>|Promise<number>} Element bounding rectangle
3643
- *
3644
- */
3645
- async grabElementBoundingRect(locator, prop) {
3646
- const res = await this._locate(locator, true);
3647
- assertElementExists(res, locator);
3648
- const el = usingFirstElement(res);
3649
-
3650
- const rect = {
3651
- ...await el.getLocation(),
3652
- ...await el.getSize(),
3653
- };
3654
- if (prop) return rect[prop];
3655
- return rect;
3656
- }
3657
-
3658
- /**
3659
- * Placeholder for ~ locator only test case write once run on both Appium and WebDriver.
3660
- * @param {*} caps
3661
- * @param {*} fn
3662
- */
3663
- /* eslint-disable */
3664
- runOnIOS(caps, fn) {
3665
- }
3666
-
3667
- /**
3668
- * Placeholder for ~ locator only test case write once run on both Appium and WebDriver.
3669
- * @param {*} caps
3670
- * @param {*} fn
3671
- */
3672
- runOnAndroid(caps, fn) {
3673
- }
3674
- /* eslint-enable */
3675
-
3676
- /**
3677
- * Placeholder for ~ locator only test case write once run on both Appium and WebDriver.
3678
- */
3679
- runInWeb(fn) {
3680
- return fn();
3681
- }
3682
- }
3683
-
3684
- async function proceedSee(assertType, text, context, strict = false) {
3685
- let description;
3686
- if (!context) {
3687
- if (this.context === webRoot) {
3688
- context = this.context;
3689
- description = 'web page';
3690
- } else {
3691
- description = `current context ${this.context}`;
3692
- context = './/*';
3693
- }
3694
- } else {
3695
- description = `element ${context}`;
3696
- }
3697
-
3698
- const smartWaitEnabled = assertType === 'assert';
3699
- const res = await this._locate(withStrictLocator(context), smartWaitEnabled);
3700
- assertElementExists(res, context);
3701
- const selected = await forEachAsync(res, async el => this.browser.getElementText(getElementId(el)));
3702
- if (strict) {
3703
- if (Array.isArray(selected) && selected.length !== 0) {
3704
- return selected.map(elText => equals(description)[assertType](text, elText));
3705
- }
3706
- return equals(description)[assertType](text, selected);
3707
- }
3708
- return stringIncludes(description)[assertType](text, selected);
3709
- }
3710
-
3711
- /**
3712
- * Mimic Array.forEach() API, but with an async callback function.
3713
- * Execute each callback on each array item serially. Useful when using WebDriver API.
3714
- *
3715
- * Added due because of problem with chrome driver when too many requests
3716
- * are made simultaneously. https://bugs.chromium.org/p/chromedriver/issues/detail?id=2152#c9
3717
- * @private
3718
- * @param {Array} array Input array items to iterate over.
3719
- * @param {Function} callback - Async function to excute on each array item.
3720
- * @param {object} [options] - Configurable options.
3721
- * @param {boolean} [options.expandArrayResults=true] - Flag to flat one dimension array results.
3722
- * @return {Promise<Array>} - Array of values.
3723
- */
3724
- async function forEachAsync(array, callback, options = { expandArrayResults: true }) {
3725
- const {
3726
- expandArrayResults = true,
3727
- } = options;
3728
- const inputArray = Array.isArray(array) ? array : [array];
3729
- const values = [];
3730
- for (let index = 0; index < inputArray.length; index++) {
3731
- const res = await callback(inputArray[index], index, inputArray);
3732
-
3733
- if (Array.isArray(res) && expandArrayResults) {
3734
- res.forEach(val => values.push(val));
3735
- } else if (res) {
3736
- values.push(res);
3737
- }
3738
- }
3739
- return values;
3740
- }
3741
-
3742
- /**
3743
- * Mimic Array.filter() API, but with an async callback function.
3744
- * Execute each callback on each array item serially. Useful when using WebDriver API.
3745
- *
3746
- * Added due because of problem with chrome driver when too many requests
3747
- * are made simultaneously. https://bugs.chromium.org/p/chromedriver/issues/detail?id=2152#c9
3748
- * @private
3749
- * @param {Array} array - Input array items to iterate over.
3750
- * @param {Function} callback - Async functin to excute on each array item.
3751
- * @return {Promise<Array>} - Array of values.
3752
- */
3753
- async function filterAsync(array, callback) {
3754
- const inputArray = Array.isArray(array) ? array : [array];
3755
- const values = [];
3756
- for (let index = 0; index < inputArray.length; index++) {
3757
- const res = await callback(inputArray[index], index, inputArray);
3758
- const value = Array.isArray(res) ? res[0] : res;
3759
-
3760
- if (value) {
3761
- values.push(inputArray[index]);
3762
- }
3763
- }
3764
- return values;
3765
- }
3766
-
3767
- async function findClickable(locator, locateFn) {
3768
- locator = new Locator(locator);
3769
-
3770
- if (this._isCustomLocator(locator)) {
3771
- return locateFn(locator.value);
3772
- }
3773
-
3774
- if (locator.isAccessibilityId() && !this.isWeb) return locateFn(locator, true);
3775
- if (!locator.isFuzzy()) return locateFn(locator, true);
3776
-
3777
- let els;
3778
- const literal = xpathLocator.literal(locator.value);
3779
-
3780
- els = await locateFn(Locator.clickable.narrow(literal));
3781
- if (els.length) return els;
3782
-
3783
- els = await locateFn(Locator.clickable.wide(literal));
3784
- if (els.length) return els;
3785
-
3786
- els = await locateFn(Locator.clickable.self(literal));
3787
- if (els.length) return els;
3788
-
3789
- return locateFn(locator.value); // by css or xpath
3790
- }
3791
-
3792
- async function findFields(locator) {
3793
- locator = new Locator(locator);
3794
-
3795
- if (this._isCustomLocator(locator)) {
3796
- return this._locate(locator);
3797
- }
3798
-
3799
- if (locator.isAccessibilityId() && !this.isWeb) return this._locate(locator, true);
3800
- if (!locator.isFuzzy()) return this._locate(locator, true);
3801
-
3802
- const literal = xpathLocator.literal(locator.value);
3803
- let els = await this._locate(Locator.field.labelEquals(literal));
3804
- if (els.length) return els;
3805
-
3806
- els = await this._locate(Locator.field.labelContains(literal));
3807
- if (els.length) return els;
3808
-
3809
- els = await this._locate(Locator.field.byName(literal));
3810
- if (els.length) return els;
3811
- return this._locate(locator.value); // by css or xpath
3812
- }
3813
-
3814
- async function proceedSeeField(assertType, field, value) {
3815
- const res = await findFields.call(this, field);
3816
- assertElementExists(res, field, 'Field');
3817
- const elem = usingFirstElement(res);
3818
- const elemId = getElementId(elem);
3819
-
3820
- const proceedMultiple = async (fields) => {
3821
- const fieldResults = toArray(await forEachAsync(fields, async (el) => {
3822
- const elementId = getElementId(el);
3823
- return this.browser.isW3C ? el.getValue() : this.browser.getElementAttribute(elementId, 'value');
3824
- }));
3825
-
3826
- if (typeof value === 'boolean') {
3827
- equals(`no. of items matching > 0: ${field}`)[assertType](value, !!fieldResults.length);
3828
- } else {
3829
- // Assert that results were found so the forEach assert does not silently pass
3830
- equals(`no. of items matching > 0: ${field}`)[assertType](true, !!fieldResults.length);
3831
- fieldResults.forEach(val => stringIncludes(`fields by ${field}`)[assertType](value, val));
3832
- }
3833
- };
3834
-
3835
- const proceedSingle = el => this.browser.getElementAttribute(getElementId(el), 'value').then((res) => {
3836
- if (res === null) {
3837
- throw new Error(`Element ${el.selector} has no value attribute`);
3838
- }
3839
- stringIncludes(`fields by ${field}`)[assertType](value, res);
3840
- });
3841
-
3842
- const filterBySelected = async elements => filterAsync(elements, async el => this.browser.isElementSelected(getElementId(el)));
3843
-
3844
- const filterSelectedByValue = async (elements, value) => {
3845
- return filterAsync(elements, async (el) => {
3846
- const elementId = getElementId(el);
3847
- const currentValue = this.browser.isW3C ? await el.getValue() : await this.browser.getElementAttribute(elementId, 'value');
3848
- const isSelected = await this.browser.isElementSelected(elementId);
3849
- return currentValue === value && isSelected;
3850
- });
3851
- };
3852
-
3853
- const tag = await elem.getTagName();
3854
- if (tag === 'select') {
3855
- const subOptions = await this.browser.findElementsFromElement(elemId, 'css', 'option');
3856
-
3857
- if (value === '') {
3858
- // Don't filter by value
3859
- const selectedOptions = await filterBySelected(subOptions);
3860
- return proceedMultiple(selectedOptions);
3861
- }
3862
-
3863
- const options = await filterSelectedByValue(subOptions, value);
3864
- return proceedMultiple(options);
3865
- }
3866
-
3867
- if (tag === 'input') {
3868
- const fieldType = await elem.getAttribute('type');
3869
-
3870
- if (fieldType === 'checkbox' || fieldType === 'radio') {
3871
- if (typeof value === 'boolean') {
3872
- // Support boolean values
3873
- const options = await filterBySelected(res);
3874
- return proceedMultiple(options);
3875
- }
3876
-
3877
- const options = await filterSelectedByValue(res, value);
3878
- return proceedMultiple(options);
3879
- }
3880
- return proceedSingle(elem);
3881
- }
3882
- return proceedSingle(elem);
3883
- }
3884
-
3885
- function toArray(item) {
3886
- if (!Array.isArray(item)) {
3887
- return [item];
3888
- }
3889
- return item;
3890
- }
3891
-
3892
- async function proceedSeeCheckbox(assertType, field) {
3893
- const res = await findFields.call(this, field);
3894
- assertElementExists(res, field, 'Field');
3895
-
3896
- const selected = await forEachAsync(res, async el => this.browser.isElementSelected(getElementId(el)));
3897
- return truth(`checkable field "${field}"`, 'to be checked')[assertType](selected);
3898
- }
3899
-
3900
- async function findCheckable(locator, locateFn) {
3901
- let els;
3902
- locator = new Locator(locator);
3903
-
3904
- if (this._isCustomLocator(locator)) {
3905
- return locateFn(locator.value);
3906
- }
3907
-
3908
- if (locator.isAccessibilityId() && !this.isWeb) return locateFn(locator, true);
3909
- if (!locator.isFuzzy()) return locateFn(locator, true);
3910
-
3911
- const literal = xpathLocator.literal(locator.value);
3912
- els = await locateFn(Locator.checkable.byText(literal));
3913
- if (els.length) return els;
3914
- els = await locateFn(Locator.checkable.byName(literal));
3915
- if (els.length) return els;
3916
-
3917
- return locateFn(locator.value); // by css or xpath
3918
- }
3919
-
3920
- function withStrictLocator(locator) {
3921
- locator = new Locator(locator);
3922
- return locator.simplify();
3923
- }
3924
-
3925
- function isFrameLocator(locator) {
3926
- locator = new Locator(locator);
3927
- if (locator.isFrame()) return locator.value;
3928
- return false;
3929
- }
3930
-
3931
- function assertElementExists(res, locator, prefix, suffix) {
3932
- if (!res || res.length === 0) {
3933
- throw new ElementNotFound(locator, prefix, suffix);
3934
- }
3935
- }
3936
-
3937
- function usingFirstElement(els) {
3938
- if (els.length > 1) debug(`[Elements] Using first element out of ${els.length}`);
3939
- return els[0];
3940
- }
3941
-
3942
- function getElementId(el) {
3943
- // W3C WebDriver web element identifier
3944
- // https://w3c.github.io/webdriver/#dfn-web-element-identifier
3945
- if (el['element-6066-11e4-a52e-4f735466cecf']) {
3946
- return el['element-6066-11e4-a52e-4f735466cecf'];
3947
- }
3948
- // (deprecated) JsonWireProtocol identifier
3949
- // https://github.com/SeleniumHQ/selenium/wiki/JsonWireProtocol#webelement-json-object
3950
- if (el.ELEMENT) {
3951
- return el.ELEMENT;
3952
- }
3953
-
3954
- return null;
3955
- }
3956
-
3957
- // List of known key values to unicode code points
3958
- // https://www.w3.org/TR/webdriver/#keyboard-actions
3959
- const keyUnicodeMap = {
3960
- /* eslint-disable quote-props */
3961
- 'Unidentified': '\uE000',
3962
- 'Cancel': '\uE001',
3963
- 'Clear': '\uE005',
3964
- 'Help': '\uE002',
3965
- 'Pause': '\uE00B',
3966
- 'Backspace': '\uE003',
3967
- 'Return': '\uE006',
3968
- 'Enter': '\uE007',
3969
- 'Escape': '\uE00C',
3970
- 'Alt': '\uE00A',
3971
- 'AltLeft': '\uE00A',
3972
- 'AltRight': '\uE052',
3973
- 'Control': '\uE009',
3974
- 'ControlLeft': '\uE009',
3975
- 'ControlRight': '\uE051',
3976
- 'Meta': '\uE03D',
3977
- 'MetaLeft': '\uE03D',
3978
- 'MetaRight': '\uE053',
3979
- 'Shift': '\uE008',
3980
- 'ShiftLeft': '\uE008',
3981
- 'ShiftRight': '\uE050',
3982
- 'Space': '\uE00D',
3983
- ' ': '\uE00D',
3984
- 'Tab': '\uE004',
3985
- 'Insert': '\uE016',
3986
- 'Delete': '\uE017',
3987
- 'End': '\uE010',
3988
- 'Home': '\uE011',
3989
- 'PageUp': '\uE00E',
3990
- 'PageDown': '\uE00F',
3991
- 'ArrowDown': '\uE015',
3992
- 'ArrowLeft': '\uE012',
3993
- 'ArrowRight': '\uE014',
3994
- 'ArrowUp': '\uE013',
3995
- 'F1': '\uE031',
3996
- 'F2': '\uE032',
3997
- 'F3': '\uE033',
3998
- 'F4': '\uE034',
3999
- 'F5': '\uE035',
4000
- 'F6': '\uE036',
4001
- 'F7': '\uE037',
4002
- 'F8': '\uE038',
4003
- 'F9': '\uE039',
4004
- 'F10': '\uE03A',
4005
- 'F11': '\uE03B',
4006
- 'F12': '\uE03C',
4007
- 'Numpad0': '\uE01A',
4008
- 'Numpad1': '\uE01B',
4009
- 'Numpad2': '\uE01C',
4010
- 'Numpad3': '\uE01D',
4011
- 'Numpad4': '\uE01E',
4012
- 'Numpad5': '\uE01F',
4013
- 'Numpad6': '\uE020',
4014
- 'Numpad7': '\uE021',
4015
- 'Numpad8': '\uE022',
4016
- 'Numpad9': '\uE023',
4017
- 'NumpadMultiply': '\uE024',
4018
- 'NumpadAdd': '\uE025',
4019
- 'NumpadSubtract': '\uE027',
4020
- 'NumpadDecimal': '\uE028',
4021
- 'NumpadDivide': '\uE029',
4022
- 'NumpadEnter': '\uE007',
4023
- 'NumpadInsert': '\uE05C', // 'Numpad0' alternate (when NumLock off)
4024
- 'NumpadDelete': '\uE05D', // 'NumpadDecimal' alternate (when NumLock off)
4025
- 'NumpadEnd': '\uE056', // 'Numpad1' alternate (when NumLock off)
4026
- 'NumpadHome': '\uE057', // 'Numpad7' alternate (when NumLock off)
4027
- 'NumpadPageDown': '\uE055', // 'Numpad3' alternate (when NumLock off)
4028
- 'NumpadPageUp': '\uE054', // 'Numpad9' alternate (when NumLock off)
4029
- 'NumpadArrowDown': '\uE05B', // 'Numpad2' alternate (when NumLock off)
4030
- 'NumpadArrowLeft': '\uE058', // 'Numpad4' alternate (when NumLock off)
4031
- 'NumpadArrowRight': '\uE05A', // 'Numpad6' alternate (when NumLock off)
4032
- 'NumpadArrowUp': '\uE059', // 'Numpad8' alternate (when NumLock off)
4033
- 'Comma': '\uE026', // ',' alias
4034
- 'Digit0': '0', // '0' alias
4035
- 'Digit1': '1', // '1' alias
4036
- 'Digit2': '2', // '2' alias
4037
- 'Digit3': '3', // '3' alias
4038
- 'Digit4': '4', // '4' alias
4039
- 'Digit5': '5', // '5' alias
4040
- 'Digit6': '6', // '6' alias
4041
- 'Digit7': '7', // '7' alias
4042
- 'Digit8': '8', // '8' alias
4043
- 'Digit9': '9', // '9' alias
4044
- 'Equal': '\uE019', // '=' alias
4045
- 'KeyA': 'a', // 'a' alias
4046
- 'KeyB': 'b', // 'b' alias
4047
- 'KeyC': 'c', // 'c' alias
4048
- 'KeyD': 'd', // 'd' alias
4049
- 'KeyE': 'e', // 'e' alias
4050
- 'KeyF': 'f', // 'f' alias
4051
- 'KeyG': 'g', // 'g' alias
4052
- 'KeyH': 'h', // 'h' alias
4053
- 'KeyI': 'i', // 'i' alias
4054
- 'KeyJ': 'j', // 'j' alias
4055
- 'KeyK': 'k', // 'k' alias
4056
- 'KeyL': 'l', // 'l' alias
4057
- 'KeyM': 'm', // 'm' alias
4058
- 'KeyN': 'n', // 'n' alias
4059
- 'KeyO': 'o', // 'o' alias
4060
- 'KeyP': 'p', // 'p' alias
4061
- 'KeyQ': 'q', // 'q' alias
4062
- 'KeyR': 'r', // 'r' alias
4063
- 'KeyS': 's', // 's' alias
4064
- 'KeyT': 't', // 't' alias
4065
- 'KeyU': 'u', // 'u' alias
4066
- 'KeyV': 'v', // 'v' alias
4067
- 'KeyW': 'w', // 'w' alias
4068
- 'KeyX': 'x', // 'x' alias
4069
- 'KeyY': 'y', // 'y' alias
4070
- 'KeyZ': 'z', // 'z' alias
4071
- 'Period': '.', // '.' alias
4072
- 'Semicolon': '\uE018', // ';' alias
4073
- 'Slash': '/', // '/' alias
4074
- 'ZenkakuHankaku': '\uE040',
4075
- /* eslint-enable quote-props */
4076
- };
4077
-
4078
- function convertKeyToRawKey(key) {
4079
- if (Object.prototype.hasOwnProperty.call(keyUnicodeMap, key)) {
4080
- return keyUnicodeMap[key];
4081
- }
4082
- // Key is raw key when no representative unicode code point for value
4083
- return key;
4084
- }
4085
-
4086
- function getNormalizedKey(key) {
4087
- let normalizedKey = getNormalizedKeyAttributeValue(key);
4088
- // Always use "left" modifier keys for non-W3C sessions,
4089
- // as JsonWireProtocol does not support "right" modifier keys
4090
- if (!this.browser.isW3C) {
4091
- normalizedKey = normalizedKey.replace(/^(Alt|Control|Meta|Shift)Right$/, '$1');
4092
- }
4093
- if (key !== normalizedKey) {
4094
- this.debugSection('Input', `Mapping key '${key}' to '${normalizedKey}'`);
4095
- }
4096
- return convertKeyToRawKey(normalizedKey);
4097
- }
4098
-
4099
- const unicodeModifierKeys = modifierKeys.map(k => convertKeyToRawKey(k));
4100
- function isModifierKey(key) {
4101
- return unicodeModifierKeys.includes(key);
4102
- }
4103
-
4104
- function highlightActiveElement(element) {
4105
- if (this.options.highlightElement && global.debugMode) {
4106
- highlightElement(element, this.browser);
4107
- }
4108
- }
4109
-
4110
- function prepareLocateFn(context) {
4111
- if (!context) return this._locate.bind(this);
4112
- return (l) => {
4113
- l = new Locator(l, 'css');
4114
- return this._locate(context, true).then(async (res) => {
4115
- assertElementExists(res, context, 'Context element');
4116
- if (l.react) {
4117
- return res[0].react$$(l.react, l.props || undefined);
4118
- }
4119
- return res[0].$$(l.simplify());
4120
- });
4121
- };
4122
- }
4123
-
4124
- module.exports = WebDriver;