codeceptjs 3.5.0 → 3.5.1-2.beta.7

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