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