codeceptjs 3.5.0 → 3.5.1-2.beta.7

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