codeceptjs 3.4.1 → 3.5.1-2.beta.7

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