codeceptjs 3.5.0 → 3.5.1-2.beta.7

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