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,3710 +0,0 @@
1
- const axios = require('axios');
2
- const fs = require('fs');
3
- const fsExtra = require('fs-extra');
4
- const path = require('path');
5
-
6
- const Helper = require('@codeceptjs/helper');
7
- const Locator = require('../locator');
8
- const recorder = require('../recorder');
9
- const stringIncludes = require('../assert/include').includes;
10
- const { urlEquals } = require('../assert/equal');
11
- const { equals } = require('../assert/equal');
12
- const { empty } = require('../assert/empty');
13
- const { truth } = require('../assert/truth');
14
- const isElementClickable = require('./scripts/isElementClickable');
15
- const {
16
- xpathLocator,
17
- ucfirst,
18
- fileExists,
19
- chunkArray,
20
- toCamelCase,
21
- convertCssPropertiesToCamelCase,
22
- screenshotOutputFolder,
23
- getNormalizedKeyAttributeValue,
24
- isModifierKey,
25
- requireWithFallback,
26
- } = require('../utils');
27
- const {
28
- isColorProperty,
29
- convertColorToRGBA,
30
- } = require('../colorUtils');
31
- const ElementNotFound = require('./errors/ElementNotFound');
32
- const RemoteBrowserConnectionRefused = require('./errors/RemoteBrowserConnectionRefused');
33
- const Popup = require('./extras/Popup');
34
- const Console = require('./extras/Console');
35
- const findReact = require('./extras/React');
36
-
37
- let puppeteer;
38
- let perfTiming;
39
- const popupStore = new Popup();
40
- const consoleLogStore = new Console();
41
-
42
- /**
43
- * ## Configuration
44
- *
45
- * This helper should be configured in codecept.conf.js
46
- *
47
- * @typedef PuppeteerConfig
48
- * @type {object}
49
- * @prop {string} url - base url of website to be tested
50
- * @prop {object} [basicAuth] (optional) the basic authentication to pass to base url. Example: {username: 'username', password: 'password'}
51
- * @prop {boolean} [show] - show Google Chrome window for debug.
52
- * @prop {boolean} [restart=true] - restart browser between tests.
53
- * @prop {boolean} [disableScreenshots=false] - don't save screenshot on failure.
54
- * @prop {boolean} [fullPageScreenshots=false] - make full page screenshots on failure.
55
- * @prop {boolean} [uniqueScreenshotNames=false] - option to prevent screenshot override if you have scenarios with the same name in different suites.
56
- * @prop {boolean} [keepBrowserState=false] - keep browser state between tests when `restart` is set to false.
57
- * @prop {boolean} [keepCookies=false] - keep cookies between tests when `restart` is set to false.
58
- * @prop {number} [waitForAction=100] - how long to wait after click, doubleClick or PressKey actions in ms. Default: 100.
59
- * @prop {string} [waitForNavigation=load] - when to consider navigation succeeded. Possible options: `load`, `domcontentloaded`, `networkidle0`, `networkidle2`. See [Puppeteer API](https://github.com/GoogleChrome/puppeteer/blob/master/docs/api.md#pagewaitfornavigationoptions). Array values are accepted as well.
60
- * @prop {number} [pressKeyDelay=10] - delay between key presses in ms. Used when calling Puppeteers page.type(...) in fillField/appendField
61
- * @prop {number} [getPageTimeout=30000] - config option to set maximum navigation time in milliseconds. If the timeout is set to 0, then timeout will be disabled.
62
- * @prop {number} [waitForTimeout=1000] - default wait* timeout in ms.
63
- * @prop {string} [windowSize] - default window size. Set a dimension in format WIDTHxHEIGHT like `640x480`.
64
- * @prop {string} [userAgent] - user-agent string.
65
- * @prop {boolean} [manualStart=false] - do not start browser before a test, start it manually inside a helper with `this.helpers["Puppeteer"]._startBrowser()`.
66
- * @prop {string} [browser=chrome] - can be changed to `firefox` when using [puppeteer-firefox](https://codecept.io/helpers/Puppeteer-firefox).
67
- * @prop {object} [chrome] - pass additional [Puppeteer run options](https://github.com/GoogleChrome/puppeteer/blob/master/docs/api.md#puppeteerlaunchoptions).
68
- */
69
- const config = {};
70
-
71
- /**
72
- * Uses [Google Chrome's Puppeteer](https://github.com/GoogleChrome/puppeteer) library to run tests inside headless Chrome.
73
- * Browser control is executed via DevTools Protocol (instead of Selenium).
74
- * This helper works with a browser out of the box with no additional tools required to install.
75
- *
76
- * Requires `puppeteer` or `puppeteer-core` package to be installed.
77
- * ```
78
- * npm i puppeteer --save
79
- * ```
80
- * or
81
- * ```
82
- * npm i puppeteer-core --save
83
- * ```
84
- * Using `puppeteer-core` package, will prevent the download of browser binaries and allow connecting to an existing browser installation or for connecting to a remote one.
85
- *
86
- * > Experimental Firefox support [can be activated](https://codecept.io/helpers/Puppeteer-firefox).
87
- *
88
- * <!-- configuration -->
89
- *
90
- * #### Example #1: Wait for 0 network connections.
91
- *
92
- * ```js
93
- * {
94
- * helpers: {
95
- * Puppeteer : {
96
- * url: "http://localhost",
97
- * restart: false,
98
- * waitForNavigation: "networkidle0",
99
- * waitForAction: 500
100
- * }
101
- * }
102
- * }
103
- * ```
104
- *
105
- * #### Example #2: Wait for DOMContentLoaded event and 0 network connections
106
- *
107
- * ```js
108
- * {
109
- * helpers: {
110
- * Puppeteer : {
111
- * url: "http://localhost",
112
- * restart: false,
113
- * waitForNavigation: [ "domcontentloaded", "networkidle0" ],
114
- * waitForAction: 500
115
- * }
116
- * }
117
- * }
118
- * ```
119
- *
120
- * #### Example #3: Debug in window mode
121
- *
122
- * ```js
123
- * {
124
- * helpers: {
125
- * Puppeteer : {
126
- * url: "http://localhost",
127
- * show: true
128
- * }
129
- * }
130
- * }
131
- * ```
132
- *
133
- * #### Example #4: Connect to remote browser by specifying [websocket endpoint](https://chromedevtools.github.io/devtools-protocol/#how-do-i-access-the-browser-target)
134
- *
135
- * ```js
136
- * {
137
- * helpers: {
138
- * Puppeteer: {
139
- * url: "http://localhost",
140
- * chrome: {
141
- * browserWSEndpoint: "ws://localhost:9222/devtools/browser/c5aa6160-b5bc-4d53-bb49-6ecb36cd2e0a"
142
- * }
143
- * }
144
- * }
145
- * }
146
- * ```
147
- * > Note: When connecting to remote browser `show` and specific `chrome` options (e.g. `headless` or `devtools`) are ignored.
148
- *
149
- * #### Example #5: Target URL with provided basic authentication
150
- *
151
- * ```js
152
- * {
153
- * helpers: {
154
- * Puppeteer : {
155
- * url: 'http://localhost',
156
- * basicAuth: {username: 'username', password: 'password'},
157
- * show: true
158
- * }
159
- * }
160
- * }
161
- * ```
162
- * #### Troubleshooting
163
- *
164
- * Error Message: `No usable sandbox!`
165
- *
166
- * When running Puppeteer on CI try to disable sandbox if you see that message
167
- *
168
- * ```
169
- * helpers: {
170
- * Puppeteer: {
171
- * url: 'http://localhost',
172
- * show: false,
173
- * chrome: {
174
- * args: ['--no-sandbox', '--disable-setuid-sandbox']
175
- * }
176
- * },
177
- * }
178
- * ```
179
- *
180
- *
181
- *
182
- * ## Access From Helpers
183
- *
184
- * Receive Puppeteer client from a custom helper by accessing `browser` for the Browser object or `page` for the current Page object:
185
- *
186
- * ```js
187
- * const { browser } = this.helpers.Puppeteer;
188
- * await browser.pages(); // List of pages in the browser
189
- *
190
- * const { page } = this.helpers.Puppeteer;
191
- * await page.url(); // Get the url of the current page
192
- * ```
193
- *
194
- * ## Methods
195
- */
196
- class Puppeteer extends Helper {
197
- constructor(config) {
198
- super(config);
199
-
200
- puppeteer = requireWithFallback('puppeteer', 'puppeteer-core');
201
- // set defaults
202
- this.isRemoteBrowser = false;
203
- this.isRunning = false;
204
- this.isAuthenticated = false;
205
- this.sessionPages = {};
206
- this.activeSessionName = '';
207
-
208
- // override defaults with config
209
- this._setConfig(config);
210
- }
211
-
212
- _validateConfig(config) {
213
- const defaults = {
214
- browser: 'chrome',
215
- waitForAction: 100,
216
- waitForTimeout: 1000,
217
- pressKeyDelay: 10,
218
- fullPageScreenshots: false,
219
- disableScreenshots: false,
220
- uniqueScreenshotNames: false,
221
- manualStart: false,
222
- getPageTimeout: 30000,
223
- waitForNavigation: 'load',
224
- restart: true,
225
- keepCookies: false,
226
- keepBrowserState: false,
227
- show: false,
228
- defaultPopupAction: 'accept',
229
- };
230
-
231
- return Object.assign(defaults, config);
232
- }
233
-
234
- _getOptions(config) {
235
- return config.browser === 'firefox' ? Object.assign(this.options.firefox, { product: 'firefox' }) : this.options.chrome;
236
- }
237
-
238
- _setConfig(config) {
239
- this.options = this._validateConfig(config);
240
- this.puppeteerOptions = {
241
- headless: !this.options.show,
242
- ...this._getOptions(config),
243
- };
244
- this.isRemoteBrowser = !!this.puppeteerOptions.browserWSEndpoint;
245
- popupStore.defaultAction = this.options.defaultPopupAction;
246
- }
247
-
248
- static _config() {
249
- return [
250
- { name: 'url', message: 'Base url of site to be tested', default: 'http://localhost' },
251
- {
252
- name: 'show', message: 'Show browser window', default: true, type: 'confirm',
253
- },
254
- {
255
- name: 'windowSize', message: 'Browser viewport size', default: '1200x900',
256
- },
257
- ];
258
- }
259
-
260
- static _checkRequirements() {
261
- try {
262
- requireWithFallback('puppeteer', 'puppeteer-core');
263
- } catch (e) {
264
- return ['puppeteer'];
265
- }
266
- }
267
-
268
- _init() {
269
- }
270
-
271
- _beforeSuite() {
272
- if (!this.options.restart && !this.options.manualStart && !this.isRunning) {
273
- this.debugSection('Session', 'Starting singleton browser session');
274
- return this._startBrowser();
275
- }
276
- }
277
-
278
- async _before() {
279
- this.sessionPages = {};
280
- recorder.retry({
281
- retries: 3,
282
- when: err => {
283
- if (!err || typeof (err.message) !== 'string') {
284
- return false;
285
- }
286
- // ignore context errors
287
- return err.message.includes('context');
288
- },
289
- });
290
- if (this.options.restart && !this.options.manualStart) return this._startBrowser();
291
- if (!this.isRunning && !this.options.manualStart) return this._startBrowser();
292
- return this.browser;
293
- }
294
-
295
- async _after() {
296
- if (!this.isRunning) return;
297
-
298
- // close other sessions
299
- const contexts = this.browser.browserContexts();
300
- const defaultCtx = contexts.shift();
301
-
302
- await Promise.all(contexts.map(c => c.close()));
303
-
304
- if (this.options.restart) {
305
- this.isRunning = false;
306
- return this._stopBrowser();
307
- }
308
-
309
- // ensure this.page is from default context
310
- if (this.page) {
311
- const existingPages = defaultCtx.targets().filter(t => t.type() === 'page');
312
- await this._setPage(await existingPages[0].page());
313
- }
314
-
315
- if (this.options.keepBrowserState) return;
316
-
317
- if (!this.options.keepCookies) {
318
- this.debugSection('Session', 'cleaning cookies and localStorage');
319
- await this.clearCookie();
320
- }
321
- const currentUrl = await this.grabCurrentUrl();
322
-
323
- if (currentUrl.startsWith('http')) {
324
- await this.executeScript('localStorage.clear();').catch((err) => {
325
- if (!(err.message.indexOf("Storage is disabled inside 'data:' URLs.") > -1)) throw err;
326
- });
327
- await this.executeScript('sessionStorage.clear();').catch((err) => {
328
- if (!(err.message.indexOf("Storage is disabled inside 'data:' URLs.") > -1)) throw err;
329
- });
330
- }
331
- await this.closeOtherTabs();
332
- return this.browser;
333
- }
334
-
335
- _afterSuite() {
336
- }
337
-
338
- _finishTest() {
339
- if (!this.options.restart && this.isRunning) return this._stopBrowser();
340
- }
341
-
342
- _session() {
343
- return {
344
- start: async (name = '') => {
345
- this.debugSection('Incognito Tab', 'opened');
346
- this.activeSessionName = name;
347
-
348
- const bc = await this.browser.createIncognitoBrowserContext();
349
- await bc.newPage();
350
-
351
- // Create a new page inside context.
352
- return bc;
353
- },
354
- stop: async () => {
355
- // is closed by _after
356
- },
357
- loadVars: async (context) => {
358
- const existingPages = context.targets().filter(t => t.type() === 'page');
359
- this.sessionPages[this.activeSessionName] = await existingPages[0].page();
360
- return this._setPage(this.sessionPages[this.activeSessionName]);
361
- },
362
- restoreVars: async (session) => {
363
- this.withinLocator = null;
364
-
365
- if (!session) {
366
- this.activeSessionName = '';
367
- } else {
368
- this.activeSessionName = session;
369
- }
370
- const defaultCtx = this.browser.defaultBrowserContext();
371
- const existingPages = defaultCtx.targets().filter(t => t.type() === 'page');
372
- await this._setPage(await existingPages[0].page());
373
-
374
- return this._waitForAction();
375
- },
376
- };
377
- }
378
-
379
- /**
380
- * Use Puppeteer API inside a test.
381
- *
382
- * First argument is a description of an action.
383
- * Second argument is async function that gets this helper as parameter.
384
- *
385
- * { [`page`](https://github.com/puppeteer/puppeteer/blob/master/docs/api.md#class-page), [`browser`](https://github.com/puppeteer/puppeteer/blob/master/docs/api.md#class-browser) } from Puppeteer API are available.
386
- *
387
- * ```js
388
- * I.usePuppeteerTo('emulate offline mode', async ({ page }) {
389
- * await page.setOfflineMode(true);
390
- * });
391
- * ```
392
- *
393
- * @param {string} description used to show in logs.
394
- * @param {function} fn async function that is executed with Puppeteer as argument
395
- */
396
- usePuppeteerTo(description, fn) {
397
- return this._useTo(...arguments);
398
- }
399
-
400
- /**
401
- * Set the automatic popup response to Accept.
402
- * This must be set before a popup is triggered.
403
- *
404
- * ```js
405
- * I.amAcceptingPopups();
406
- * I.click('#triggerPopup');
407
- * I.acceptPopup();
408
- * ```
409
- */
410
- amAcceptingPopups() {
411
- popupStore.actionType = 'accept';
412
- }
413
-
414
- /**
415
- * Accepts the active JavaScript native popup window, as created by window.alert|window.confirm|window.prompt.
416
- * Don't confuse popups with modal windows, as created by [various
417
- * libraries](http://jster.net/category/windows-modals-popups).
418
- */
419
- acceptPopup() {
420
- popupStore.assertPopupActionType('accept');
421
- }
422
-
423
- /**
424
- * Set the automatic popup response to Cancel/Dismiss.
425
- * This must be set before a popup is triggered.
426
- *
427
- * ```js
428
- * I.amCancellingPopups();
429
- * I.click('#triggerPopup');
430
- * I.cancelPopup();
431
- * ```
432
- */
433
- amCancellingPopups() {
434
- popupStore.actionType = 'cancel';
435
- }
436
-
437
- /**
438
- * Dismisses the active JavaScript popup, as created by window.alert|window.confirm|window.prompt.
439
- */
440
- cancelPopup() {
441
- popupStore.assertPopupActionType('cancel');
442
- }
443
-
444
- /**
445
- * Checks that the active JavaScript popup, as created by `window.alert|window.confirm|window.prompt`, contains the
446
- * given string.
447
- *
448
- * ```js
449
- * I.seeInPopup('Popup text');
450
- * ```
451
- * @param {string} text value to check.
452
- * ⚠️ returns a _promise_ which is synchronized internally by recorder
453
- *
454
- */
455
- async seeInPopup(text) {
456
- popupStore.assertPopupVisible();
457
- const popupText = await popupStore.popup.message();
458
- stringIncludes('text in popup').assert(text, popupText);
459
- }
460
-
461
- /**
462
- * Set current page
463
- * @param {object} page page to set
464
- */
465
- async _setPage(page) {
466
- page = await page;
467
- this._addPopupListener(page);
468
- this._addErrorListener(page);
469
- this.page = page;
470
- if (!page) return;
471
- page.setDefaultNavigationTimeout(this.options.getPageTimeout);
472
- this.context = await this.page.$('body');
473
- if (this.config.browser === 'chrome') {
474
- await page.bringToFront();
475
- }
476
- }
477
-
478
- async _addErrorListener(page) {
479
- if (!page) {
480
- return;
481
- }
482
- page.on('error', async (error) => {
483
- console.error('Puppeteer page error', error);
484
- });
485
- }
486
-
487
- /**
488
- * Add the 'dialog' event listener to a page
489
- * @page {Puppeteer.Page}
490
- *
491
- * The popup listener handles the dialog with the predefined action when it appears on the page.
492
- * It also saves a reference to the object which is used in seeInPopup.
493
- */
494
- _addPopupListener(page) {
495
- if (!page) {
496
- return;
497
- }
498
- page.on('dialog', async (dialog) => {
499
- popupStore.popup = dialog;
500
- const action = popupStore.actionType || this.options.defaultPopupAction;
501
- await this._waitForAction();
502
-
503
- switch (action) {
504
- case 'accept':
505
- return dialog.accept();
506
-
507
- case 'cancel':
508
- return dialog.dismiss();
509
-
510
- default: {
511
- throw new Error('Unknown popup action type. Only "accept" or "cancel" are accepted');
512
- }
513
- }
514
- });
515
- }
516
-
517
- /**
518
- * Gets page URL including hash.
519
- */
520
- async _getPageUrl() {
521
- return this.executeScript(() => window.location.href);
522
- }
523
-
524
- /**
525
- * Grab the text within the popup. If no popup is visible then it will return null
526
- *
527
- * ```js
528
- * await I.grabPopupText();
529
- * ```
530
- * @return {Promise<string | null>}
531
- */
532
- async grabPopupText() {
533
- if (popupStore.popup) {
534
- return popupStore.popup.message();
535
- }
536
- return null;
537
- }
538
-
539
- async _startBrowser() {
540
- if (this.isRemoteBrowser) {
541
- try {
542
- this.browser = await puppeteer.connect(this.puppeteerOptions);
543
- } catch (err) {
544
- if (err.toString().indexOf('ECONNREFUSED')) {
545
- throw new RemoteBrowserConnectionRefused(err);
546
- }
547
- throw err;
548
- }
549
- } else {
550
- this.browser = await puppeteer.launch(this.puppeteerOptions);
551
- }
552
-
553
- this.browser.on('targetcreated', target => target.page().then(page => targetCreatedHandler.call(this, page)).catch((e) => {
554
- console.error('Puppeteer page error', e);
555
- }));
556
- this.browser.on('targetchanged', (target) => {
557
- this.debugSection('Url', target.url());
558
- });
559
-
560
- const existingPages = await this.browser.pages();
561
- const mainPage = existingPages[0] || await this.browser.newPage();
562
-
563
- if (existingPages.length) {
564
- // Run the handler as it will not be triggered if the page already exists
565
- targetCreatedHandler.call(this, mainPage);
566
- }
567
- await this._setPage(mainPage);
568
- await this.closeOtherTabs();
569
-
570
- this.isRunning = true;
571
- }
572
-
573
- async _stopBrowser() {
574
- this.withinLocator = null;
575
- this._setPage(null);
576
- this.context = null;
577
- popupStore.clear();
578
- this.isAuthenticated = false;
579
- await this.browser.close();
580
- if (this.isRemoteBrowser) {
581
- await this.browser.disconnect();
582
- }
583
- }
584
-
585
- async _evaluateHandeInContext(...args) {
586
- let context = await this._getContext();
587
-
588
- if (context.constructor.name === 'Frame') {
589
- // Currently there is no evalateHandle for the Frame object
590
- // https://github.com/GoogleChrome/puppeteer/issues/1051
591
- context = await context.executionContext();
592
- }
593
-
594
- return context.evaluateHandle(...args);
595
- }
596
-
597
- async _withinBegin(locator) {
598
- if (this.withinLocator) {
599
- throw new Error('Can\'t start within block inside another within block');
600
- }
601
-
602
- const frame = isFrameLocator(locator);
603
-
604
- if (frame) {
605
- if (Array.isArray(frame)) {
606
- return this.switchTo(null)
607
- .then(() => frame.reduce((p, frameLocator) => p.then(() => this.switchTo(frameLocator)), Promise.resolve()));
608
- }
609
- await this.switchTo(locator);
610
- this.withinLocator = new Locator(locator);
611
- return;
612
- }
613
-
614
- const els = await this._locate(locator);
615
- assertElementExists(els, locator);
616
- this.context = els[0];
617
-
618
- this.withinLocator = new Locator(locator);
619
- }
620
-
621
- async _withinEnd() {
622
- this.withinLocator = null;
623
- this.context = await this.page.mainFrame().$('body');
624
- }
625
-
626
- _extractDataFromPerformanceTiming(timing, ...dataNames) {
627
- const navigationStart = timing.navigationStart;
628
-
629
- const extractedData = {};
630
- dataNames.forEach((name) => {
631
- extractedData[name] = timing[name] - navigationStart;
632
- });
633
-
634
- return extractedData;
635
- }
636
-
637
- /**
638
- * Opens a web page in a browser. Requires relative or absolute url.
639
- * If url starts with `/`, opens a web page of a site defined in `url` config parameter.
640
- *
641
- * ```js
642
- * I.amOnPage('/'); // opens main page of website
643
- * I.amOnPage('https://github.com'); // opens github
644
- * I.amOnPage('/login'); // opens a login page
645
- * ```
646
- *
647
- * @param {string} url url path or global url.
648
- * @return {void} automatically synchronized promise with recorder #!
649
- */
650
- async amOnPage(url) {
651
- if (!(/^\w+\:\/\//.test(url))) {
652
- url = this.options.url + url;
653
- }
654
-
655
- if (this.config.basicAuth && (this.isAuthenticated !== true)) {
656
- if (url.includes(this.options.url)) {
657
- await this.page.authenticate(this.config.basicAuth);
658
- this.isAuthenticated = true;
659
- }
660
- }
661
-
662
- await this.page.goto(url, { waitUntil: this.options.waitForNavigation });
663
-
664
- const performanceTiming = JSON.parse(await this.page.evaluate(() => JSON.stringify(window.performance.timing)));
665
-
666
- perfTiming = this._extractDataFromPerformanceTiming(
667
- performanceTiming,
668
- 'responseEnd',
669
- 'domInteractive',
670
- 'domContentLoadedEventEnd',
671
- 'loadEventEnd',
672
- );
673
-
674
- return this._waitForAction();
675
- }
676
-
677
- /**
678
- * Resize the current window to provided width and height.
679
- * First parameter can be set to `maximize`.
680
- *
681
- * @param {number} width width in pixels or `maximize`.
682
- * @param {number} height height in pixels.
683
- * ⚠️ returns a _promise_ which is synchronized internally by recorder
684
- *
685
- *
686
- * Unlike other drivers Puppeteer changes the size of a viewport, not the window!
687
- * Puppeteer does not control the window of a browser so it can't adjust its real size.
688
- * It also can't maximize a window.
689
- */
690
- async resizeWindow(width, height) {
691
- if (width === 'maximize') {
692
- throw new Error('Puppeteer can\'t control windows, so it can\'t maximize it');
693
- }
694
-
695
- await this.page.setViewport({ width, height });
696
- return this._waitForAction();
697
- }
698
-
699
- /**
700
- * Set headers for all next requests
701
- *
702
- * ```js
703
- * I.haveRequestHeaders({
704
- * 'X-Sent-By': 'CodeceptJS',
705
- * });
706
- * ```
707
- *
708
- * @param {object} customHeaders headers to set
709
- */
710
- async haveRequestHeaders(customHeaders) {
711
- if (!customHeaders) {
712
- throw new Error('Cannot send empty headers.');
713
- }
714
- return this.page.setExtraHTTPHeaders(customHeaders);
715
- }
716
-
717
- /**
718
- * Moves cursor to element matched by locator.
719
- * Extra shift can be set with offsetX and offsetY options.
720
- *
721
- * ```js
722
- * I.moveCursorTo('.tooltip');
723
- * I.moveCursorTo('#submit', 5,5);
724
- * ```
725
- *
726
- * @param {CodeceptJS.LocatorOrString} locator located by CSS|XPath|strict locator.
727
- * @param {number} [offsetX=0] (optional, `0` by default) X-axis offset.
728
- * @param {number} [offsetY=0] (optional, `0` by default) Y-axis offset.
729
- * ⚠️ returns a _promise_ which is synchronized internally by recorder
730
- *
731
- * {{ react }}
732
- */
733
- async moveCursorTo(locator, offsetX = 0, offsetY = 0) {
734
- const els = await this._locate(locator);
735
- assertElementExists(els, locator);
736
-
737
- // Use manual mouse.move instead of .hover() so the offset can be added to the coordinates
738
- const { x, y } = await getClickablePoint(els[0]);
739
- await this.page.mouse.move(x + offsetX, y + offsetY);
740
- return this._waitForAction();
741
- }
742
-
743
- /**
744
- * Drag an item to a destination element.
745
- *
746
- * ```js
747
- * I.dragAndDrop('#dragHandle', '#container');
748
- * ```
749
- *
750
- * @param {LocatorOrString} srcElement located by CSS|XPath|strict locator.
751
- * @param {LocatorOrString} destElement located by CSS|XPath|strict locator.
752
- * ⚠️ returns a _promise_ which is synchronized internally by recorder
753
- *
754
- */
755
- async dragAndDrop(srcElement, destElement) {
756
- return proceedDragAndDrop.call(this, srcElement, destElement);
757
- }
758
-
759
- /**
760
- * Reload the current page.
761
- *
762
- * ```js
763
- * I.refreshPage();
764
- * ```
765
- * ⚠️ returns a _promise_ which is synchronized internally by recorder
766
- *
767
- */
768
- async refreshPage() {
769
- return this.page.reload({ timeout: this.options.getPageTimeout, waitUntil: this.options.waitForNavigation });
770
- }
771
-
772
- /**
773
- * Scroll page to the top.
774
- *
775
- * ```js
776
- * I.scrollPageToTop();
777
- * ```
778
- * ⚠️ returns a _promise_ which is synchronized internally by recorder
779
- *
780
- */
781
- scrollPageToTop() {
782
- return this.executeScript(() => {
783
- window.scrollTo(0, 0);
784
- });
785
- }
786
-
787
- /**
788
- * Scroll page to the bottom.
789
- *
790
- * ```js
791
- * I.scrollPageToBottom();
792
- * ```
793
- * ⚠️ returns a _promise_ which is synchronized internally by recorder
794
- *
795
- */
796
- scrollPageToBottom() {
797
- return this.executeScript(() => {
798
- const body = document.body;
799
- const html = document.documentElement;
800
- window.scrollTo(0, Math.max(
801
- body.scrollHeight, body.offsetHeight,
802
- html.clientHeight, html.scrollHeight, html.offsetHeight,
803
- ));
804
- });
805
- }
806
-
807
- /**
808
- * Scrolls to element matched by locator.
809
- * Extra shift can be set with offsetX and offsetY options.
810
- *
811
- * ```js
812
- * I.scrollTo('footer');
813
- * I.scrollTo('#submit', 5, 5);
814
- * ```
815
- *
816
- * @param {CodeceptJS.LocatorOrString} locator located by CSS|XPath|strict locator.
817
- * @param {number} [offsetX=0] (optional, `0` by default) X-axis offset.
818
- * @param {number} [offsetY=0] (optional, `0` by default) Y-axis offset.
819
- * ⚠️ returns a _promise_ which is synchronized internally by recorder
820
- *
821
- */
822
- async scrollTo(locator, offsetX = 0, offsetY = 0) {
823
- if (typeof locator === 'number' && typeof offsetX === 'number') {
824
- offsetY = offsetX;
825
- offsetX = locator;
826
- locator = null;
827
- }
828
-
829
- if (locator) {
830
- const els = await this._locate(locator);
831
- assertElementExists(els, locator, 'Element');
832
- const el = els[0];
833
- await el.evaluate((el) => el.scrollIntoView());
834
- const elementCoordinates = await getClickablePoint(els[0]);
835
- await this.executeScript((x, y) => window.scrollBy(x, y), elementCoordinates.x + offsetX, elementCoordinates.y + offsetY);
836
- } else {
837
- await this.executeScript((x, y) => window.scrollTo(x, y), offsetX, offsetY);
838
- }
839
- return this._waitForAction();
840
- }
841
-
842
- /**
843
- * Checks that title contains text.
844
- *
845
- * ```js
846
- * I.seeInTitle('Home Page');
847
- * ```
848
- *
849
- * @param {string} text text value to check.
850
- * ⚠️ returns a _promise_ which is synchronized internally by recorder
851
- *
852
- */
853
- async seeInTitle(text) {
854
- const title = await this.page.title();
855
- stringIncludes('web page title').assert(text, title);
856
- }
857
-
858
- /**
859
- * Retrieves a page scroll position and returns it to test.
860
- * Resumes test execution, so **should be used inside an async function with `await`** operator.
861
- *
862
- * ```js
863
- * let { x, y } = await I.grabPageScrollPosition();
864
- * ```
865
- *
866
- * @returns {Promise<PageScrollPosition>} scroll position
867
- *
868
- */
869
- async grabPageScrollPosition() {
870
- /* eslint-disable comma-dangle */
871
- function getScrollPosition() {
872
- return {
873
- x: window.pageXOffset,
874
- y: window.pageYOffset
875
- };
876
- }
877
- /* eslint-enable comma-dangle */
878
- return this.executeScript(getScrollPosition);
879
- }
880
-
881
- /**
882
- * Checks that title is equal to provided one.
883
- *
884
- * ```js
885
- * I.seeTitleEquals('Test title.');
886
- * ```
887
- *
888
- * @param {string} text value to check.
889
- * ⚠️ returns a _promise_ which is synchronized internally by recorder
890
- *
891
- */
892
- async seeTitleEquals(text) {
893
- const title = await this.page.title();
894
- return equals('web page title').assert(title, text);
895
- }
896
-
897
- /**
898
- * Checks that title does not contain text.
899
- *
900
- * ```js
901
- * I.dontSeeInTitle('Error');
902
- * ```
903
- *
904
- * @param {string} text value to check.
905
- * ⚠️ returns a _promise_ which is synchronized internally by recorder
906
- *
907
- */
908
- async dontSeeInTitle(text) {
909
- const title = await this.page.title();
910
- stringIncludes('web page title').negate(text, title);
911
- }
912
-
913
- /**
914
- * Retrieves a page title and returns it to test.
915
- * Resumes test execution, so **should be used inside async with `await`** operator.
916
- *
917
- * ```js
918
- * let title = await I.grabTitle();
919
- * ```
920
- *
921
- * @returns {Promise<string>} title
922
- */
923
- async grabTitle() {
924
- return this.page.title();
925
- }
926
-
927
- /**
928
- * Get elements by different locator types, including strict locator
929
- * Should be used in custom helpers:
930
- *
931
- * ```js
932
- * const elements = await this.helpers['Puppeteer']._locate({name: 'password'});
933
- * ```
934
- *
935
- * {{ react }}
936
- */
937
- async _locate(locator) {
938
- return findElements(await this.context, locator);
939
- }
940
-
941
- /**
942
- * Find a checkbox by providing human readable text:
943
- * NOTE: Assumes the checkable element exists
944
- *
945
- * ```js
946
- * this.helpers['Puppeteer']._locateCheckable('I agree with terms and conditions').then // ...
947
- * ```
948
- */
949
- async _locateCheckable(locator, providedContext = null) {
950
- const context = providedContext || await this._getContext();
951
- const els = await findCheckable.call(this, locator, context);
952
- assertElementExists(els[0], locator, 'Checkbox or radio');
953
- return els[0];
954
- }
955
-
956
- /**
957
- * Find a clickable element by providing human readable text:
958
- *
959
- * ```js
960
- * this.helpers['Puppeteer']._locateClickable('Next page').then // ...
961
- * ```
962
- */
963
- async _locateClickable(locator) {
964
- const context = await this._getContext();
965
- return findClickable.call(this, context, locator);
966
- }
967
-
968
- /**
969
- * Find field elements by providing human readable text:
970
- *
971
- * ```js
972
- * this.helpers['Puppeteer']._locateFields('Your email').then // ...
973
- * ```
974
- */
975
- async _locateFields(locator) {
976
- return findFields.call(this, locator);
977
- }
978
-
979
- /**
980
- * Switch focus to a particular tab by its number. It waits tabs loading and then switch tab
981
- *
982
- * ```js
983
- * I.switchToNextTab();
984
- * I.switchToNextTab(2);
985
- * ```
986
- *
987
- * @param {number} [num=1]
988
- */
989
- async switchToNextTab(num = 1) {
990
- const pages = await this.browser.pages();
991
- const index = pages.indexOf(this.page);
992
- this.withinLocator = null;
993
- const page = pages[index + num];
994
-
995
- if (!page) {
996
- throw new Error(`There is no ability to switch to next tab with offset ${num}`);
997
- }
998
-
999
- await this._setPage(page);
1000
- return this._waitForAction();
1001
- }
1002
-
1003
- /**
1004
- * Switch focus to a particular tab by its number. It waits tabs loading and then switch tab
1005
- *
1006
- * ```js
1007
- * I.switchToPreviousTab();
1008
- * I.switchToPreviousTab(2);
1009
- * ```
1010
- * @param {number} [num=1]
1011
- */
1012
- async switchToPreviousTab(num = 1) {
1013
- const pages = await this.browser.pages();
1014
- const index = pages.indexOf(this.page);
1015
- this.withinLocator = null;
1016
- const page = pages[index - num];
1017
-
1018
- if (!page) {
1019
- throw new Error(`There is no ability to switch to previous tab with offset ${num}`);
1020
- }
1021
-
1022
- await this._setPage(page);
1023
- return this._waitForAction();
1024
- }
1025
-
1026
- /**
1027
- * Close current tab and switches to previous.
1028
- *
1029
- * ```js
1030
- * I.closeCurrentTab();
1031
- * ```
1032
- */
1033
- async closeCurrentTab() {
1034
- const oldPage = this.page;
1035
- await this.switchToPreviousTab();
1036
- await oldPage.close();
1037
- return this._waitForAction();
1038
- }
1039
-
1040
- /**
1041
- * Close all tabs except for the current one.
1042
- *
1043
- * ```js
1044
- * I.closeOtherTabs();
1045
- * ```
1046
- */
1047
- async closeOtherTabs() {
1048
- const pages = await this.browser.pages();
1049
- const otherPages = pages.filter(page => page !== this.page);
1050
-
1051
- let p = Promise.resolve();
1052
- otherPages.forEach((page) => {
1053
- p = p.then(() => page.close());
1054
- });
1055
- await p;
1056
- return this._waitForAction();
1057
- }
1058
-
1059
- /**
1060
- * Open new tab and switch to it
1061
- *
1062
- * ```js
1063
- * I.openNewTab();
1064
- * ```
1065
- */
1066
- async openNewTab() {
1067
- await this._setPage(await this.browser.newPage());
1068
- return this._waitForAction();
1069
- }
1070
-
1071
- /**
1072
- * Grab number of open tabs.
1073
- * Resumes test execution, so **should be used inside async function with `await`** operator.
1074
- *
1075
- * ```js
1076
- * let tabs = await I.grabNumberOfOpenTabs();
1077
- * ```
1078
- *
1079
- * @returns {Promise<number>} number of open tabs
1080
- *
1081
- */
1082
- async grabNumberOfOpenTabs() {
1083
- const pages = await this.browser.pages();
1084
- return pages.length;
1085
- }
1086
-
1087
- /**
1088
- * Checks that a given Element is visible
1089
- * Element is located by CSS or XPath.
1090
- *
1091
- * ```js
1092
- * I.seeElement('#modal');
1093
- * ```
1094
- * @param {CodeceptJS.LocatorOrString} locator located by CSS|XPath|strict locator.
1095
- * ⚠️ returns a _promise_ which is synchronized internally by recorder
1096
- *
1097
- * {{ react }}
1098
- */
1099
- async seeElement(locator) {
1100
- let els = await this._locate(locator);
1101
- els = (await Promise.all(els.map(el => el.boundingBox() && el))).filter(v => v);
1102
- // Puppeteer visibility was ignored? | Remove when Puppeteer is fixed
1103
- els = await Promise.all(els.map(async el => (await el.evaluate(node => window.getComputedStyle(node).visibility !== 'hidden' && window.getComputedStyle(node).display !== 'none')) && el));
1104
-
1105
- return empty('visible elements').negate(els.filter(v => v).fill('ELEMENT'));
1106
- }
1107
-
1108
- /**
1109
- * Opposite to `seeElement`. Checks that element is not visible (or in DOM)
1110
- *
1111
- * ```js
1112
- * I.dontSeeElement('.modal'); // modal is not shown
1113
- * ```
1114
- *
1115
- * @param {CodeceptJS.LocatorOrString} locator located by CSS|XPath|Strict locator.
1116
- * ⚠️ returns a _promise_ which is synchronized internally by recorder
1117
- *
1118
- * {{ react }}
1119
- */
1120
- async dontSeeElement(locator) {
1121
- let els = await this._locate(locator);
1122
- els = (await Promise.all(els.map(el => el.boundingBox() && el))).filter(v => v);
1123
- // Puppeteer visibility was ignored? | Remove when Puppeteer is fixed
1124
- els = await Promise.all(els.map(async el => (await el.evaluate(node => window.getComputedStyle(node).visibility !== 'hidden' && window.getComputedStyle(node).display !== 'none')) && el));
1125
-
1126
- return empty('visible elements').assert(els.filter(v => v).fill('ELEMENT'));
1127
- }
1128
-
1129
- /**
1130
- * Checks that a given Element is present in the DOM
1131
- * Element is located by CSS or XPath.
1132
- *
1133
- * ```js
1134
- * I.seeElementInDOM('#modal');
1135
- * ```
1136
- * @param {CodeceptJS.LocatorOrString} locator element located by CSS|XPath|strict locator.
1137
- * ⚠️ returns a _promise_ which is synchronized internally by recorder
1138
- *
1139
- */
1140
- async seeElementInDOM(locator) {
1141
- const els = await this._locate(locator);
1142
- return empty('elements on page').negate(els.filter(v => v).fill('ELEMENT'));
1143
- }
1144
-
1145
- /**
1146
- * Opposite to `seeElementInDOM`. Checks that element is not on page.
1147
- *
1148
- * ```js
1149
- * I.dontSeeElementInDOM('.nav'); // checks that element is not on page visible or not
1150
- * ```
1151
- *
1152
- * @param {CodeceptJS.LocatorOrString} locator located by CSS|XPath|Strict locator.
1153
- * ⚠️ returns a _promise_ which is synchronized internally by recorder
1154
- *
1155
- */
1156
- async dontSeeElementInDOM(locator) {
1157
- const els = await this._locate(locator);
1158
- return empty('elements on a page').assert(els.filter(v => v).fill('ELEMENT'));
1159
- }
1160
-
1161
- /**
1162
- * Perform a click on a link or a button, given by a locator.
1163
- * If a fuzzy locator is given, the page will be searched for a button, link, or image matching the locator string.
1164
- * For buttons, the "value" attribute, "name" attribute, and inner text are searched. For links, the link text is searched.
1165
- * For images, the "alt" attribute and inner text of any parent links are searched.
1166
- *
1167
- * The second parameter is a context (CSS or XPath locator) to narrow the search.
1168
- *
1169
- * ```js
1170
- * // simple link
1171
- * I.click('Logout');
1172
- * // button of form
1173
- * I.click('Submit');
1174
- * // CSS button
1175
- * I.click('#form input[type=submit]');
1176
- * // XPath
1177
- * I.click('//form/*[@type=submit]');
1178
- * // link in context
1179
- * I.click('Logout', '#nav');
1180
- * // using strict locator
1181
- * I.click({css: 'nav a.login'});
1182
- * ```
1183
- *
1184
- * @param {CodeceptJS.LocatorOrString} locator clickable link or button located by text, or any element located by CSS|XPath|strict locator.
1185
- * @param {?CodeceptJS.LocatorOrString | null} [context=null] (optional, `null` by default) element to search in CSS|XPath|Strict locator.
1186
- * ⚠️ returns a _promise_ which is synchronized internally by recorder
1187
- *
1188
- *
1189
- * {{ react }}
1190
- */
1191
- async click(locator, context = null) {
1192
- return proceedClick.call(this, locator, context);
1193
- }
1194
-
1195
- /**
1196
- * Perform an emulated click on a link or a button, given by a locator.
1197
- * Unlike normal click instead of sending native event, emulates a click with JavaScript.
1198
- * This works on hidden, animated or inactive elements as well.
1199
- *
1200
- * If a fuzzy locator is given, the page will be searched for a button, link, or image matching the locator string.
1201
- * For buttons, the "value" attribute, "name" attribute, and inner text are searched. For links, the link text is searched.
1202
- * For images, the "alt" attribute and inner text of any parent links are searched.
1203
- *
1204
- * The second parameter is a context (CSS or XPath locator) to narrow the search.
1205
- *
1206
- * ```js
1207
- * // simple link
1208
- * I.forceClick('Logout');
1209
- * // button of form
1210
- * I.forceClick('Submit');
1211
- * // CSS button
1212
- * I.forceClick('#form input[type=submit]');
1213
- * // XPath
1214
- * I.forceClick('//form/*[@type=submit]');
1215
- * // link in context
1216
- * I.forceClick('Logout', '#nav');
1217
- * // using strict locator
1218
- * I.forceClick({css: 'nav a.login'});
1219
- * ```
1220
- *
1221
- * @param {CodeceptJS.LocatorOrString} locator clickable link or button located by text, or any element located by CSS|XPath|strict locator.
1222
- * @param {?CodeceptJS.LocatorOrString} [context=null] (optional, `null` by default) element to search in CSS|XPath|Strict locator.
1223
- * ⚠️ returns a _promise_ which is synchronized internally by recorder
1224
- *
1225
- *
1226
- * {{ react }}
1227
- */
1228
- async forceClick(locator, context = null) {
1229
- let matcher = await this.context;
1230
- if (context) {
1231
- const els = await this._locate(context);
1232
- assertElementExists(els, context);
1233
- matcher = els[0];
1234
- }
1235
-
1236
- const els = await findClickable.call(this, matcher, locator);
1237
- if (context) {
1238
- assertElementExists(els, locator, 'Clickable element', `was not found inside element ${new Locator(context).toString()}`);
1239
- } else {
1240
- assertElementExists(els, locator, 'Clickable element');
1241
- }
1242
- const elem = els[0];
1243
- return this.executeScript((el) => {
1244
- if (document.activeElement instanceof HTMLElement) {
1245
- document.activeElement.blur();
1246
- }
1247
- const event = document.createEvent('MouseEvent');
1248
- event.initEvent('click', true, true);
1249
- return el.dispatchEvent(event);
1250
- }, elem);
1251
- }
1252
-
1253
- /**
1254
- * Performs a click on a link and waits for navigation before moving on.
1255
- *
1256
- * ```js
1257
- * I.clickLink('Logout', '#nav');
1258
- * ```
1259
- * @param {CodeceptJS.LocatorOrString} locator clickable link or button located by text, or any element located by CSS|XPath|strict locator
1260
- * @param {?CodeceptJS.LocatorOrString} [context=null] (optional, `null` by default) element to search in CSS|XPath|Strict locator
1261
- * ⚠️ returns a _promise_ which is synchronized internally by recorder
1262
- *
1263
- *
1264
- * {{ react }}
1265
- */
1266
- async clickLink(locator, context = null) {
1267
- return proceedClick.call(this, locator, context, { waitForNavigation: true });
1268
- }
1269
-
1270
- /**
1271
- * Sets a directory to where save files. Allows to test file downloads.
1272
- * Should be used with [FileSystem helper](https://codecept.io/helpers/FileSystem) to check that file were downloaded correctly.
1273
- *
1274
- * By default files are saved to `output/downloads`.
1275
- * This directory is cleaned on every `handleDownloads` call, to ensure no old files are kept.
1276
- *
1277
- * ```js
1278
- * I.handleDownloads();
1279
- * I.click('Download Avatar');
1280
- * I.amInPath('output/downloads');
1281
- * I.seeFile('avatar.jpg');
1282
- *
1283
- * ```
1284
- *
1285
- * @param {string} [downloadPath='downloads'] change this parameter to set another directory for saving
1286
- */
1287
- async handleDownloads(downloadPath = 'downloads') {
1288
- downloadPath = path.join(global.output_dir, downloadPath);
1289
- if (!fs.existsSync(downloadPath)) {
1290
- fs.mkdirSync(downloadPath, '0777');
1291
- }
1292
- fsExtra.emptyDirSync(downloadPath);
1293
-
1294
- try {
1295
- return this.page._client.send('Page.setDownloadBehavior', { behavior: 'allow', downloadPath });
1296
- } catch (e) {
1297
- return this.page._client().send('Page.setDownloadBehavior', { behavior: 'allow', downloadPath });
1298
- }
1299
- }
1300
-
1301
- /**
1302
- * This method is **deprecated**.
1303
- *
1304
- * Please use `handleDownloads()` instead.
1305
- */
1306
- async downloadFile(locator, customName) {
1307
- let fileName;
1308
- await this.page.setRequestInterception(true);
1309
-
1310
- const xRequest = await new Promise((resolve) => {
1311
- this.page.on('request', (request) => {
1312
- console.log('rq', request, customName);
1313
- const grabbedFileName = request.url().split('/')[request.url().split('/').length - 1];
1314
- const fileExtension = request.url().split('/')[request.url().split('/').length - 1].split('.')[1];
1315
- console.log('nm', customName, fileExtension);
1316
- if (customName && path.extname(customName) !== fileExtension) {
1317
- console.log('bypassing a request');
1318
- request.continue();
1319
- return;
1320
- }
1321
- customName ? fileName = `${customName}.${fileExtension}` : fileName = grabbedFileName;
1322
- request.abort();
1323
- resolve(request);
1324
- });
1325
- });
1326
-
1327
- await this.click(locator);
1328
-
1329
- const options = {
1330
- encoding: null,
1331
- method: xRequest._method,
1332
- uri: xRequest._url,
1333
- body: xRequest._postData,
1334
- headers: xRequest._headers,
1335
- };
1336
-
1337
- const cookies = await this.page.cookies();
1338
- options.headers.Cookie = cookies.map(ck => `${ck.name}=${ck.value}`).join(';');
1339
-
1340
- const response = await axios({
1341
- method: options.method,
1342
- url: options.uri,
1343
- headers: options.headers,
1344
- responseType: 'arraybuffer',
1345
- onDownloadProgress(e) {
1346
- console.log('+', e);
1347
- },
1348
- });
1349
-
1350
- const outputFile = path.join(`${global.output_dir}/${fileName}`);
1351
-
1352
- try {
1353
- await new Promise((resolve, reject) => {
1354
- const wstream = fs.createWriteStream(outputFile);
1355
- console.log(response);
1356
- wstream.write(response.data);
1357
- wstream.end();
1358
- this.debug(`File is downloaded in ${outputFile}`);
1359
- wstream.on('finish', () => { resolve(fileName); });
1360
- wstream.on('error', reject);
1361
- });
1362
- } catch (error) {
1363
- throw new Error(`There is something wrong with downloaded file. ${error}`);
1364
- }
1365
- }
1366
-
1367
- /**
1368
- * Performs a double-click on an element matched by link|button|label|CSS or XPath.
1369
- * Context can be specified as second parameter to narrow search.
1370
- *
1371
- * ```js
1372
- * I.doubleClick('Edit');
1373
- * I.doubleClick('Edit', '.actions');
1374
- * I.doubleClick({css: 'button.accept'});
1375
- * I.doubleClick('.btn.edit');
1376
- * ```
1377
- *
1378
- * @param {CodeceptJS.LocatorOrString} locator clickable link or button located by text, or any element located by CSS|XPath|strict locator.
1379
- * @param {?CodeceptJS.LocatorOrString} [context=null] (optional, `null` by default) element to search in CSS|XPath|Strict locator.
1380
- * ⚠️ returns a _promise_ which is synchronized internally by recorder
1381
- *
1382
- *
1383
- * {{ react }}
1384
- */
1385
- async doubleClick(locator, context = null) {
1386
- return proceedClick.call(this, locator, context, { clickCount: 2 });
1387
- }
1388
-
1389
- /**
1390
- * Performs right click on a clickable element matched by semantic locator, CSS or XPath.
1391
- *
1392
- * ```js
1393
- * // right click element with id el
1394
- * I.rightClick('#el');
1395
- * // right click link or button with text "Click me"
1396
- * I.rightClick('Click me');
1397
- * // right click button with text "Click me" inside .context
1398
- * I.rightClick('Click me', '.context');
1399
- * ```
1400
- *
1401
- * @param {CodeceptJS.LocatorOrString} locator clickable element located by CSS|XPath|strict locator.
1402
- * @param {?CodeceptJS.LocatorOrString} [context=null] (optional, `null` by default) element located by CSS|XPath|strict locator.
1403
- * ⚠️ returns a _promise_ which is synchronized internally by recorder
1404
- *
1405
- *
1406
- * {{ react }}
1407
- */
1408
- async rightClick(locator, context = null) {
1409
- return proceedClick.call(this, locator, context, { button: 'right' });
1410
- }
1411
-
1412
- /**
1413
- * Selects a checkbox or radio button.
1414
- * Element is located by label or name or CSS or XPath.
1415
- *
1416
- * The second parameter is a context (CSS or XPath locator) to narrow the search.
1417
- *
1418
- * ```js
1419
- * I.checkOption('#agree');
1420
- * I.checkOption('I Agree to Terms and Conditions');
1421
- * I.checkOption('agree', '//form');
1422
- * ```
1423
- * @param {CodeceptJS.LocatorOrString} field checkbox located by label | name | CSS | XPath | strict locator.
1424
- * @param {?CodeceptJS.LocatorOrString} [context=null] (optional, `null` by default) element located by CSS | XPath | strict locator.
1425
- * ⚠️ returns a _promise_ which is synchronized internally by recorder
1426
- *
1427
- */
1428
- async checkOption(field, context = null) {
1429
- const elm = await this._locateCheckable(field, context);
1430
- const curentlyChecked = await elm.getProperty('checked')
1431
- .then(checkedProperty => checkedProperty.jsonValue());
1432
- // Only check if NOT currently checked
1433
- if (!curentlyChecked) {
1434
- await elm.click();
1435
- return this._waitForAction();
1436
- }
1437
- }
1438
-
1439
- /**
1440
- * Unselects a checkbox or radio button.
1441
- * Element is located by label or name or CSS or XPath.
1442
- *
1443
- * The second parameter is a context (CSS or XPath locator) to narrow the search.
1444
- *
1445
- * ```js
1446
- * I.uncheckOption('#agree');
1447
- * I.uncheckOption('I Agree to Terms and Conditions');
1448
- * I.uncheckOption('agree', '//form');
1449
- * ```
1450
- * @param {CodeceptJS.LocatorOrString} field checkbox located by label | name | CSS | XPath | strict locator.
1451
- * @param {?CodeceptJS.LocatorOrString} [context=null] (optional, `null` by default) element located by CSS | XPath | strict locator.
1452
- * ⚠️ returns a _promise_ which is synchronized internally by recorder
1453
- *
1454
- */
1455
- async uncheckOption(field, context = null) {
1456
- const elm = await this._locateCheckable(field, context);
1457
- const curentlyChecked = await elm.getProperty('checked')
1458
- .then(checkedProperty => checkedProperty.jsonValue());
1459
- // Only uncheck if currently checked
1460
- if (curentlyChecked) {
1461
- await elm.click();
1462
- return this._waitForAction();
1463
- }
1464
- }
1465
-
1466
- /**
1467
- * Verifies that the specified checkbox is checked.
1468
- *
1469
- * ```js
1470
- * I.seeCheckboxIsChecked('Agree');
1471
- * I.seeCheckboxIsChecked('#agree'); // I suppose user agreed to terms
1472
- * I.seeCheckboxIsChecked({css: '#signup_form input[type=checkbox]'});
1473
- * ```
1474
- *
1475
- * @param {CodeceptJS.LocatorOrString} field located by label|name|CSS|XPath|strict locator.
1476
- * ⚠️ returns a _promise_ which is synchronized internally by recorder
1477
- *
1478
- */
1479
- async seeCheckboxIsChecked(field) {
1480
- return proceedIsChecked.call(this, 'assert', field);
1481
- }
1482
-
1483
- /**
1484
- * Verifies that the specified checkbox is not checked.
1485
- *
1486
- * ```js
1487
- * I.dontSeeCheckboxIsChecked('#agree'); // located by ID
1488
- * I.dontSeeCheckboxIsChecked('I agree to terms'); // located by label
1489
- * I.dontSeeCheckboxIsChecked('agree'); // located by name
1490
- * ```
1491
- *
1492
- * @param {CodeceptJS.LocatorOrString} field located by label|name|CSS|XPath|strict locator.
1493
- * ⚠️ returns a _promise_ which is synchronized internally by recorder
1494
- *
1495
- */
1496
- async dontSeeCheckboxIsChecked(field) {
1497
- return proceedIsChecked.call(this, 'negate', field);
1498
- }
1499
-
1500
- /**
1501
- * Presses a key in the browser and leaves it in a down state.
1502
- *
1503
- * To make combinations with modifier key and user operation (e.g. `'Control'` + [`click`](#click)).
1504
- *
1505
- * ```js
1506
- * I.pressKeyDown('Control');
1507
- * I.click('#element');
1508
- * I.pressKeyUp('Control');
1509
- * ```
1510
- *
1511
- * @param {string} key name of key to press down.
1512
- * ⚠️ returns a _promise_ which is synchronized internally by recorder
1513
- *
1514
- */
1515
- async pressKeyDown(key) {
1516
- key = getNormalizedKey.call(this, key);
1517
- await this.page.keyboard.down(key);
1518
- return this._waitForAction();
1519
- }
1520
-
1521
- /**
1522
- * Releases a key in the browser which was previously set to a down state.
1523
- *
1524
- * To make combinations with modifier key and user operation (e.g. `'Control'` + [`click`](#click)).
1525
- *
1526
- * ```js
1527
- * I.pressKeyDown('Control');
1528
- * I.click('#element');
1529
- * I.pressKeyUp('Control');
1530
- * ```
1531
- *
1532
- * @param {string} key name of key to release.
1533
- * ⚠️ returns a _promise_ which is synchronized internally by recorder
1534
- *
1535
- */
1536
- async pressKeyUp(key) {
1537
- key = getNormalizedKey.call(this, key);
1538
- await this.page.keyboard.up(key);
1539
- return this._waitForAction();
1540
- }
1541
-
1542
- /**
1543
- * Presses a key in the browser (on a focused element).
1544
- *
1545
- * _Hint:_ For populating text field or textarea, it is recommended to use [`fillField`](#fillfield).
1546
- *
1547
- * ```js
1548
- * I.pressKey('Backspace');
1549
- * ```
1550
- *
1551
- * 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.
1552
- *
1553
- * ```js
1554
- * I.pressKey(['Control', 'Z']);
1555
- * ```
1556
- *
1557
- * For specifying operation modifier key based on operating system it is suggested to use `'CommandOrControl'`.
1558
- * This will press `'Command'` (also known as `'Meta'`) on macOS machines and `'Control'` on non-macOS machines.
1559
- *
1560
- * ```js
1561
- * I.pressKey(['CommandOrControl', 'Z']);
1562
- * ```
1563
- *
1564
- * Some of the supported key names are:
1565
- * - `'AltLeft'` or `'Alt'`
1566
- * - `'AltRight'`
1567
- * - `'ArrowDown'`
1568
- * - `'ArrowLeft'`
1569
- * - `'ArrowRight'`
1570
- * - `'ArrowUp'`
1571
- * - `'Backspace'`
1572
- * - `'Clear'`
1573
- * - `'ControlLeft'` or `'Control'`
1574
- * - `'ControlRight'`
1575
- * - `'Command'`
1576
- * - `'CommandOrControl'`
1577
- * - `'Delete'`
1578
- * - `'End'`
1579
- * - `'Enter'`
1580
- * - `'Escape'`
1581
- * - `'F1'` to `'F12'`
1582
- * - `'Home'`
1583
- * - `'Insert'`
1584
- * - `'MetaLeft'` or `'Meta'`
1585
- * - `'MetaRight'`
1586
- * - `'Numpad0'` to `'Numpad9'`
1587
- * - `'NumpadAdd'`
1588
- * - `'NumpadDecimal'`
1589
- * - `'NumpadDivide'`
1590
- * - `'NumpadMultiply'`
1591
- * - `'NumpadSubtract'`
1592
- * - `'PageDown'`
1593
- * - `'PageUp'`
1594
- * - `'Pause'`
1595
- * - `'Return'`
1596
- * - `'ShiftLeft'` or `'Shift'`
1597
- * - `'ShiftRight'`
1598
- * - `'Space'`
1599
- * - `'Tab'`
1600
- *
1601
- * @param {string|string[]} key key or array of keys to press.
1602
- * ⚠️ returns a _promise_ which is synchronized internally by recorder
1603
- *
1604
- *
1605
- * _Note:_ Shortcuts like `'Meta'` + `'A'` do not work on macOS ([GoogleChrome/puppeteer#1313](https://github.com/GoogleChrome/puppeteer/issues/1313)).
1606
- */
1607
- async pressKey(key) {
1608
- const modifiers = [];
1609
- if (Array.isArray(key)) {
1610
- for (let k of key) {
1611
- k = getNormalizedKey.call(this, k);
1612
- if (isModifierKey(k)) {
1613
- modifiers.push(k);
1614
- } else {
1615
- key = k;
1616
- break;
1617
- }
1618
- }
1619
- } else {
1620
- key = getNormalizedKey.call(this, key);
1621
- }
1622
- for (const modifier of modifiers) {
1623
- await this.page.keyboard.down(modifier);
1624
- }
1625
- await this.page.keyboard.press(key);
1626
- for (const modifier of modifiers) {
1627
- await this.page.keyboard.up(modifier);
1628
- }
1629
- return this._waitForAction();
1630
- }
1631
-
1632
- /**
1633
- * Types out the given text into an active field.
1634
- * To slow down typing use a second parameter, to set interval between key presses.
1635
- * _Note:_ Should be used when [`fillField`](#fillfield) is not an option.
1636
- *
1637
- * ```js
1638
- * // passing in a string
1639
- * I.type('Type this out.');
1640
- *
1641
- * // typing values with a 100ms interval
1642
- * I.type('4141555311111111', 100);
1643
- *
1644
- * // passing in an array
1645
- * I.type(['T', 'E', 'X', 'T']);
1646
- * ```
1647
- *
1648
- * @param {string|string[]} key or array of keys to type.
1649
- * @param {?number} [delay=null] (optional) delay in ms between key presses
1650
- * ⚠️ returns a _promise_ which is synchronized internally by recorder
1651
- *
1652
- */
1653
- async type(keys, delay = null) {
1654
- if (!Array.isArray(keys)) {
1655
- keys = keys.split('');
1656
- }
1657
-
1658
- for (const key of keys) {
1659
- await this.page.keyboard.press(key);
1660
- if (delay) await this.wait(delay / 1000);
1661
- }
1662
- }
1663
-
1664
- /**
1665
- * Fills a text field or textarea, after clearing its value, with the given string.
1666
- * Field is located by name, label, CSS, or XPath.
1667
- *
1668
- * ```js
1669
- * // by label
1670
- * I.fillField('Email', 'hello@world.com');
1671
- * // by name
1672
- * I.fillField('password', secret('123456'));
1673
- * // by CSS
1674
- * I.fillField('form#login input[name=username]', 'John');
1675
- * // or by strict locator
1676
- * I.fillField({css: 'form#login input[name=username]'}, 'John');
1677
- * ```
1678
- * @param {CodeceptJS.LocatorOrString} field located by label|name|CSS|XPath|strict locator.
1679
- * @param {CodeceptJS.StringOrSecret} value text value to fill.
1680
- * ⚠️ returns a _promise_ which is synchronized internally by recorder
1681
- *
1682
- * {{ react }}
1683
- */
1684
- async fillField(field, value) {
1685
- const els = await findVisibleFields.call(this, field);
1686
- assertElementExists(els, field, 'Field');
1687
- const el = els[0];
1688
- const tag = await el.getProperty('tagName').then(el => el.jsonValue());
1689
- const editable = await el.getProperty('contenteditable').then(el => el.jsonValue());
1690
- if (tag === 'INPUT' || tag === 'TEXTAREA') {
1691
- await this._evaluateHandeInContext(el => el.value = '', el);
1692
- } else if (editable) {
1693
- await this._evaluateHandeInContext(el => el.innerHTML = '', el);
1694
- }
1695
- await el.type(value.toString(), { delay: this.options.pressKeyDelay });
1696
- return this._waitForAction();
1697
- }
1698
-
1699
- /**
1700
- * Clears a `<textarea>` or text `<input>` element's value.
1701
- *
1702
- * ```js
1703
- * I.clearField('Email');
1704
- * I.clearField('user[email]');
1705
- * I.clearField('#email');
1706
- * ```
1707
- * @param {LocatorOrString} editable field located by label|name|CSS|XPath|strict locator.
1708
- * ⚠️ returns a _promise_ which is synchronized internally by recorder.
1709
- *
1710
- */
1711
- async clearField(field) {
1712
- return this.fillField(field, '');
1713
- }
1714
-
1715
- /**
1716
- * Appends text to a input field or textarea.
1717
- * Field is located by name, label, CSS or XPath
1718
- *
1719
- * ```js
1720
- * I.appendField('#myTextField', 'appended');
1721
- * ```
1722
- * @param {CodeceptJS.LocatorOrString} field located by label|name|CSS|XPath|strict locator
1723
- * @param {string} value text value to append.
1724
- * ⚠️ returns a _promise_ which is synchronized internally by recorder
1725
- *
1726
- *
1727
- * {{ react }}
1728
- */
1729
- async appendField(field, value) {
1730
- const els = await findVisibleFields.call(this, field);
1731
- assertElementExists(els, field, 'Field');
1732
- await els[0].press('End');
1733
- await els[0].type(value, { delay: this.options.pressKeyDelay });
1734
- return this._waitForAction();
1735
- }
1736
-
1737
- /**
1738
- * Checks that the given input field or textarea equals to given value.
1739
- * For fuzzy locators, fields are matched by label text, the "name" attribute, CSS, and XPath.
1740
- *
1741
- * ```js
1742
- * I.seeInField('Username', 'davert');
1743
- * I.seeInField({css: 'form textarea'},'Type your comment here');
1744
- * I.seeInField('form input[type=hidden]','hidden_value');
1745
- * I.seeInField('#searchform input','Search');
1746
- * ```
1747
- * @param {CodeceptJS.LocatorOrString} field located by label|name|CSS|XPath|strict locator.
1748
- * @param {string} value value to check.
1749
- * ⚠️ returns a _promise_ which is synchronized internally by recorder
1750
- *
1751
- */
1752
- async seeInField(field, value) {
1753
- return proceedSeeInField.call(this, 'assert', field, value);
1754
- }
1755
-
1756
- /**
1757
- * Checks that value of input field or textarea doesn't equal to given value
1758
- * Opposite to `seeInField`.
1759
- *
1760
- * ```js
1761
- * I.dontSeeInField('email', 'user@user.com'); // field by name
1762
- * I.dontSeeInField({ css: 'form input.email' }, 'user@user.com'); // field by CSS
1763
- * ```
1764
- *
1765
- * @param {CodeceptJS.LocatorOrString} field located by label|name|CSS|XPath|strict locator.
1766
- * @param {string} value value to check.
1767
- * ⚠️ returns a _promise_ which is synchronized internally by recorder
1768
- *
1769
- */
1770
- async dontSeeInField(field, value) {
1771
- return proceedSeeInField.call(this, 'negate', field, value);
1772
- }
1773
-
1774
- /**
1775
- * Attaches a file to element located by label, name, CSS or XPath
1776
- * Path to file is relative current codecept directory (where codecept.conf.ts or codecept.conf.js is located).
1777
- * File will be uploaded to remote system (if tests are running remotely).
1778
- *
1779
- * ```js
1780
- * I.attachFile('Avatar', 'data/avatar.jpg');
1781
- * I.attachFile('form input[name=avatar]', 'data/avatar.jpg');
1782
- * ```
1783
- *
1784
- * @param {CodeceptJS.LocatorOrString} locator field located by label|name|CSS|XPath|strict locator.
1785
- * @param {string} pathToFile local file path relative to codecept.conf.ts or codecept.conf.js config file.
1786
- * ⚠️ returns a _promise_ which is synchronized internally by recorder
1787
- *
1788
- *
1789
- * > ⚠ There is an [issue with file upload in Puppeteer 2.1.0 & 2.1.1](https://github.com/puppeteer/puppeteer/issues/5420), downgrade to 2.0.0 if you face it.
1790
- */
1791
- async attachFile(locator, pathToFile) {
1792
- const file = path.join(global.codecept_dir, pathToFile);
1793
-
1794
- if (!fileExists(file)) {
1795
- throw new Error(`File at ${file} can not be found on local system`);
1796
- }
1797
- const els = await findFields.call(this, locator);
1798
- assertElementExists(els, locator, 'Field');
1799
- await els[0].uploadFile(file);
1800
- return this._waitForAction();
1801
- }
1802
-
1803
- /**
1804
- * Selects an option in a drop-down select.
1805
- * Field is searched by label | name | CSS | XPath.
1806
- * Option is selected by visible text or by value.
1807
- *
1808
- * ```js
1809
- * I.selectOption('Choose Plan', 'Monthly'); // select by label
1810
- * I.selectOption('subscription', 'Monthly'); // match option by text
1811
- * I.selectOption('subscription', '0'); // or by value
1812
- * I.selectOption('//form/select[@name=account]','Premium');
1813
- * I.selectOption('form select[name=account]', 'Premium');
1814
- * I.selectOption({css: 'form select[name=account]'}, 'Premium');
1815
- * ```
1816
- *
1817
- * Provide an array for the second argument to select multiple options.
1818
- *
1819
- * ```js
1820
- * I.selectOption('Which OS do you use?', ['Android', 'iOS']);
1821
- * ```
1822
- * @param {LocatorOrString} select field located by label|name|CSS|XPath|strict locator.
1823
- * @param {string|Array<*>} option visible text or value of option.
1824
- * ⚠️ returns a _promise_ which is synchronized internally by recorder
1825
- *
1826
- */
1827
- async selectOption(select, option) {
1828
- const els = await findVisibleFields.call(this, select);
1829
- assertElementExists(els, select, 'Selectable field');
1830
- const el = els[0];
1831
- if (await el.getProperty('tagName').then(t => t.jsonValue()) !== 'SELECT') {
1832
- throw new Error('Element is not <select>');
1833
- }
1834
- if (!Array.isArray(option)) option = [option];
1835
-
1836
- for (const key in option) {
1837
- const opt = xpathLocator.literal(option[key]);
1838
- let optEl = await findElements.call(this, el, { xpath: Locator.select.byVisibleText(opt) });
1839
- if (optEl.length) {
1840
- this._evaluateHandeInContext(el => el.selected = true, optEl[0]);
1841
- continue;
1842
- }
1843
- optEl = await findElements.call(this, el, { xpath: Locator.select.byValue(opt) });
1844
- if (optEl.length) {
1845
- this._evaluateHandeInContext(el => el.selected = true, optEl[0]);
1846
- }
1847
- }
1848
- await this._evaluateHandeInContext((element) => {
1849
- element.dispatchEvent(new Event('input', { bubbles: true }));
1850
- element.dispatchEvent(new Event('change', { bubbles: true }));
1851
- }, el);
1852
-
1853
- return this._waitForAction();
1854
- }
1855
-
1856
- /**
1857
- * Grab number of visible elements by locator.
1858
- * Resumes test execution, so **should be used inside async function with `await`** operator.
1859
- *
1860
- * ```js
1861
- * let numOfElements = await I.grabNumberOfVisibleElements('p');
1862
- * ```
1863
- *
1864
- * @param {CodeceptJS.LocatorOrString} locator located by CSS|XPath|strict locator.
1865
- * @returns {Promise<number>} number of visible elements
1866
- * {{ react }}
1867
- */
1868
- async grabNumberOfVisibleElements(locator) {
1869
- let els = await this._locate(locator);
1870
- els = (await Promise.all(els.map(el => el.boundingBox() && el))).filter(v => v);
1871
- // Puppeteer visibility was ignored? | Remove when Puppeteer is fixed
1872
- els = await Promise.all(els.map(async el => (await el.evaluate(node => window.getComputedStyle(node).visibility !== 'hidden' && window.getComputedStyle(node).display !== 'none')) && el));
1873
-
1874
- return els.filter(v => v).length;
1875
- }
1876
-
1877
- /**
1878
- * Checks that current url contains a provided fragment.
1879
- *
1880
- * ```js
1881
- * I.seeInCurrentUrl('/register'); // we are on registration page
1882
- * ```
1883
- *
1884
- * @param {string} url a fragment to check
1885
- * ⚠️ returns a _promise_ which is synchronized internally by recorder
1886
- *
1887
- */
1888
- async seeInCurrentUrl(url) {
1889
- stringIncludes('url').assert(url, await this._getPageUrl());
1890
- }
1891
-
1892
- /**
1893
- * Checks that current url does not contain a provided fragment.
1894
- *
1895
- * @param {string} url value to check.
1896
- * ⚠️ returns a _promise_ which is synchronized internally by recorder
1897
- *
1898
- */
1899
- async dontSeeInCurrentUrl(url) {
1900
- stringIncludes('url').negate(url, await this._getPageUrl());
1901
- }
1902
-
1903
- /**
1904
- * Checks that current url is equal to provided one.
1905
- * If a relative url provided, a configured url will be prepended to it.
1906
- * So both examples will work:
1907
- *
1908
- * ```js
1909
- * I.seeCurrentUrlEquals('/register');
1910
- * I.seeCurrentUrlEquals('http://my.site.com/register');
1911
- * ```
1912
- *
1913
- * @param {string} url value to check.
1914
- * ⚠️ returns a _promise_ which is synchronized internally by recorder
1915
- *
1916
- */
1917
- async seeCurrentUrlEquals(url) {
1918
- urlEquals(this.options.url).assert(url, await this._getPageUrl());
1919
- }
1920
-
1921
- /**
1922
- * Checks that current url is not equal to provided one.
1923
- * If a relative url provided, a configured url will be prepended to it.
1924
- *
1925
- * ```js
1926
- * I.dontSeeCurrentUrlEquals('/login'); // relative url are ok
1927
- * I.dontSeeCurrentUrlEquals('http://mysite.com/login'); // absolute urls are also ok
1928
- * ```
1929
- *
1930
- * @param {string} url value to check.
1931
- * ⚠️ returns a _promise_ which is synchronized internally by recorder
1932
- *
1933
- */
1934
- async dontSeeCurrentUrlEquals(url) {
1935
- urlEquals(this.options.url).negate(url, await this._getPageUrl());
1936
- }
1937
-
1938
- /**
1939
- * Checks that a page contains a visible text.
1940
- * Use context parameter to narrow down the search.
1941
- *
1942
- * ```js
1943
- * I.see('Welcome'); // text welcome on a page
1944
- * I.see('Welcome', '.content'); // text inside .content div
1945
- * I.see('Register', {css: 'form.register'}); // use strict locator
1946
- * ```
1947
- * @param {string} text expected on page.
1948
- * @param {?CodeceptJS.LocatorOrString} [context=null] (optional, `null` by default) element located by CSS|Xpath|strict locator in which to search for text.
1949
- * ⚠️ returns a _promise_ which is synchronized internally by recorder
1950
- *
1951
- *
1952
- * {{ react }}
1953
- */
1954
- async see(text, context = null) {
1955
- return proceedSee.call(this, 'assert', text, context);
1956
- }
1957
-
1958
- /**
1959
- * Checks that text is equal to provided one.
1960
- *
1961
- * ```js
1962
- * I.seeTextEquals('text', 'h1');
1963
- * ```
1964
- *
1965
- * @param {string} text element value to check.
1966
- * @param {CodeceptJS.LocatorOrString?} [context=null] element located by CSS|XPath|strict locator.
1967
- * ⚠️ returns a _promise_ which is synchronized internally by recorder
1968
- *
1969
- */
1970
- async seeTextEquals(text, context = null) {
1971
- return proceedSee.call(this, 'assert', text, context, true);
1972
- }
1973
-
1974
- /**
1975
- * Opposite to `see`. Checks that a text is not present on a page.
1976
- * Use context parameter to narrow down the search.
1977
- *
1978
- * ```js
1979
- * I.dontSee('Login'); // assume we are already logged in.
1980
- * I.dontSee('Login', '.nav'); // no login inside .nav element
1981
- * ```
1982
- *
1983
- * @param {string} text which is not present.
1984
- * @param {CodeceptJS.LocatorOrString} [context] (optional) element located by CSS|XPath|strict locator in which to perfrom search.
1985
- * ⚠️ returns a _promise_ which is synchronized internally by recorder
1986
- *
1987
- *
1988
- * {{ react }}
1989
- */
1990
- async dontSee(text, context = null) {
1991
- return proceedSee.call(this, 'negate', text, context);
1992
- }
1993
-
1994
- /**
1995
- * Retrieves page source and returns it to test.
1996
- * Resumes test execution, so **should be used inside async function with `await`** operator.
1997
- *
1998
- * ```js
1999
- * let pageSource = await I.grabSource();
2000
- * ```
2001
- *
2002
- * @returns {Promise<string>} source code
2003
- */
2004
- async grabSource() {
2005
- return this.page.content();
2006
- }
2007
-
2008
- /**
2009
- * Get JS log from browser.
2010
- *
2011
- * ```js
2012
- * let logs = await I.grabBrowserLogs();
2013
- * console.log(JSON.stringify(logs))
2014
- * ```
2015
- * @return {Promise<any[]>}
2016
- */
2017
- async grabBrowserLogs() {
2018
- const logs = consoleLogStore.entries;
2019
- consoleLogStore.clear();
2020
- return logs;
2021
- }
2022
-
2023
- /**
2024
- * Get current URL from browser.
2025
- * Resumes test execution, so should be used inside an async function.
2026
- *
2027
- * ```js
2028
- * let url = await I.grabCurrentUrl();
2029
- * console.log(`Current URL is [${url}]`);
2030
- * ```
2031
- *
2032
- * @returns {Promise<string>} current URL
2033
- */
2034
- async grabCurrentUrl() {
2035
- return this._getPageUrl();
2036
- }
2037
-
2038
- /**
2039
- * Checks that the current page contains the given string in its raw source code.
2040
- *
2041
- * ```js
2042
- * I.seeInSource('<h1>Green eggs &amp; ham</h1>');
2043
- * ```
2044
- * @param {string} text value to check.
2045
- * ⚠️ returns a _promise_ which is synchronized internally by recorder
2046
- *
2047
- */
2048
- async seeInSource(text) {
2049
- const source = await this.page.content();
2050
- stringIncludes('HTML source of a page').assert(text, source);
2051
- }
2052
-
2053
- /**
2054
- * Checks that the current page does not contains the given string in its raw source code.
2055
- *
2056
- * ```js
2057
- * I.dontSeeInSource('<!--'); // no comments in source
2058
- * ```
2059
- *
2060
- * @param {string} value to check.
2061
- * ⚠️ returns a _promise_ which is synchronized internally by recorder
2062
- *
2063
- */
2064
- async dontSeeInSource(text) {
2065
- const source = await this.page.content();
2066
- stringIncludes('HTML source of a page').negate(text, source);
2067
- }
2068
-
2069
- /**
2070
- * Asserts that an element appears a given number of times in the DOM.
2071
- * Element is located by label or name or CSS or XPath.
2072
- *
2073
- *
2074
- * ```js
2075
- * I.seeNumberOfElements('#submitBtn', 1);
2076
- * ```
2077
- *
2078
- * @param {CodeceptJS.LocatorOrString} locator element located by CSS|XPath|strict locator.
2079
- * @param {number} num number of elements.
2080
- * ⚠️ returns a _promise_ which is synchronized internally by recorder
2081
- *
2082
- *
2083
- * {{ react }}
2084
- */
2085
- async seeNumberOfElements(locator, num) {
2086
- const elements = await this._locate(locator);
2087
- return equals(`expected number of elements (${(new Locator(locator))}) is ${num}, but found ${elements.length}`).assert(elements.length, num);
2088
- }
2089
-
2090
- /**
2091
- * Asserts that an element is visible a given number of times.
2092
- * Element is located by CSS or XPath.
2093
- *
2094
- * ```js
2095
- * I.seeNumberOfVisibleElements('.buttons', 3);
2096
- * ```
2097
- *
2098
- * @param {CodeceptJS.LocatorOrString} locator element located by CSS|XPath|strict locator.
2099
- * @param {number} num number of elements.
2100
- * ⚠️ returns a _promise_ which is synchronized internally by recorder
2101
- *
2102
- *
2103
- * {{ react }}
2104
- */
2105
- async seeNumberOfVisibleElements(locator, num) {
2106
- const res = await this.grabNumberOfVisibleElements(locator);
2107
- return equals(`expected number of visible elements (${(new Locator(locator))}) is ${num}, but found ${res}`).assert(res, num);
2108
- }
2109
-
2110
- /**
2111
- * Sets cookie(s).
2112
- *
2113
- * Can be a single cookie object or an array of cookies:
2114
- *
2115
- * ```js
2116
- * I.setCookie({name: 'auth', value: true});
2117
- *
2118
- * // as array
2119
- * I.setCookie([
2120
- * {name: 'auth', value: true},
2121
- * {name: 'agree', value: true}
2122
- * ]);
2123
- * ```
2124
- *
2125
- * @param {Cookie|Array<Cookie>} cookie a cookie object or array of cookie objects.
2126
- * ⚠️ returns a _promise_ which is synchronized internally by recorder
2127
- *
2128
- */
2129
- async setCookie(cookie) {
2130
- if (Array.isArray(cookie)) {
2131
- return this.page.setCookie(...cookie);
2132
- }
2133
- return this.page.setCookie(cookie);
2134
- }
2135
-
2136
- /**
2137
- * Checks that cookie with given name exists.
2138
- *
2139
- * ```js
2140
- * I.seeCookie('Auth');
2141
- * ```
2142
- *
2143
- * @param {string} name cookie name.
2144
- * ⚠️ returns a _promise_ which is synchronized internally by recorder
2145
- *
2146
- *
2147
- */
2148
- async seeCookie(name) {
2149
- const cookies = await this.page.cookies();
2150
- empty(`cookie ${name} to be set`).negate(cookies.filter(c => c.name === name));
2151
- }
2152
-
2153
- /**
2154
- * Checks that cookie with given name does not exist.
2155
- *
2156
- * ```js
2157
- * I.dontSeeCookie('auth'); // no auth cookie
2158
- * ```
2159
- *
2160
- * @param {string} name cookie name.
2161
- * ⚠️ returns a _promise_ which is synchronized internally by recorder
2162
- *
2163
- */
2164
- async dontSeeCookie(name) {
2165
- const cookies = await this.page.cookies();
2166
- empty(`cookie ${name} to be set`).assert(cookies.filter(c => c.name === name));
2167
- }
2168
-
2169
- /**
2170
- * Gets a cookie object by name.
2171
- * If none provided gets all cookies.
2172
- * Resumes test execution, so **should be used inside async function with `await`** operator.
2173
- *
2174
- * ```js
2175
- * let cookie = await I.grabCookie('auth');
2176
- * assert(cookie.value, '123456');
2177
- * ```
2178
- *
2179
- * @param {?string} [name=null] cookie name.
2180
- * @returns {Promise<string>|Promise<string[]>} attribute value
2181
- *
2182
- *
2183
- * Returns cookie in JSON format. If name not passed returns all cookies for this domain.
2184
- */
2185
- async grabCookie(name) {
2186
- const cookies = await this.page.cookies();
2187
- if (!name) return cookies;
2188
- const cookie = cookies.filter(c => c.name === name);
2189
- if (cookie[0]) return cookie[0];
2190
- }
2191
-
2192
- /**
2193
- * Clears a cookie by name,
2194
- * if none provided clears all cookies.
2195
- *
2196
- * ```js
2197
- * I.clearCookie();
2198
- * I.clearCookie('test');
2199
- * ```
2200
- *
2201
- * @param {?string} [cookie=null] (optional, `null` by default) cookie name
2202
- * ⚠️ returns a _promise_ which is synchronized internally by recorder
2203
- *
2204
- */
2205
- async clearCookie(name) {
2206
- const cookies = await this.page.cookies();
2207
- if (!name) {
2208
- return this.page.deleteCookie.apply(this.page, cookies);
2209
- }
2210
- const cookie = cookies.filter(c => c.name === name);
2211
- if (!cookie[0]) return;
2212
- return this.page.deleteCookie(cookie[0]);
2213
- }
2214
-
2215
- /**
2216
- * Executes sync script on a page.
2217
- * Pass arguments to function as additional parameters.
2218
- * Will return execution result to a test.
2219
- * In this case you should use async function and await to receive results.
2220
- *
2221
- * Example with jQuery DatePicker:
2222
- *
2223
- * ```js
2224
- * // change date of jQuery DatePicker
2225
- * I.executeScript(function() {
2226
- * // now we are inside browser context
2227
- * $('date').datetimepicker('setDate', new Date());
2228
- * });
2229
- * ```
2230
- * Can return values. Don't forget to use `await` to get them.
2231
- *
2232
- * ```js
2233
- * let date = await I.executeScript(function(el) {
2234
- * // only basic types can be returned
2235
- * return $(el).datetimepicker('getDate').toString();
2236
- * }, '#date'); // passing jquery selector
2237
- * ```
2238
- *
2239
- * @param {string|function} fn function to be executed in browser context.
2240
- * @param {...any} args to be passed to function.
2241
- * ⚠️ returns a _promise_ which is synchronized internally by recorder
2242
- *
2243
- *
2244
- * If a function returns a Promise It will wait for it resolution.
2245
- */
2246
- async executeScript(...args) {
2247
- let context = this.page;
2248
- if (this.context && this.context.constructor.name === 'Frame') {
2249
- context = this.context; // switching to iframe context
2250
- }
2251
- return context.evaluate.apply(context, args);
2252
- }
2253
-
2254
- /**
2255
- * Executes async script on page.
2256
- * Provided function should execute a passed callback (as first argument) to signal it is finished.
2257
- *
2258
- * Example: In Vue.js to make components completely rendered we are waiting for [nextTick](https://vuejs.org/v2/api/#Vue-nextTick).
2259
- *
2260
- * ```js
2261
- * I.executeAsyncScript(function(done) {
2262
- * Vue.nextTick(done); // waiting for next tick
2263
- * });
2264
- * ```
2265
- *
2266
- * By passing value to `done()` function you can return values.
2267
- * Additional arguments can be passed as well, while `done` function is always last parameter in arguments list.
2268
- *
2269
- * ```js
2270
- * let val = await I.executeAsyncScript(function(url, done) {
2271
- * // in browser context
2272
- * $.ajax(url, { success: (data) => done(data); }
2273
- * }, 'http://ajax.callback.url/');
2274
- * ```
2275
- *
2276
- * @param {string|function} fn function to be executed in browser context.
2277
- * @param {...any} args to be passed to function.
2278
- * ⚠️ returns a _promise_ which is synchronized internally by recorder
2279
- *
2280
- *
2281
- * Asynchronous scripts can also be executed with `executeScript` if a function returns a Promise.
2282
- */
2283
- async executeAsyncScript(...args) {
2284
- const asyncFn = function () {
2285
- const args = Array.from(arguments);
2286
- const fn = eval(`(${args.shift()})`); // eslint-disable-line no-eval
2287
- return new Promise((done) => {
2288
- args.push(done);
2289
- fn.apply(null, args);
2290
- });
2291
- };
2292
- args[0] = args[0].toString();
2293
- args.unshift(asyncFn);
2294
- return this.page.evaluate.apply(this.page, args);
2295
- }
2296
-
2297
- /**
2298
- * Retrieves all texts from an element located by CSS or XPath and returns it to test.
2299
- * Resumes test execution, so **should be used inside async with `await`** operator.
2300
- *
2301
- * ```js
2302
- * let pins = await I.grabTextFromAll('#pin li');
2303
- * ```
2304
- *
2305
- * @param {CodeceptJS.LocatorOrString} locator element located by CSS|XPath|strict locator.
2306
- * @returns {Promise<string[]>} attribute value
2307
- *
2308
- * {{ react }}
2309
- */
2310
- async grabTextFromAll(locator) {
2311
- const els = await this._locate(locator);
2312
- const texts = [];
2313
- for (const el of els) {
2314
- texts.push(await (await el.getProperty('innerText')).jsonValue());
2315
- }
2316
- return texts;
2317
- }
2318
-
2319
- /**
2320
- * Retrieves a text from an element located by CSS or XPath and returns it to test.
2321
- * Resumes test execution, so **should be used inside async with `await`** operator.
2322
- *
2323
- * ```js
2324
- * let pin = await I.grabTextFrom('#pin');
2325
- * ```
2326
- * If multiple elements found returns first element.
2327
- *
2328
- * @param {CodeceptJS.LocatorOrString} locator element located by CSS|XPath|strict locator.
2329
- * @returns {Promise<string>} attribute value
2330
- *
2331
- * {{ react }}
2332
- */
2333
- async grabTextFrom(locator) {
2334
- const texts = await this.grabTextFromAll(locator);
2335
- assertElementExists(texts, locator);
2336
- if (texts.length > 1) {
2337
- this.debugSection('GrabText', `Using first element out of ${texts.length}`);
2338
- }
2339
-
2340
- return texts[0];
2341
- }
2342
-
2343
- /**
2344
- * Retrieves an array of value from a form located by CSS or XPath and returns it to test.
2345
- * Resumes test execution, so **should be used inside async function with `await`** operator.
2346
- *
2347
- * ```js
2348
- * let inputs = await I.grabValueFromAll('//form/input');
2349
- * ```
2350
- * @param {CodeceptJS.LocatorOrString} locator field located by label|name|CSS|XPath|strict locator.
2351
- * @returns {Promise<string[]>} attribute value
2352
- *
2353
- */
2354
- async grabValueFromAll(locator) {
2355
- const els = await findFields.call(this, locator);
2356
- const values = [];
2357
- for (const el of els) {
2358
- values.push(await (await el.getProperty('value')).jsonValue());
2359
- }
2360
- return values;
2361
- }
2362
-
2363
- /**
2364
- * Retrieves a value from a form element located by CSS or XPath and returns it to test.
2365
- * Resumes test execution, so **should be used inside async function with `await`** operator.
2366
- * If more than one element is found - value of first element is returned.
2367
- *
2368
- * ```js
2369
- * let email = await I.grabValueFrom('input[name=email]');
2370
- * ```
2371
- * @param {CodeceptJS.LocatorOrString} locator field located by label|name|CSS|XPath|strict locator.
2372
- * @returns {Promise<string>} attribute value
2373
- *
2374
- */
2375
- async grabValueFrom(locator) {
2376
- const values = await this.grabValueFromAll(locator);
2377
- assertElementExists(values, locator);
2378
- if (values.length > 1) {
2379
- this.debugSection('GrabValue', `Using first element out of ${values.length}`);
2380
- }
2381
-
2382
- return values[0];
2383
- }
2384
-
2385
- /**
2386
- * Retrieves all the innerHTML from elements located by CSS or XPath and returns it to test.
2387
- * Resumes test execution, so **should be used inside async function with `await`** operator.
2388
- *
2389
- * ```js
2390
- * let postHTMLs = await I.grabHTMLFromAll('.post');
2391
- * ```
2392
- *
2393
- * @param {CodeceptJS.LocatorOrString} element located by CSS|XPath|strict locator.
2394
- * @returns {Promise<string[]>} HTML code for an element
2395
- *
2396
- */
2397
- async grabHTMLFromAll(locator) {
2398
- const els = await this._locate(locator);
2399
- const values = await Promise.all(els.map(el => el.executionContext().evaluate(element => element.innerHTML, el)));
2400
- return values;
2401
- }
2402
-
2403
- /**
2404
- * Retrieves the innerHTML from an element located by CSS or XPath and returns it to test.
2405
- * Resumes test execution, so **should be used inside async function with `await`** operator.
2406
- * If more than one element is found - HTML of first element is returned.
2407
- *
2408
- * ```js
2409
- * let postHTML = await I.grabHTMLFrom('#post');
2410
- * ```
2411
- *
2412
- * @param {CodeceptJS.LocatorOrString} element located by CSS|XPath|strict locator.
2413
- * @returns {Promise<string>} HTML code for an element
2414
- *
2415
- */
2416
- async grabHTMLFrom(locator) {
2417
- const html = await this.grabHTMLFromAll(locator);
2418
- assertElementExists(html, locator);
2419
- if (html.length > 1) {
2420
- this.debugSection('GrabHTML', `Using first element out of ${html.length}`);
2421
- }
2422
-
2423
- return html[0];
2424
- }
2425
-
2426
- /**
2427
- * Grab array of CSS properties for given locator
2428
- * Resumes test execution, so **should be used inside an async function with `await`** operator.
2429
- *
2430
- * ```js
2431
- * const values = await I.grabCssPropertyFromAll('h3', 'font-weight');
2432
- * ```
2433
- *
2434
- * @param {CodeceptJS.LocatorOrString} locator element located by CSS|XPath|strict locator.
2435
- * @param {string} cssProperty CSS property name.
2436
- * @returns {Promise<string[]>} CSS value
2437
- *
2438
- * {{ react }}
2439
- */
2440
- async grabCssPropertyFromAll(locator, cssProperty) {
2441
- const els = await this._locate(locator);
2442
- const res = await Promise.all(els.map(el => el.executionContext().evaluate(el => JSON.parse(JSON.stringify(getComputedStyle(el))), el)));
2443
- const cssValues = res.map(props => props[toCamelCase(cssProperty)]);
2444
-
2445
- return cssValues;
2446
- }
2447
-
2448
- /**
2449
- * Grab CSS property for given locator
2450
- * Resumes test execution, so **should be used inside an async function with `await`** operator.
2451
- * If more than one element is found - value of first element is returned.
2452
- *
2453
- * ```js
2454
- * const value = await I.grabCssPropertyFrom('h3', 'font-weight');
2455
- * ```
2456
- *
2457
- * @param {CodeceptJS.LocatorOrString} locator element located by CSS|XPath|strict locator.
2458
- * @param {string} cssProperty CSS property name.
2459
- * @returns {Promise<string>} CSS value
2460
- *
2461
- * {{ react }}
2462
- */
2463
- async grabCssPropertyFrom(locator, cssProperty) {
2464
- const cssValues = await this.grabCssPropertyFromAll(locator, cssProperty);
2465
- assertElementExists(cssValues, locator);
2466
-
2467
- if (cssValues.length > 1) {
2468
- this.debugSection('GrabCSS', `Using first element out of ${cssValues.length}`);
2469
- }
2470
-
2471
- return cssValues[0];
2472
- }
2473
-
2474
- /**
2475
- * Checks that all elements with given locator have given CSS properties.
2476
- *
2477
- * ```js
2478
- * I.seeCssPropertiesOnElements('h3', { 'font-weight': "bold"});
2479
- * ```
2480
- *
2481
- * @param {CodeceptJS.LocatorOrString} locator located by CSS|XPath|strict locator.
2482
- * @param {object} cssProperties object with CSS properties and their values to check.
2483
- * ⚠️ returns a _promise_ which is synchronized internally by recorder
2484
- *
2485
- * {{ react }}
2486
- */
2487
- async seeCssPropertiesOnElements(locator, cssProperties) {
2488
- const res = await this._locate(locator);
2489
- assertElementExists(res, locator);
2490
-
2491
- const cssPropertiesCamelCase = convertCssPropertiesToCamelCase(cssProperties);
2492
- const elemAmount = res.length;
2493
- const commands = [];
2494
- res.forEach((el) => {
2495
- Object.keys(cssPropertiesCamelCase).forEach((prop) => {
2496
- commands.push(el.executionContext()
2497
- .evaluate((el) => {
2498
- const style = window.getComputedStyle ? getComputedStyle(el) : el.currentStyle;
2499
- return JSON.parse(JSON.stringify(style));
2500
- }, el)
2501
- .then((props) => {
2502
- if (isColorProperty(prop)) {
2503
- return convertColorToRGBA(props[prop]);
2504
- }
2505
- return props[prop];
2506
- }));
2507
- });
2508
- });
2509
- let props = await Promise.all(commands);
2510
- const values = Object.keys(cssPropertiesCamelCase).map(key => cssPropertiesCamelCase[key]);
2511
- if (!Array.isArray(props)) props = [props];
2512
- let chunked = chunkArray(props, values.length);
2513
- chunked = chunked.filter((val) => {
2514
- for (let i = 0; i < val.length; ++i) {
2515
- if (val[i] !== values[i]) return false;
2516
- }
2517
- return true;
2518
- });
2519
- return equals(`all elements (${(new Locator(locator))}) to have CSS property ${JSON.stringify(cssProperties)}`).assert(chunked.length, elemAmount);
2520
- }
2521
-
2522
- /**
2523
- * Checks that all elements with given locator have given attributes.
2524
- *
2525
- * ```js
2526
- * I.seeAttributesOnElements('//form', { method: "post"});
2527
- * ```
2528
- *
2529
- * @param {CodeceptJS.LocatorOrString} locator located by CSS|XPath|strict locator.
2530
- * @param {object} attributes attributes and their values to check.
2531
- * ⚠️ returns a _promise_ which is synchronized internally by recorder
2532
- *
2533
- * {{ react }}
2534
- */
2535
- async seeAttributesOnElements(locator, attributes) {
2536
- const res = await this._locate(locator);
2537
- assertElementExists(res, locator);
2538
-
2539
- const elemAmount = res.length;
2540
- const commands = [];
2541
- res.forEach((el) => {
2542
- Object.keys(attributes).forEach((prop) => {
2543
- commands.push(el
2544
- .executionContext()
2545
- .evaluateHandle((el, attr) => el[attr] || el.getAttribute(attr), el, prop)
2546
- .then(el => el.jsonValue()));
2547
- });
2548
- });
2549
- let attrs = await Promise.all(commands);
2550
- const values = Object.keys(attributes).map(key => attributes[key]);
2551
- if (!Array.isArray(attrs)) attrs = [attrs];
2552
- let chunked = chunkArray(attrs, values.length);
2553
- chunked = chunked.filter((val) => {
2554
- for (let i = 0; i < val.length; ++i) {
2555
- if (val[i] !== values[i]) return false;
2556
- }
2557
- return true;
2558
- });
2559
- return equals(`all elements (${(new Locator(locator))}) to have attributes ${JSON.stringify(attributes)}`).assert(chunked.length, elemAmount);
2560
- }
2561
-
2562
- /**
2563
- * Drag the scrubber of a slider to a given position
2564
- * For fuzzy locators, fields are matched by label text, the "name" attribute, CSS, and XPath.
2565
- *
2566
- * ```js
2567
- * I.dragSlider('#slider', 30);
2568
- * I.dragSlider('#slider', -70);
2569
- * ```
2570
- *
2571
- * @param {CodeceptJS.LocatorOrString} locator located by label|name|CSS|XPath|strict locator.
2572
- * @param {number} offsetX position to drag.
2573
- * ⚠️ returns a _promise_ which is synchronized internally by recorder
2574
- *
2575
- * {{ react }}
2576
- */
2577
- async dragSlider(locator, offsetX = 0) {
2578
- const src = await this._locate(locator);
2579
- assertElementExists(src, locator, 'Slider Element');
2580
-
2581
- // Note: Using public api .getClickablePoint because the .BoundingBox does not take into account iframe offsets
2582
- const sliderSource = await getClickablePoint(src[0]);
2583
-
2584
- // Drag start point
2585
- await this.page.mouse.move(sliderSource.x, sliderSource.y, { steps: 5 });
2586
- await this.page.mouse.down();
2587
-
2588
- // Drag destination
2589
- await this.page.mouse.move(sliderSource.x + offsetX, sliderSource.y, { steps: 5 });
2590
- await this.page.mouse.up();
2591
-
2592
- await this._waitForAction();
2593
- }
2594
-
2595
- /**
2596
- * Retrieves an array of attributes from elements located by CSS or XPath and returns it to test.
2597
- * Resumes test execution, so **should be used inside async with `await`** operator.
2598
- *
2599
- * ```js
2600
- * let hints = await I.grabAttributeFromAll('.tooltip', 'title');
2601
- * ```
2602
- * @param {CodeceptJS.LocatorOrString} locator element located by CSS|XPath|strict locator.
2603
- * @param {string} attr attribute name.
2604
- * @returns {Promise<string[]>} attribute value
2605
- *
2606
- * {{ react }}
2607
- */
2608
- async grabAttributeFromAll(locator, attr) {
2609
- const els = await this._locate(locator);
2610
- const array = [];
2611
- for (let index = 0; index < els.length; index++) {
2612
- const a = await this._evaluateHandeInContext((el, attr) => el[attr] || el.getAttribute(attr), els[index], attr);
2613
- array.push(await a.jsonValue());
2614
- }
2615
- return array;
2616
- }
2617
-
2618
- /**
2619
- * Retrieves an attribute from an element located by CSS or XPath and returns it to test.
2620
- * Resumes test execution, so **should be used inside async with `await`** operator.
2621
- * If more than one element is found - attribute of first element is returned.
2622
- *
2623
- * ```js
2624
- * let hint = await I.grabAttributeFrom('#tooltip', 'title');
2625
- * ```
2626
- * @param {CodeceptJS.LocatorOrString} locator element located by CSS|XPath|strict locator.
2627
- * @param {string} attr attribute name.
2628
- * @returns {Promise<string>} attribute value
2629
- *
2630
- * {{ react }}
2631
- */
2632
- async grabAttributeFrom(locator, attr) {
2633
- const attrs = await this.grabAttributeFromAll(locator, attr);
2634
- assertElementExists(attrs, locator);
2635
- if (attrs.length > 1) {
2636
- this.debugSection('GrabAttribute', `Using first element out of ${attrs.length}`);
2637
- }
2638
-
2639
- return attrs[0];
2640
- }
2641
-
2642
- /**
2643
- * Saves screenshot of the specified locator to ouput folder (set in codecept.conf.ts or codecept.conf.js).
2644
- * Filename is relative to output folder.
2645
- *
2646
- * ```js
2647
- * I.saveElementScreenshot(`#submit`,'debug.png');
2648
- * ```
2649
- *
2650
- * @param {CodeceptJS.LocatorOrString} locator element located by CSS|XPath|strict locator.
2651
- * @param {string} fileName file name to save.
2652
- * ⚠️ returns a _promise_ which is synchronized internally by recorder
2653
- *
2654
- */
2655
- async saveElementScreenshot(locator, fileName) {
2656
- const outputFile = screenshotOutputFolder(fileName);
2657
-
2658
- const res = await this._locate(locator);
2659
- assertElementExists(res, locator);
2660
- if (res.length > 1) this.debug(`[Elements] Using first element out of ${res.length}`);
2661
- const elem = res[0];
2662
- this.debug(`Screenshot of ${(new Locator(locator))} element has been saved to ${outputFile}`);
2663
- return elem.screenshot({ path: outputFile, type: 'png' });
2664
- }
2665
-
2666
- /**
2667
- * Saves a screenshot to ouput folder (set in codecept.conf.ts or codecept.conf.js).
2668
- * Filename is relative to output folder.
2669
- * 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.
2670
- *
2671
- * ```js
2672
- * I.saveScreenshot('debug.png');
2673
- * I.saveScreenshot('debug.png', true) //resizes to available scrollHeight and scrollWidth before taking screenshot
2674
- * ```
2675
- *
2676
- * @param {string} fileName file name to save.
2677
- * @param {boolean} [fullPage=false] (optional, `false` by default) flag to enable fullscreen screenshot mode.
2678
- * ⚠️ returns a _promise_ which is synchronized internally by recorder
2679
- *
2680
- */
2681
- async saveScreenshot(fileName, fullPage) {
2682
- const fullPageOption = fullPage || this.options.fullPageScreenshots;
2683
- const outputFile = screenshotOutputFolder(fileName);
2684
-
2685
- this.debug(`Screenshot is saving to ${outputFile}`);
2686
-
2687
- if (this.activeSessionName) {
2688
- const activeSessionPage = this.sessionPages[this.activeSessionName];
2689
-
2690
- if (activeSessionPage) {
2691
- return activeSessionPage.screenshot({
2692
- path: outputFile,
2693
- fullPage: fullPageOption,
2694
- type: 'png',
2695
- });
2696
- }
2697
- }
2698
-
2699
- return this.page.screenshot({ path: outputFile, fullPage: fullPageOption, type: 'png' });
2700
- }
2701
-
2702
- async _failed() {
2703
- await this._withinEnd();
2704
- }
2705
-
2706
- /**
2707
- * Pauses execution for a number of seconds.
2708
- *
2709
- * ```js
2710
- * I.wait(2); // wait 2 secs
2711
- * ```
2712
- *
2713
- * @param {number} sec number of second to wait.
2714
- * ⚠️ returns a _promise_ which is synchronized internally by recorder
2715
- *
2716
- */
2717
- async wait(sec) {
2718
- return new Promise(((done) => {
2719
- setTimeout(done, sec * 1000);
2720
- }));
2721
- }
2722
-
2723
- /**
2724
- * Waits for element to become enabled (by default waits for 1sec).
2725
- * Element can be located by CSS or XPath.
2726
- *
2727
- * @param {CodeceptJS.LocatorOrString} locator element located by CSS|XPath|strict locator.
2728
- * @param {number} [sec=1] (optional) time in seconds to wait, 1 by default.
2729
- * ⚠️ returns a _promise_ which is synchronized internally by recorder
2730
- *
2731
- */
2732
- async waitForEnabled(locator, sec) {
2733
- const waitTimeout = sec ? sec * 1000 : this.options.waitForTimeout;
2734
- locator = new Locator(locator, 'css');
2735
- await this.context;
2736
- let waiter;
2737
- const context = await this._getContext();
2738
- if (locator.isCSS()) {
2739
- const enabledFn = function (locator) {
2740
- const els = document.querySelectorAll(locator);
2741
- if (!els || els.length === 0) {
2742
- return false;
2743
- }
2744
- return Array.prototype.filter.call(els, el => !el.disabled).length > 0;
2745
- };
2746
- waiter = context.waitForFunction(enabledFn, { timeout: waitTimeout }, locator.value);
2747
- } else {
2748
- const enabledFn = function (locator, $XPath) {
2749
- eval($XPath); // eslint-disable-line no-eval
2750
- return $XPath(null, locator).filter(el => !el.disabled).length > 0;
2751
- };
2752
- waiter = context.waitForFunction(enabledFn, { timeout: waitTimeout }, locator.value, $XPath.toString());
2753
- }
2754
- return waiter.catch((err) => {
2755
- throw new Error(`element (${locator.toString()}) still not enabled after ${waitTimeout / 1000} sec\n${err.message}`);
2756
- });
2757
- }
2758
-
2759
- /**
2760
- * Waits for the specified value to be in value attribute.
2761
- *
2762
- * ```js
2763
- * I.waitForValue('//input', "GoodValue");
2764
- * ```
2765
- *
2766
- * @param {LocatorOrString} field input field.
2767
- * @param {string }value expected value.
2768
- * @param {number} [sec=1] (optional, `1` by default) time in seconds to wait
2769
- * ⚠️ returns a _promise_ which is synchronized internally by recorder
2770
- *
2771
- */
2772
- async waitForValue(field, value, sec) {
2773
- const waitTimeout = sec ? sec * 1000 : this.options.waitForTimeout;
2774
- const locator = new Locator(field, 'css');
2775
- await this.context;
2776
- let waiter;
2777
- const context = await this._getContext();
2778
- if (locator.isCSS()) {
2779
- const valueFn = function (locator, value) {
2780
- const els = document.querySelectorAll(locator);
2781
- if (!els || els.length === 0) {
2782
- return false;
2783
- }
2784
- return Array.prototype.filter.call(els, el => (el.value.toString() || '').indexOf(value) !== -1).length > 0;
2785
- };
2786
- waiter = context.waitForFunction(valueFn, { timeout: waitTimeout }, locator.value, value);
2787
- } else {
2788
- const valueFn = function (locator, $XPath, value) {
2789
- eval($XPath); // eslint-disable-line no-eval
2790
- return $XPath(null, locator).filter(el => (el.value || '').indexOf(value) !== -1).length > 0;
2791
- };
2792
- waiter = context.waitForFunction(valueFn, { timeout: waitTimeout }, locator.value, $XPath.toString(), value);
2793
- }
2794
- return waiter.catch((err) => {
2795
- const loc = locator.toString();
2796
- throw new Error(`element (${loc}) is not in DOM or there is no element(${loc}) with value "${value}" after ${waitTimeout / 1000} sec\n${err.message}`);
2797
- });
2798
- }
2799
-
2800
- /**
2801
- * Waits for a specified number of elements on the page.
2802
- *
2803
- * ```js
2804
- * I.waitNumberOfVisibleElements('a', 3);
2805
- * ```
2806
- *
2807
- * @param {CodeceptJS.LocatorOrString} locator element located by CSS|XPath|strict locator.
2808
- * @param {number} num number of elements.
2809
- * @param {number} [sec=1] (optional, `1` by default) time in seconds to wait
2810
- * ⚠️ returns a _promise_ which is synchronized internally by recorder
2811
- *
2812
- * {{ react }}
2813
- */
2814
- async waitNumberOfVisibleElements(locator, num, sec) {
2815
- const waitTimeout = sec ? sec * 1000 : this.options.waitForTimeout;
2816
- locator = new Locator(locator, 'css');
2817
- await this.context;
2818
- let waiter;
2819
- const context = await this._getContext();
2820
- if (locator.isCSS()) {
2821
- const visibleFn = function (locator, num) {
2822
- const els = document.querySelectorAll(locator);
2823
- if (!els || els.length === 0) {
2824
- return false;
2825
- }
2826
- return Array.prototype.filter.call(els, el => el.offsetParent !== null).length === num;
2827
- };
2828
- waiter = context.waitForFunction(visibleFn, { timeout: waitTimeout }, locator.value, num);
2829
- } else {
2830
- const visibleFn = function (locator, $XPath, num) {
2831
- eval($XPath); // eslint-disable-line no-eval
2832
- return $XPath(null, locator).filter(el => el.offsetParent !== null).length === num;
2833
- };
2834
- waiter = context.waitForFunction(visibleFn, { timeout: waitTimeout }, locator.value, $XPath.toString(), num);
2835
- }
2836
- return waiter.catch((err) => {
2837
- throw new Error(`The number of elements (${locator.toString()}) is not ${num} after ${waitTimeout / 1000} sec\n${err.message}`);
2838
- });
2839
- }
2840
-
2841
- /**
2842
- * Waits for element to be clickable (by default waits for 1sec).
2843
- * Element can be located by CSS or XPath.
2844
- *
2845
- * ```js
2846
- * I.waitForClickable('.btn.continue');
2847
- * I.waitForClickable('.btn.continue', 5); // wait for 5 secs
2848
- * ```
2849
- *
2850
- * @param {CodeceptJS.LocatorOrString} locator element located by CSS|XPath|strict locator.
2851
- * @param {number} [sec] (optional, `1` by default) time in seconds to wait
2852
- * ⚠️ returns a _promise_ which is synchronized internally by recorder
2853
- *
2854
- */
2855
- async waitForClickable(locator, waitTimeout) {
2856
- const els = await this._locate(locator);
2857
- assertElementExists(els, locator);
2858
-
2859
- return this.waitForFunction(isElementClickable, [els[0]], waitTimeout).catch(async (e) => {
2860
- if (/failed: timeout/i.test(e.message)) {
2861
- throw new Error(`element ${new Locator(locator).toString()} still not clickable after ${waitTimeout || this.options.waitForTimeout / 1000} sec`);
2862
- } else {
2863
- throw e;
2864
- }
2865
- });
2866
- }
2867
-
2868
- /**
2869
- * Waits for element to be present on page (by default waits for 1sec).
2870
- * Element can be located by CSS or XPath.
2871
- *
2872
- * ```js
2873
- * I.waitForElement('.btn.continue');
2874
- * I.waitForElement('.btn.continue', 5); // wait for 5 secs
2875
- * ```
2876
- *
2877
- * @param {CodeceptJS.LocatorOrString} locator element located by CSS|XPath|strict locator.
2878
- * @param {number} [sec] (optional, `1` by default) time in seconds to wait
2879
- * ⚠️ returns a _promise_ which is synchronized internally by recorder
2880
- *
2881
- * {{ react }}
2882
- */
2883
- async waitForElement(locator, sec) {
2884
- const waitTimeout = sec ? sec * 1000 : this.options.waitForTimeout;
2885
- locator = new Locator(locator, 'css');
2886
-
2887
- let waiter;
2888
- const context = await this._getContext();
2889
- if (locator.isCSS()) {
2890
- waiter = context.waitForSelector(locator.simplify(), { timeout: waitTimeout });
2891
- } else {
2892
- waiter = context.waitForXPath(locator.value, { timeout: waitTimeout });
2893
- }
2894
- return waiter.catch((err) => {
2895
- throw new Error(`element (${locator.toString()}) still not present on page after ${waitTimeout / 1000} sec\n${err.message}`);
2896
- });
2897
- }
2898
-
2899
- /**
2900
- * Waits for an element to become visible on a page (by default waits for 1sec).
2901
- * Element can be located by CSS or XPath.
2902
- *
2903
- * ```js
2904
- * I.waitForVisible('#popup');
2905
- * ```
2906
- *
2907
- * @param {CodeceptJS.LocatorOrString} locator element located by CSS|XPath|strict locator.
2908
- * @param {number} [sec=1] (optional, `1` by default) time in seconds to wait
2909
- * ⚠️ returns a _promise_ which is synchronized internally by recorder
2910
- *
2911
- *
2912
- * This method accepts [React selectors](https://codecept.io/react).
2913
- */
2914
- async waitForVisible(locator, sec) {
2915
- const waitTimeout = sec ? sec * 1000 : this.options.waitForTimeout;
2916
- locator = new Locator(locator, 'css');
2917
- await this.context;
2918
- let waiter;
2919
- const context = await this._getContext();
2920
- if (locator.isCSS()) {
2921
- waiter = context.waitForSelector(locator.simplify(), { timeout: waitTimeout, visible: true });
2922
- } else {
2923
- waiter = context.waitForXPath(locator.value, { timeout: waitTimeout, visible: true });
2924
- }
2925
- return waiter.catch((err) => {
2926
- throw new Error(`element (${locator.toString()}) still not visible after ${waitTimeout / 1000} sec\n${err.message}`);
2927
- });
2928
- }
2929
-
2930
- /**
2931
- * Waits for an element to be removed or become invisible on a page (by default waits for 1sec).
2932
- * Element can be located by CSS or XPath.
2933
- *
2934
- * ```js
2935
- * I.waitForInvisible('#popup');
2936
- * ```
2937
- *
2938
- * @param {CodeceptJS.LocatorOrString} locator element located by CSS|XPath|strict locator.
2939
- * @param {number} [sec=1] (optional, `1` by default) time in seconds to wait
2940
- * ⚠️ returns a _promise_ which is synchronized internally by recorder
2941
- *
2942
- */
2943
- async waitForInvisible(locator, sec) {
2944
- const waitTimeout = sec ? sec * 1000 : this.options.waitForTimeout;
2945
- locator = new Locator(locator, 'css');
2946
- await this.context;
2947
- let waiter;
2948
- const context = await this._getContext();
2949
- if (locator.isCSS()) {
2950
- waiter = context.waitForSelector(locator.simplify(), { timeout: waitTimeout, hidden: true });
2951
- } else {
2952
- waiter = context.waitForXPath(locator.value, { timeout: waitTimeout, hidden: true });
2953
- }
2954
- return waiter.catch((err) => {
2955
- throw new Error(`element (${locator.toString()}) still visible after ${waitTimeout / 1000} sec\n${err.message}`);
2956
- });
2957
- }
2958
-
2959
- /**
2960
- * Waits for an element to hide (by default waits for 1sec).
2961
- * Element can be located by CSS or XPath.
2962
- *
2963
- * ```js
2964
- * I.waitToHide('#popup');
2965
- * ```
2966
- *
2967
- * @param {CodeceptJS.LocatorOrString} locator element located by CSS|XPath|strict locator.
2968
- * @param {number} [sec=1] (optional, `1` by default) time in seconds to wait
2969
- * ⚠️ returns a _promise_ which is synchronized internally by recorder
2970
- *
2971
- */
2972
- async waitToHide(locator, sec) {
2973
- const waitTimeout = sec ? sec * 1000 : this.options.waitForTimeout;
2974
- locator = new Locator(locator, 'css');
2975
- let waiter;
2976
- const context = await this._getContext();
2977
- if (locator.isCSS()) {
2978
- waiter = context.waitForSelector(locator.simplify(), { timeout: waitTimeout, hidden: true });
2979
- } else {
2980
- waiter = context.waitForXPath(locator.value, { timeout: waitTimeout, hidden: true });
2981
- }
2982
- return waiter.catch((err) => {
2983
- throw new Error(`element (${locator.toString()}) still not hidden after ${waitTimeout / 1000} sec\n${err.message}`);
2984
- });
2985
- }
2986
-
2987
- async _getContext() {
2988
- if (this.context && this.context.constructor.name === 'Frame') {
2989
- return this.context;
2990
- }
2991
- return this.page;
2992
- }
2993
-
2994
- /**
2995
- * Waiting for the part of the URL to match the expected. Useful for SPA to understand that page was changed.
2996
- *
2997
- * ```js
2998
- * I.waitInUrl('/info', 2);
2999
- * ```
3000
- *
3001
- * @param {string} urlPart value to check.
3002
- * @param {number} [sec=1] (optional, `1` by default) time in seconds to wait
3003
- * ⚠️ returns a _promise_ which is synchronized internally by recorder
3004
- *
3005
- */
3006
- async waitInUrl(urlPart, sec = null) {
3007
- const waitTimeout = sec ? sec * 1000 : this.options.waitForTimeout;
3008
-
3009
- return this.page.waitForFunction((urlPart) => {
3010
- const currUrl = decodeURIComponent(decodeURIComponent(decodeURIComponent(window.location.href)));
3011
- return currUrl.indexOf(urlPart) > -1;
3012
- }, { timeout: waitTimeout }, urlPart).catch(async (e) => {
3013
- const currUrl = await this._getPageUrl(); // Required because the waitForFunction can't return data.
3014
- if (/failed: timeout/i.test(e.message)) {
3015
- throw new Error(`expected url to include ${urlPart}, but found ${currUrl}`);
3016
- } else {
3017
- throw e;
3018
- }
3019
- });
3020
- }
3021
-
3022
- /**
3023
- * Waits for the entire URL to match the expected
3024
- *
3025
- * ```js
3026
- * I.waitUrlEquals('/info', 2);
3027
- * I.waitUrlEquals('http://127.0.0.1:8000/info');
3028
- * ```
3029
- *
3030
- * @param {string} urlPart value to check.
3031
- * @param {number} [sec=1] (optional, `1` by default) time in seconds to wait
3032
- * ⚠️ returns a _promise_ which is synchronized internally by recorder
3033
- *
3034
- */
3035
- async waitUrlEquals(urlPart, sec = null) {
3036
- const waitTimeout = sec ? sec * 1000 : this.options.waitForTimeout;
3037
-
3038
- const baseUrl = this.options.url;
3039
- if (urlPart.indexOf('http') < 0) {
3040
- urlPart = baseUrl + urlPart;
3041
- }
3042
-
3043
- return this.page.waitForFunction((urlPart) => {
3044
- const currUrl = decodeURIComponent(decodeURIComponent(decodeURIComponent(window.location.href)));
3045
- return currUrl.indexOf(urlPart) > -1;
3046
- }, { timeout: waitTimeout }, urlPart).catch(async (e) => {
3047
- const currUrl = await this._getPageUrl(); // Required because the waitForFunction can't return data.
3048
- if (/failed: timeout/i.test(e.message)) {
3049
- throw new Error(`expected url to be ${urlPart}, but found ${currUrl}`);
3050
- } else {
3051
- throw e;
3052
- }
3053
- });
3054
- }
3055
-
3056
- /**
3057
- * Waits for a text to appear (by default waits for 1sec).
3058
- * Element can be located by CSS or XPath.
3059
- * Narrow down search results by providing context.
3060
- *
3061
- * ```js
3062
- * I.waitForText('Thank you, form has been submitted');
3063
- * I.waitForText('Thank you, form has been submitted', 5, '#modal');
3064
- * ```
3065
- *
3066
- * @param {string }text to wait for.
3067
- * @param {number} [sec=1] (optional, `1` by default) time in seconds to wait
3068
- * @param {CodeceptJS.LocatorOrString} [context] (optional) element located by CSS|XPath|strict locator.
3069
- * ⚠️ returns a _promise_ which is synchronized internally by recorder
3070
- *
3071
- */
3072
- async waitForText(text, sec = null, context = null) {
3073
- const waitTimeout = sec ? sec * 1000 : this.options.waitForTimeout;
3074
- let waiter;
3075
-
3076
- const contextObject = await this._getContext();
3077
-
3078
- if (context) {
3079
- const locator = new Locator(context, 'css');
3080
- if (locator.isCSS()) {
3081
- waiter = contextObject.waitForFunction((locator, text) => {
3082
- const el = document.querySelector(locator);
3083
- if (!el) return false;
3084
- return el.innerText.indexOf(text) > -1;
3085
- }, { timeout: waitTimeout }, locator.value, text);
3086
- }
3087
-
3088
- if (locator.isXPath()) {
3089
- waiter = contextObject.waitForFunction((locator, text, $XPath) => {
3090
- eval($XPath); // eslint-disable-line no-eval
3091
- const el = $XPath(null, locator);
3092
- if (!el.length) return false;
3093
- return el[0].innerText.indexOf(text) > -1;
3094
- }, { timeout: waitTimeout }, locator.value, text, $XPath.toString());
3095
- }
3096
- } else {
3097
- waiter = contextObject.waitForFunction(text => document.body && document.body.innerText.indexOf(text) > -1, { timeout: waitTimeout }, text);
3098
- }
3099
-
3100
- return waiter.catch((err) => {
3101
- throw new Error(`Text "${text}" was not found on page after ${waitTimeout / 1000} sec\n${err.message}`);
3102
- });
3103
- }
3104
-
3105
- /**
3106
- * Waits for a network request.
3107
- *
3108
- * ```js
3109
- * I.waitForRequest('http://example.com/resource');
3110
- * I.waitForRequest(request => request.url() === 'http://example.com' && request.method() === 'GET');
3111
- * ```
3112
- *
3113
- * @param {string|function} urlOrPredicate
3114
- * @param {?number} [sec=null] seconds to wait
3115
- */
3116
- async waitForRequest(urlOrPredicate, sec = null) {
3117
- const timeout = sec ? sec * 1000 : this.options.waitForTimeout;
3118
- return this.page.waitForRequest(urlOrPredicate, { timeout });
3119
- }
3120
-
3121
- /**
3122
- * Waits for a network response.
3123
- *
3124
- * ```js
3125
- * I.waitForResponse('http://example.com/resource');
3126
- * I.waitForResponse(response => response.url() === 'http://example.com' && response.request().method() === 'GET');
3127
- * ```
3128
- *
3129
- * @param {string|function} urlOrPredicate
3130
- * @param {?number} [sec=null] number of seconds to wait
3131
- */
3132
- async waitForResponse(urlOrPredicate, sec = null) {
3133
- const timeout = sec ? sec * 1000 : this.options.waitForTimeout;
3134
- return this.page.waitForResponse(urlOrPredicate, { timeout });
3135
- }
3136
-
3137
- /**
3138
- * Switches frame or in case of null locator reverts to parent.
3139
- *
3140
- * ```js
3141
- * I.switchTo('iframe'); // switch to first iframe
3142
- * I.switchTo(); // switch back to main page
3143
- * ```
3144
- *
3145
- * @param {?CodeceptJS.LocatorOrString} [locator=null] (optional, `null` by default) element located by CSS|XPath|strict locator.
3146
- * ⚠️ returns a _promise_ which is synchronized internally by recorder
3147
- *
3148
- */
3149
- async switchTo(locator) {
3150
- if (Number.isInteger(locator)) {
3151
- // Select by frame index of current context
3152
-
3153
- let childFrames = null;
3154
- if (this.context && typeof this.context.childFrames === 'function') {
3155
- childFrames = this.context.childFrames();
3156
- } else {
3157
- childFrames = this.page.mainFrame().childFrames();
3158
- }
3159
-
3160
- if (locator >= 0 && locator < childFrames.length) {
3161
- this.context = childFrames[locator];
3162
- } else {
3163
- throw new Error('Element #invalidIframeSelector was not found by text|CSS|XPath');
3164
- }
3165
- return;
3166
- }
3167
- if (!locator) {
3168
- this.context = await this.page.mainFrame().$('body');
3169
- return;
3170
- }
3171
-
3172
- // iframe by selector
3173
- const els = await this._locate(locator);
3174
- assertElementExists(els, locator);
3175
- const contentFrame = await els[0].contentFrame();
3176
-
3177
- if (contentFrame) {
3178
- this.context = contentFrame;
3179
- } else {
3180
- this.context = els[0];
3181
- }
3182
- }
3183
-
3184
- /**
3185
- * Waits for a function to return true (waits for 1 sec by default).
3186
- * Running in browser context.
3187
- *
3188
- * ```js
3189
- * I.waitForFunction(fn[, [args[, timeout]])
3190
- * ```
3191
- *
3192
- * ```js
3193
- * I.waitForFunction(() => window.requests == 0);
3194
- * I.waitForFunction(() => window.requests == 0, 5); // waits for 5 sec
3195
- * I.waitForFunction((count) => window.requests == count, [3], 5) // pass args and wait for 5 sec
3196
- * ```
3197
- *
3198
- * @param {string|function} fn to be executed in browser context.
3199
- * @param {any[]|number} [argsOrSec] (optional, `1` by default) arguments for function or seconds.
3200
- * @param {number} [sec] (optional, `1` by default) time in seconds to wait
3201
- * ⚠️ returns a _promise_ which is synchronized internally by recorder
3202
- *
3203
- */
3204
- async waitForFunction(fn, argsOrSec = null, sec = null) {
3205
- let args = [];
3206
- if (argsOrSec) {
3207
- if (Array.isArray(argsOrSec)) {
3208
- args = argsOrSec;
3209
- } else if (typeof argsOrSec === 'number') {
3210
- sec = argsOrSec;
3211
- }
3212
- }
3213
- const waitTimeout = sec ? sec * 1000 : this.options.waitForTimeout;
3214
- const context = await this._getContext();
3215
- return context.waitForFunction(fn, { timeout: waitTimeout }, ...args);
3216
- }
3217
-
3218
- /**
3219
- * Waits for navigation to finish. By default takes configured `waitForNavigation` option.
3220
- *
3221
- * See [Pupeteer's reference](https://github.com/GoogleChrome/puppeteer/blob/master/docs/api.md#pagewaitfornavigationoptions)
3222
- *
3223
- * @param {*} opts
3224
- */
3225
- async waitForNavigation(opts = {}) {
3226
- opts = {
3227
- timeout: this.options.getPageTimeout,
3228
- waitUntil: this.options.waitForNavigation,
3229
- ...opts,
3230
- };
3231
- return this.page.waitForNavigation(opts);
3232
- }
3233
-
3234
- async waitUntilExists(locator, sec) {
3235
- console.log(`waitUntilExists deprecated:
3236
- * use 'waitForElement' to wait for element to be attached
3237
- * use 'waitForDetached to wait for element to be removed'`);
3238
- return this.waitForDetached(locator, sec);
3239
- }
3240
-
3241
- /**
3242
- * Waits for an element to become not attached to the DOM on a page (by default waits for 1sec).
3243
- * Element can be located by CSS or XPath.
3244
- *
3245
- * ```js
3246
- * I.waitForDetached('#popup');
3247
- * ```
3248
- *
3249
- * @param {CodeceptJS.LocatorOrString} locator element located by CSS|XPath|strict locator.
3250
- * @param {number} [sec=1] (optional, `1` by default) time in seconds to wait
3251
- * ⚠️ returns a _promise_ which is synchronized internally by recorder
3252
- *
3253
- */
3254
- async waitForDetached(locator, sec) {
3255
- const waitTimeout = sec ? sec * 1000 : this.options.waitForTimeout;
3256
- locator = new Locator(locator, 'css');
3257
-
3258
- let waiter;
3259
- const context = await this._getContext();
3260
- if (locator.isCSS()) {
3261
- const visibleFn = function (locator) {
3262
- return document.querySelector(locator) === null;
3263
- };
3264
- waiter = context.waitForFunction(visibleFn, { timeout: waitTimeout }, locator.value);
3265
- } else {
3266
- const visibleFn = function (locator, $XPath) {
3267
- eval($XPath); // eslint-disable-line no-eval
3268
- return $XPath(null, locator).length === 0;
3269
- };
3270
- waiter = context.waitForFunction(visibleFn, { timeout: waitTimeout }, locator.value, $XPath.toString());
3271
- }
3272
- return waiter.catch((err) => {
3273
- throw new Error(`element (${locator.toString()}) still on page after ${waitTimeout / 1000} sec\n${err.message}`);
3274
- });
3275
- }
3276
-
3277
- async _waitForAction() {
3278
- return this.wait(this.options.waitForAction / 1000);
3279
- }
3280
-
3281
- /**
3282
- * Grab the data from performance timing using Navigation Timing API.
3283
- * The returned data will contain following things in ms:
3284
- * - responseEnd,
3285
- * - domInteractive,
3286
- * - domContentLoadedEventEnd,
3287
- * - loadEventEnd
3288
- * Resumes test execution, so **should be used inside an async function with `await`** operator.
3289
- *
3290
- * ```js
3291
- * await I.amOnPage('https://example.com');
3292
- * let data = await I.grabDataFromPerformanceTiming();
3293
- * //Returned data
3294
- * { // all results are in [ms]
3295
- * responseEnd: 23,
3296
- * domInteractive: 44,
3297
- * domContentLoadedEventEnd: 196,
3298
- * loadEventEnd: 241
3299
- * }
3300
- * ```
3301
- * @return {Promise<any>} automatically synchronized promise through #recorder
3302
- */
3303
- async grabDataFromPerformanceTiming() {
3304
- return perfTiming;
3305
- }
3306
-
3307
- /**
3308
- * Grab the width, height, location of given locator.
3309
- * Provide `width` or `height`as second param to get your desired prop.
3310
- * Resumes test execution, so **should be used inside an async function with `await`** operator.
3311
- *
3312
- * Returns an object with `x`, `y`, `width`, `height` keys.
3313
- *
3314
- * ```js
3315
- * const value = await I.grabElementBoundingRect('h3');
3316
- * // value is like { x: 226.5, y: 89, width: 527, height: 220 }
3317
- * ```
3318
- *
3319
- * To get only one metric use second parameter:
3320
- *
3321
- * ```js
3322
- * const width = await I.grabElementBoundingRect('h3', 'width');
3323
- * // width == 527
3324
- * ```
3325
- * @param {LocatorOrString} locator element located by CSS|XPath|strict locator.
3326
- * @param {string=} elementSize x, y, width or height of the given element.
3327
- * @returns {Promise<DOMRect>|Promise<number>} Element bounding rectangle
3328
- *
3329
- */
3330
- async grabElementBoundingRect(locator, prop) {
3331
- const els = await this._locate(locator);
3332
- assertElementExists(els, locator);
3333
- const rect = await els[0].boundingBox();
3334
- if (prop) return rect[prop];
3335
- return rect;
3336
- }
3337
- }
3338
-
3339
- module.exports = Puppeteer;
3340
-
3341
- async function findElements(matcher, locator) {
3342
- if (locator.react) return findReact(matcher.executionContext(), locator);
3343
- locator = new Locator(locator, 'css');
3344
- if (!locator.isXPath()) return matcher.$$(locator.simplify());
3345
- return matcher.$x(locator.value);
3346
- }
3347
-
3348
- async function proceedClick(locator, context = null, options = {}) {
3349
- let matcher = await this.context;
3350
- if (context) {
3351
- const els = await this._locate(context);
3352
- assertElementExists(els, context);
3353
- matcher = els[0];
3354
- }
3355
- const els = await findClickable.call(this, matcher, locator);
3356
- if (context) {
3357
- assertElementExists(els, locator, 'Clickable element', `was not found inside element ${new Locator(context).toString()}`);
3358
- } else {
3359
- assertElementExists(els, locator, 'Clickable element');
3360
- }
3361
- await els[0].click(options);
3362
- const promises = [];
3363
- if (options.waitForNavigation) {
3364
- promises.push(this.waitForNavigation());
3365
- }
3366
- promises.push(this._waitForAction());
3367
- return Promise.all(promises);
3368
- }
3369
-
3370
- async function findClickable(matcher, locator) {
3371
- if (locator.react) return findReact(matcher.executionContext(), locator);
3372
- locator = new Locator(locator);
3373
- if (!locator.isFuzzy()) return findElements.call(this, matcher, locator);
3374
-
3375
- let els;
3376
- const literal = xpathLocator.literal(locator.value);
3377
-
3378
- els = await findElements.call(this, matcher, Locator.clickable.narrow(literal));
3379
- if (els.length) return els;
3380
-
3381
- els = await findElements.call(this, matcher, Locator.clickable.wide(literal));
3382
- if (els.length) return els;
3383
-
3384
- try {
3385
- els = await findElements.call(this, matcher, Locator.clickable.self(literal));
3386
- if (els.length) return els;
3387
- } catch (err) {
3388
- // Do nothing
3389
- }
3390
-
3391
- return findElements.call(this, matcher, locator.value); // by css or xpath
3392
- }
3393
-
3394
- async function proceedSee(assertType, text, context, strict = false) {
3395
- let description;
3396
- let allText;
3397
- if (!context) {
3398
- let el = await this.context;
3399
-
3400
- if (el && !el.getProperty) {
3401
- // Fallback to body
3402
- el = await this.context.$('body');
3403
- }
3404
-
3405
- allText = [await el.getProperty('innerText').then(p => p.jsonValue())];
3406
- description = 'web application';
3407
- } else {
3408
- const locator = new Locator(context, 'css');
3409
- description = `element ${locator.toString()}`;
3410
- const els = await this._locate(locator);
3411
- assertElementExists(els, locator.toString());
3412
- allText = await Promise.all(els.map(el => el.getProperty('innerText').then(p => p.jsonValue())));
3413
- }
3414
-
3415
- if (strict) {
3416
- return allText.map(elText => equals(description)[assertType](text, elText));
3417
- }
3418
- return stringIncludes(description)[assertType](text, allText.join(' | '));
3419
- }
3420
-
3421
- async function findCheckable(locator, context) {
3422
- let contextEl = await this.context;
3423
- if (typeof context === 'string') {
3424
- contextEl = await findElements.call(this, contextEl, (new Locator(context, 'css')).simplify());
3425
- contextEl = contextEl[0];
3426
- }
3427
-
3428
- const matchedLocator = new Locator(locator);
3429
- if (!matchedLocator.isFuzzy()) {
3430
- return findElements.call(this, contextEl, matchedLocator.simplify());
3431
- }
3432
-
3433
- const literal = xpathLocator.literal(locator);
3434
- let els = await findElements.call(this, contextEl, Locator.checkable.byText(literal));
3435
- if (els.length) {
3436
- return els;
3437
- }
3438
- els = await findElements.call(this, contextEl, Locator.checkable.byName(literal));
3439
- if (els.length) {
3440
- return els;
3441
- }
3442
- return findElements.call(this, contextEl, locator);
3443
- }
3444
-
3445
- async function proceedIsChecked(assertType, option) {
3446
- let els = await findCheckable.call(this, option);
3447
- assertElementExists(els, option, 'Checkable');
3448
- els = await Promise.all(els.map(el => el.getProperty('checked')));
3449
- els = await Promise.all(els.map(el => el.jsonValue()));
3450
- const selected = els.reduce((prev, cur) => prev || cur);
3451
- return truth(`checkable ${option}`, 'to be checked')[assertType](selected);
3452
- }
3453
-
3454
- async function findVisibleFields(locator) {
3455
- const els = await findFields.call(this, locator);
3456
- const visible = await Promise.all(els.map(el => el.boundingBox()));
3457
- return els.filter((el, index) => visible[index]);
3458
- }
3459
-
3460
- async function findFields(locator) {
3461
- const matchedLocator = new Locator(locator);
3462
- if (!matchedLocator.isFuzzy()) {
3463
- return this._locate(matchedLocator);
3464
- }
3465
- const literal = xpathLocator.literal(locator);
3466
-
3467
- let els = await this._locate({ xpath: Locator.field.labelEquals(literal) });
3468
- if (els.length) {
3469
- return els;
3470
- }
3471
-
3472
- els = await this._locate({ xpath: Locator.field.labelContains(literal) });
3473
- if (els.length) {
3474
- return els;
3475
- }
3476
- els = await this._locate({ xpath: Locator.field.byName(literal) });
3477
- if (els.length) {
3478
- return els;
3479
- }
3480
- return this._locate({ css: locator });
3481
- }
3482
-
3483
- async function proceedDragAndDrop(sourceLocator, destinationLocator) {
3484
- const src = await this._locate(sourceLocator);
3485
- assertElementExists(src, sourceLocator, 'Source Element');
3486
-
3487
- const dst = await this._locate(destinationLocator);
3488
- assertElementExists(dst, destinationLocator, 'Destination Element');
3489
-
3490
- // Note: Using public api .getClickablePoint becaues the .BoundingBox does not take into account iframe offsets
3491
- const dragSource = await getClickablePoint(src[0]);
3492
- const dragDestination = await getClickablePoint(dst[0]);
3493
-
3494
- // Drag start point
3495
- await this.page.mouse.move(dragSource.x, dragSource.y, { steps: 5 });
3496
- await this.page.mouse.down();
3497
-
3498
- // Drag destination
3499
- await this.page.mouse.move(dragDestination.x, dragDestination.y, { steps: 5 });
3500
- await this.page.mouse.up();
3501
-
3502
- await this._waitForAction();
3503
- }
3504
-
3505
- async function proceedSeeInField(assertType, field, value) {
3506
- const els = await findVisibleFields.call(this, field);
3507
- assertElementExists(els, field, 'Field');
3508
- const el = els[0];
3509
- const tag = await el.getProperty('tagName').then(el => el.jsonValue());
3510
- const fieldType = await el.getProperty('type').then(el => el.jsonValue());
3511
-
3512
- const proceedMultiple = async (elements) => {
3513
- const fields = Array.isArray(elements) ? elements : [elements];
3514
-
3515
- const elementValues = [];
3516
- for (const element of fields) {
3517
- elementValues.push(await element.getProperty('value').then(el => el.jsonValue()));
3518
- }
3519
-
3520
- if (typeof value === 'boolean') {
3521
- equals(`no. of items matching > 0: ${field}`)[assertType](value, !!elementValues.length);
3522
- } else {
3523
- if (assertType === 'assert') {
3524
- equals(`select option by ${field}`)[assertType](true, elementValues.length > 0);
3525
- }
3526
- elementValues.forEach(val => stringIncludes(`fields by ${field}`)[assertType](value, val));
3527
- }
3528
- };
3529
-
3530
- if (tag === 'SELECT') {
3531
- const selectedOptions = await el.$$('option:checked');
3532
- // locate option by values and check them
3533
- if (value === '') {
3534
- return proceedMultiple(selectedOptions);
3535
- }
3536
-
3537
- const options = await filterFieldsByValue(selectedOptions, value, true);
3538
- return proceedMultiple(options);
3539
- }
3540
-
3541
- if (tag === 'INPUT') {
3542
- if (fieldType === 'checkbox' || fieldType === 'radio') {
3543
- if (typeof value === 'boolean') {
3544
- // Filter by values
3545
- const options = await filterFieldsBySelectionState(els, true);
3546
- return proceedMultiple(options);
3547
- }
3548
-
3549
- const options = await filterFieldsByValue(els, value, true);
3550
- return proceedMultiple(options);
3551
- }
3552
- return proceedMultiple(els[0]);
3553
- }
3554
- const fieldVal = await el.getProperty('value').then(el => el.jsonValue());
3555
- return stringIncludes(`fields by ${field}`)[assertType](value, fieldVal);
3556
- }
3557
-
3558
- async function filterFieldsByValue(elements, value, onlySelected) {
3559
- const matches = [];
3560
- for (const element of elements) {
3561
- const val = await element.getProperty('value').then(el => el.jsonValue());
3562
- let isSelected = true;
3563
- if (onlySelected) {
3564
- isSelected = await elementSelected(element);
3565
- }
3566
- if ((value == null || val.indexOf(value) > -1) && isSelected) {
3567
- matches.push(element);
3568
- }
3569
- }
3570
- return matches;
3571
- }
3572
-
3573
- async function filterFieldsBySelectionState(elements, state) {
3574
- const matches = [];
3575
- for (const element of elements) {
3576
- const isSelected = await elementSelected(element);
3577
- if (isSelected === state) {
3578
- matches.push(element);
3579
- }
3580
- }
3581
- return matches;
3582
- }
3583
-
3584
- async function elementSelected(element) {
3585
- const type = await element.getProperty('type').then(el => el.jsonValue());
3586
-
3587
- if (type === 'checkbox' || type === 'radio') {
3588
- return element.getProperty('checked').then(el => el.jsonValue());
3589
- }
3590
- return element.getProperty('selected').then(el => el.jsonValue());
3591
- }
3592
-
3593
- function isFrameLocator(locator) {
3594
- locator = new Locator(locator);
3595
- if (locator.isFrame()) return locator.value;
3596
- return false;
3597
- }
3598
-
3599
- function assertElementExists(res, locator, prefix, suffix) {
3600
- if (!res || res.length === 0) {
3601
- throw new ElementNotFound(locator, prefix, suffix);
3602
- }
3603
- }
3604
-
3605
- function $XPath(element, selector) {
3606
- const found = document.evaluate(selector, element || document.body, null, 5, null);
3607
- const res = [];
3608
- let current = null;
3609
- while (current = found.iterateNext()) {
3610
- res.push(current);
3611
- }
3612
- return res;
3613
- }
3614
-
3615
- async function targetCreatedHandler(page) {
3616
- if (!page) return;
3617
- this.withinLocator = null;
3618
- page.on('load', () => {
3619
- page.$('body')
3620
- .catch(() => null)
3621
- .then(context => this.context = context);
3622
- });
3623
- page.on('console', (msg) => {
3624
- this.debugSection(`Browser:${ucfirst(msg.type())}`, (msg._text || '') + msg.args().join(' '));
3625
- consoleLogStore.add(msg);
3626
- });
3627
-
3628
- if (this.options.userAgent) {
3629
- await page.setUserAgent(this.options.userAgent);
3630
- }
3631
- if (this.options.windowSize && this.options.windowSize.indexOf('x') > 0) {
3632
- const dimensions = this.options.windowSize.split('x');
3633
- const width = parseInt(dimensions[0], 10);
3634
- const height = parseInt(dimensions[1], 10);
3635
- await page.setViewport({ width, height });
3636
- }
3637
- }
3638
-
3639
- // BC compatibility for Puppeteer < 10
3640
- async function getClickablePoint(el) {
3641
- if (el.clickablePoint) return el.clickablePoint();
3642
- if (el._clickablePoint) return el._clickablePoint();
3643
- return null;
3644
- }
3645
-
3646
- // List of key values to key definitions
3647
- // https://github.com/GoogleChrome/puppeteer/blob/v1.20.0/lib/USKeyboardLayout.js
3648
- const keyDefinitionMap = {
3649
- /* eslint-disable quote-props */
3650
- '0': 'Digit0',
3651
- '1': 'Digit1',
3652
- '2': 'Digit2',
3653
- '3': 'Digit3',
3654
- '4': 'Digit4',
3655
- '5': 'Digit5',
3656
- '6': 'Digit6',
3657
- '7': 'Digit7',
3658
- '8': 'Digit8',
3659
- '9': 'Digit9',
3660
- 'a': 'KeyA',
3661
- 'b': 'KeyB',
3662
- 'c': 'KeyC',
3663
- 'd': 'KeyD',
3664
- 'e': 'KeyE',
3665
- 'f': 'KeyF',
3666
- 'g': 'KeyG',
3667
- 'h': 'KeyH',
3668
- 'i': 'KeyI',
3669
- 'j': 'KeyJ',
3670
- 'k': 'KeyK',
3671
- 'l': 'KeyL',
3672
- 'm': 'KeyM',
3673
- 'n': 'KeyN',
3674
- 'o': 'KeyO',
3675
- 'p': 'KeyP',
3676
- 'q': 'KeyQ',
3677
- 'r': 'KeyR',
3678
- 's': 'KeyS',
3679
- 't': 'KeyT',
3680
- 'u': 'KeyU',
3681
- 'v': 'KeyV',
3682
- 'w': 'KeyW',
3683
- 'x': 'KeyX',
3684
- 'y': 'KeyY',
3685
- 'z': 'KeyZ',
3686
- ';': 'Semicolon',
3687
- '=': 'Equal',
3688
- ',': 'Comma',
3689
- '-': 'Minus',
3690
- '.': 'Period',
3691
- '/': 'Slash',
3692
- '`': 'Backquote',
3693
- '[': 'BracketLeft',
3694
- '\\': 'Backslash',
3695
- ']': 'BracketRight',
3696
- '\'': 'Quote',
3697
- /* eslint-enable quote-props */
3698
- };
3699
-
3700
- function getNormalizedKey(key) {
3701
- const normalizedKey = getNormalizedKeyAttributeValue(key);
3702
- if (key !== normalizedKey) {
3703
- this.debugSection('Input', `Mapping key '${key}' to '${normalizedKey}'`);
3704
- }
3705
- // Use key definition to ensure correct key is displayed when Shift modifier is active
3706
- if (Object.prototype.hasOwnProperty.call(keyDefinitionMap, normalizedKey)) {
3707
- return keyDefinitionMap[normalizedKey];
3708
- }
3709
- return normalizedKey;
3710
- }