codeceptjs 3.5.10 → 3.5.12-beta.1

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