codeceptjs 3.4.1 → 3.5.1-2.beta.7

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (281) hide show
  1. package/README.md +31 -30
  2. package/bin/codecept.js +1 -1
  3. package/lib/actor.js +6 -3
  4. package/lib/ai.js +180 -0
  5. package/lib/cli.js +13 -3
  6. package/lib/codecept.js +8 -0
  7. package/lib/colorUtils.js +10 -0
  8. package/lib/command/definitions.js +2 -7
  9. package/lib/command/dryRun.js +11 -2
  10. package/lib/command/generate.js +46 -3
  11. package/lib/command/info.js +24 -0
  12. package/lib/command/init.js +64 -6
  13. package/lib/command/interactive.js +15 -1
  14. package/lib/command/run-multiple/collection.js +17 -5
  15. package/lib/command/run-multiple.js +4 -2
  16. package/lib/command/run-workers.js +68 -5
  17. package/lib/command/run.js +7 -0
  18. package/lib/command/workers/runTests.js +39 -0
  19. package/lib/container.js +13 -3
  20. package/lib/data/context.js +14 -6
  21. package/lib/event.js +4 -0
  22. package/lib/helper/ApiDataFactory.js +2 -1
  23. package/lib/helper/Appium.js +116 -29
  24. package/lib/helper/Expect.js +422 -0
  25. package/lib/helper/FileSystem.js +1 -1
  26. package/lib/helper/GraphQL.js +25 -0
  27. package/lib/helper/JSONResponse.js +4 -4
  28. package/lib/helper/Nightmare.js +10 -5
  29. package/lib/helper/OpenAI.js +126 -0
  30. package/lib/helper/Playwright.js +1298 -229
  31. package/lib/helper/Protractor.js +12 -7
  32. package/lib/helper/Puppeteer.js +204 -64
  33. package/lib/helper/REST.js +15 -5
  34. package/lib/helper/TestCafe.js +45 -10
  35. package/lib/helper/WebDriver.js +252 -83
  36. package/lib/helper/errors/ElementNotFound.js +2 -1
  37. package/lib/helper/extras/PlaywrightReactVueLocator.js +38 -0
  38. package/lib/helper/scripts/blurElement.js +17 -0
  39. package/lib/helper/scripts/focusElement.js +17 -0
  40. package/lib/helper/scripts/highlightElement.js +20 -0
  41. package/lib/html.js +258 -0
  42. package/lib/interfaces/bdd.js +1 -1
  43. package/lib/interfaces/gherkin.js +37 -3
  44. package/lib/interfaces/scenarioConfig.js +1 -0
  45. package/lib/listener/retry.js +2 -1
  46. package/lib/locator.js +17 -4
  47. package/lib/mochaFactory.js +2 -1
  48. package/lib/output.js +1 -1
  49. package/lib/pause.js +78 -19
  50. package/lib/plugin/autoLogin.js +45 -10
  51. package/lib/plugin/debugErrors.js +67 -0
  52. package/lib/plugin/fakerTransform.js +4 -6
  53. package/lib/plugin/heal.js +209 -0
  54. package/lib/plugin/retryFailedStep.js +10 -1
  55. package/lib/plugin/retryTo.js +2 -4
  56. package/lib/plugin/screenshotOnFail.js +11 -2
  57. package/lib/plugin/selenoid.js +6 -1
  58. package/lib/plugin/standardActingHelpers.js +0 -2
  59. package/lib/plugin/stepByStepReport.js +2 -2
  60. package/lib/plugin/tryTo.js +5 -7
  61. package/lib/plugin/wdio.js +0 -1
  62. package/lib/recorder.js +22 -11
  63. package/lib/secret.js +5 -4
  64. package/lib/session.js +1 -1
  65. package/lib/step.js +36 -12
  66. package/lib/ui.js +5 -3
  67. package/lib/utils.js +22 -1
  68. package/lib/workers.js +83 -10
  69. package/package.json +117 -95
  70. package/translations/de-DE.js +5 -0
  71. package/translations/fr-FR.js +14 -1
  72. package/translations/it-IT.js +1 -0
  73. package/translations/ja-JP.js +14 -9
  74. package/translations/pl-PL.js +5 -0
  75. package/translations/pt-BR.js +1 -0
  76. package/translations/ru-RU.js +1 -0
  77. package/translations/zh-CN.js +5 -0
  78. package/translations/zh-TW.js +5 -0
  79. package/typings/index.d.ts +51 -15
  80. package/typings/promiseBasedTypes.d.ts +864 -802
  81. package/typings/types.d.ts +1339 -744
  82. package/CHANGELOG.md +0 -2427
  83. package/docs/advanced.md +0 -351
  84. package/docs/api.md +0 -323
  85. package/docs/basics.md +0 -980
  86. package/docs/bdd.md +0 -535
  87. package/docs/best.md +0 -237
  88. package/docs/books.md +0 -37
  89. package/docs/bootstrap.md +0 -135
  90. package/docs/build/ApiDataFactory.js +0 -409
  91. package/docs/build/Appium.js +0 -1938
  92. package/docs/build/FileSystem.js +0 -228
  93. package/docs/build/GraphQL.js +0 -204
  94. package/docs/build/GraphQLDataFactory.js +0 -309
  95. package/docs/build/JSONResponse.js +0 -338
  96. package/docs/build/Mochawesome.js +0 -71
  97. package/docs/build/Nightmare.js +0 -2145
  98. package/docs/build/Playwright.js +0 -3986
  99. package/docs/build/Polly.js +0 -42
  100. package/docs/build/Protractor.js +0 -2699
  101. package/docs/build/Puppeteer.js +0 -3710
  102. package/docs/build/REST.js +0 -334
  103. package/docs/build/SeleniumWebdriver.js +0 -76
  104. package/docs/build/TestCafe.js +0 -2057
  105. package/docs/build/WebDriver.js +0 -4017
  106. package/docs/changelog.md +0 -2436
  107. package/docs/commands.md +0 -254
  108. package/docs/community-helpers.md +0 -58
  109. package/docs/configuration.md +0 -157
  110. package/docs/continuous-integration.md +0 -22
  111. package/docs/custom-helpers.md +0 -306
  112. package/docs/data.md +0 -375
  113. package/docs/detox.md +0 -235
  114. package/docs/docker.md +0 -137
  115. package/docs/email.md +0 -183
  116. package/docs/examples.md +0 -149
  117. package/docs/helpers/ApiDataFactory.md +0 -266
  118. package/docs/helpers/Appium.md +0 -1312
  119. package/docs/helpers/Detox.md +0 -586
  120. package/docs/helpers/FileSystem.md +0 -152
  121. package/docs/helpers/GraphQL.md +0 -130
  122. package/docs/helpers/GraphQLDataFactory.md +0 -226
  123. package/docs/helpers/JSONResponse.md +0 -254
  124. package/docs/helpers/Mochawesome.md +0 -8
  125. package/docs/helpers/MockRequest.md +0 -377
  126. package/docs/helpers/Nightmare.md +0 -1256
  127. package/docs/helpers/Playwright.md +0 -2208
  128. package/docs/helpers/Polly.md +0 -44
  129. package/docs/helpers/Puppeteer-firefox.md +0 -86
  130. package/docs/helpers/Puppeteer.md +0 -2141
  131. package/docs/helpers/REST.md +0 -217
  132. package/docs/helpers/TestCafe.md +0 -1222
  133. package/docs/helpers/WebDriver.md +0 -2319
  134. package/docs/hooks.md +0 -340
  135. package/docs/index.md +0 -111
  136. package/docs/installation.md +0 -75
  137. package/docs/internal-api.md +0 -265
  138. package/docs/locators.md +0 -331
  139. package/docs/mobile-react-native-locators.md +0 -67
  140. package/docs/mobile.md +0 -297
  141. package/docs/nightmare.md +0 -223
  142. package/docs/pageobjects.md +0 -291
  143. package/docs/parallel.md +0 -232
  144. package/docs/playwright.md +0 -609
  145. package/docs/plugins.md +0 -1171
  146. package/docs/puppeteer.md +0 -316
  147. package/docs/quickstart.md +0 -163
  148. package/docs/react.md +0 -69
  149. package/docs/reports.md +0 -392
  150. package/docs/secrets.md +0 -30
  151. package/docs/shadow.md +0 -68
  152. package/docs/shared/keys.mustache +0 -31
  153. package/docs/shared/react.mustache +0 -1
  154. package/docs/testcafe.md +0 -174
  155. package/docs/translation.md +0 -247
  156. package/docs/tutorial.md +0 -271
  157. package/docs/typescript.md +0 -180
  158. package/docs/ui.md +0 -59
  159. package/docs/videos.md +0 -28
  160. package/docs/visual.md +0 -202
  161. package/docs/vue.md +0 -121
  162. package/docs/webapi/amOnPage.mustache +0 -11
  163. package/docs/webapi/appendField.mustache +0 -9
  164. package/docs/webapi/attachFile.mustache +0 -12
  165. package/docs/webapi/checkOption.mustache +0 -13
  166. package/docs/webapi/clearCookie.mustache +0 -10
  167. package/docs/webapi/clearField.mustache +0 -9
  168. package/docs/webapi/click.mustache +0 -25
  169. package/docs/webapi/clickLink.mustache +0 -8
  170. package/docs/webapi/closeCurrentTab.mustache +0 -7
  171. package/docs/webapi/closeOtherTabs.mustache +0 -8
  172. package/docs/webapi/dontSee.mustache +0 -11
  173. package/docs/webapi/dontSeeCheckboxIsChecked.mustache +0 -10
  174. package/docs/webapi/dontSeeCookie.mustache +0 -8
  175. package/docs/webapi/dontSeeCurrentUrlEquals.mustache +0 -10
  176. package/docs/webapi/dontSeeElement.mustache +0 -8
  177. package/docs/webapi/dontSeeElementInDOM.mustache +0 -8
  178. package/docs/webapi/dontSeeInCurrentUrl.mustache +0 -4
  179. package/docs/webapi/dontSeeInField.mustache +0 -11
  180. package/docs/webapi/dontSeeInSource.mustache +0 -8
  181. package/docs/webapi/dontSeeInTitle.mustache +0 -8
  182. package/docs/webapi/doubleClick.mustache +0 -13
  183. package/docs/webapi/downloadFile.mustache +0 -12
  184. package/docs/webapi/dragAndDrop.mustache +0 -9
  185. package/docs/webapi/dragSlider.mustache +0 -11
  186. package/docs/webapi/executeAsyncScript.mustache +0 -24
  187. package/docs/webapi/executeScript.mustache +0 -26
  188. package/docs/webapi/fillField.mustache +0 -16
  189. package/docs/webapi/forceClick.mustache +0 -28
  190. package/docs/webapi/forceRightClick.mustache +0 -18
  191. package/docs/webapi/grabAllWindowHandles.mustache +0 -7
  192. package/docs/webapi/grabAttributeFrom.mustache +0 -10
  193. package/docs/webapi/grabAttributeFromAll.mustache +0 -9
  194. package/docs/webapi/grabBrowserLogs.mustache +0 -9
  195. package/docs/webapi/grabCookie.mustache +0 -11
  196. package/docs/webapi/grabCssPropertyFrom.mustache +0 -11
  197. package/docs/webapi/grabCssPropertyFromAll.mustache +0 -10
  198. package/docs/webapi/grabCurrentUrl.mustache +0 -9
  199. package/docs/webapi/grabCurrentWindowHandle.mustache +0 -6
  200. package/docs/webapi/grabDataFromPerformanceTiming.mustache +0 -20
  201. package/docs/webapi/grabElementBoundingRect.mustache +0 -20
  202. package/docs/webapi/grabGeoLocation.mustache +0 -8
  203. package/docs/webapi/grabHTMLFrom.mustache +0 -10
  204. package/docs/webapi/grabHTMLFromAll.mustache +0 -9
  205. package/docs/webapi/grabNumberOfOpenTabs.mustache +0 -8
  206. package/docs/webapi/grabNumberOfVisibleElements.mustache +0 -9
  207. package/docs/webapi/grabPageScrollPosition.mustache +0 -8
  208. package/docs/webapi/grabPopupText.mustache +0 -5
  209. package/docs/webapi/grabSource.mustache +0 -8
  210. package/docs/webapi/grabTextFrom.mustache +0 -10
  211. package/docs/webapi/grabTextFromAll.mustache +0 -9
  212. package/docs/webapi/grabTitle.mustache +0 -8
  213. package/docs/webapi/grabValueFrom.mustache +0 -9
  214. package/docs/webapi/grabValueFromAll.mustache +0 -8
  215. package/docs/webapi/moveCursorTo.mustache +0 -12
  216. package/docs/webapi/openNewTab.mustache +0 -7
  217. package/docs/webapi/pressKey.mustache +0 -12
  218. package/docs/webapi/pressKeyDown.mustache +0 -12
  219. package/docs/webapi/pressKeyUp.mustache +0 -12
  220. package/docs/webapi/pressKeyWithKeyNormalization.mustache +0 -60
  221. package/docs/webapi/refreshPage.mustache +0 -6
  222. package/docs/webapi/resizeWindow.mustache +0 -6
  223. package/docs/webapi/rightClick.mustache +0 -14
  224. package/docs/webapi/saveElementScreenshot.mustache +0 -10
  225. package/docs/webapi/saveScreenshot.mustache +0 -12
  226. package/docs/webapi/say.mustache +0 -10
  227. package/docs/webapi/scrollIntoView.mustache +0 -11
  228. package/docs/webapi/scrollPageToBottom.mustache +0 -6
  229. package/docs/webapi/scrollPageToTop.mustache +0 -6
  230. package/docs/webapi/scrollTo.mustache +0 -12
  231. package/docs/webapi/see.mustache +0 -11
  232. package/docs/webapi/seeAttributesOnElements.mustache +0 -9
  233. package/docs/webapi/seeCheckboxIsChecked.mustache +0 -10
  234. package/docs/webapi/seeCookie.mustache +0 -8
  235. package/docs/webapi/seeCssPropertiesOnElements.mustache +0 -9
  236. package/docs/webapi/seeCurrentUrlEquals.mustache +0 -11
  237. package/docs/webapi/seeElement.mustache +0 -8
  238. package/docs/webapi/seeElementInDOM.mustache +0 -8
  239. package/docs/webapi/seeInCurrentUrl.mustache +0 -8
  240. package/docs/webapi/seeInField.mustache +0 -12
  241. package/docs/webapi/seeInPopup.mustache +0 -8
  242. package/docs/webapi/seeInSource.mustache +0 -7
  243. package/docs/webapi/seeInTitle.mustache +0 -8
  244. package/docs/webapi/seeNumberOfElements.mustache +0 -11
  245. package/docs/webapi/seeNumberOfVisibleElements.mustache +0 -10
  246. package/docs/webapi/seeTextEquals.mustache +0 -9
  247. package/docs/webapi/seeTitleEquals.mustache +0 -8
  248. package/docs/webapi/selectOption.mustache +0 -21
  249. package/docs/webapi/setCookie.mustache +0 -16
  250. package/docs/webapi/setGeoLocation.mustache +0 -12
  251. package/docs/webapi/switchTo.mustache +0 -9
  252. package/docs/webapi/switchToNextTab.mustache +0 -10
  253. package/docs/webapi/switchToPreviousTab.mustache +0 -10
  254. package/docs/webapi/type.mustache +0 -18
  255. package/docs/webapi/uncheckOption.mustache +0 -13
  256. package/docs/webapi/wait.mustache +0 -8
  257. package/docs/webapi/waitForClickable.mustache +0 -11
  258. package/docs/webapi/waitForDetached.mustache +0 -10
  259. package/docs/webapi/waitForElement.mustache +0 -11
  260. package/docs/webapi/waitForEnabled.mustache +0 -6
  261. package/docs/webapi/waitForFunction.mustache +0 -17
  262. package/docs/webapi/waitForInvisible.mustache +0 -10
  263. package/docs/webapi/waitForText.mustache +0 -13
  264. package/docs/webapi/waitForValue.mustache +0 -10
  265. package/docs/webapi/waitForVisible.mustache +0 -10
  266. package/docs/webapi/waitInUrl.mustache +0 -9
  267. package/docs/webapi/waitNumberOfVisibleElements.mustache +0 -10
  268. package/docs/webapi/waitToHide.mustache +0 -10
  269. package/docs/webapi/waitUrlEquals.mustache +0 -10
  270. package/docs/webdriver.md +0 -657
  271. package/docs/wiki/Books-&-Posts.md +0 -27
  272. package/docs/wiki/Community-Helpers-&-Plugins.md +0 -49
  273. package/docs/wiki/Converting-Playwright-to-Istanbul-Coverage.md +0 -29
  274. package/docs/wiki/Examples.md +0 -139
  275. package/docs/wiki/Google-Summer-of-Code-(GSoC)-2020.md +0 -68
  276. package/docs/wiki/Home.md +0 -16
  277. package/docs/wiki/Release-Process.md +0 -24
  278. package/docs/wiki/Roadmap.md +0 -23
  279. package/docs/wiki/Tests.md +0 -1393
  280. package/docs/wiki/Upgrading-to-CodeceptJS-3.md +0 -153
  281. package/docs/wiki/Videos.md +0 -19
@@ -1,2699 +0,0 @@
1
- let EC;
2
- let Key;
3
- let Button;
4
- let ProtractorBy;
5
- let ProtractorExpectedConditions;
6
-
7
- const path = require('path');
8
-
9
- const Helper = require('@codeceptjs/helper');
10
- const stringIncludes = require('../assert/include').includes;
11
- const { urlEquals, equals } = require('../assert/equal');
12
- const { empty } = require('../assert/empty');
13
- const { truth } = require('../assert/truth');
14
- const {
15
- xpathLocator,
16
- fileExists,
17
- convertCssPropertiesToCamelCase,
18
- screenshotOutputFolder,
19
- } = require('../utils');
20
- const {
21
- isColorProperty,
22
- convertColorToRGBA,
23
- } = require('../colorUtils');
24
- const ElementNotFound = require('./errors/ElementNotFound');
25
- const ConnectionRefused = require('./errors/ConnectionRefused');
26
- const Locator = require('../locator');
27
-
28
- let withinStore = {};
29
- let Runner;
30
-
31
- /**
32
- * Protractor helper is based on [Protractor library](http://www.protractortest.org) and used for testing web applications.
33
- *
34
- * Protractor requires [Selenium Server and ChromeDriver/GeckoDriver to be installed](http://codecept.io/quickstart/#prepare-selenium-server).
35
- * To test non-Angular applications please make sure you have `angular: false` in configuration file.
36
- *
37
- * ### Configuration
38
- *
39
- * This helper should be configured in codecept.conf.ts or codecept.conf.js
40
- *
41
- * * `url` - base url of website to be tested
42
- * * `browser` - browser in which perform testing
43
- * * `angular` (optional, default: true): disable this option to run tests for non-Angular applications.
44
- * * `driver` - which protractor driver to use (local, direct, session, hosted, sauce, browserstack). By default set to 'hosted' which requires selenium server to be started.
45
- * * `restart` (optional, default: true) - restart browser between tests.
46
- * * `smartWait`: (optional) **enables [SmartWait](http://codecept.io/acceptance/#smartwait)**; wait for additional milliseconds for element to appear. Enable for 5 secs: "smartWait": 5000
47
- * * `disableScreenshots` (optional, default: false) - don't save screenshot on failure
48
- * * `fullPageScreenshots` (optional, default: false) - make full page screenshots on failure.
49
- * * `uniqueScreenshotNames` (optional, default: false) - option to prevent screenshot override if you have scenarios with the same name in different suites
50
- * * `keepBrowserState` (optional, default: false) - keep browser state between tests when `restart` set to false.
51
- * * `seleniumAddress` - Selenium address to connect (default: http://localhost:4444/wd/hub)
52
- * * `rootElement` - Root element of AngularJS application (default: body)
53
- * * `getPageTimeout` (optional) sets default timeout for a page to be loaded. 10000 by default.
54
- * * `waitForTimeout`: (optional) sets default wait time in _ms_ for all `wait*` functions. 1000 by default.
55
- * * `scriptsTimeout`: (optional) timeout in milliseconds for each script run on the browser, 10000 by default.
56
- * * `windowSize`: (optional) default window size. Set to `maximize` or a dimension in the format `640x480`.
57
- * * `manualStart` (optional, default: false) - do not start browser before a test, start it manually inside a helper with `this.helpers.WebDriver._startBrowser()`
58
- * * `capabilities`: {} - list of [Desired Capabilities](https://github.com/SeleniumHQ/selenium/wiki/DesiredCapabilities)
59
- * * `proxy`: set proxy settings
60
- *
61
- * other options are the same as in [Protractor config](https://github.com/angular/protractor/blob/master/docs/referenceConf.js).
62
- *
63
- * #### Sample Config
64
- *
65
- * ```json
66
- * {
67
- * "helpers": {
68
- * "Protractor" : {
69
- * "url": "http://localhost",
70
- * "browser": "chrome",
71
- * "smartWait": 5000,
72
- * "restart": false
73
- * }
74
- * }
75
- * }
76
- * ```
77
- *
78
- * #### Config for Non-Angular application:
79
- *
80
- * ```json
81
- * {
82
- * "helpers": {
83
- * "Protractor" : {
84
- * "url": "http://localhost",
85
- * "browser": "chrome",
86
- * "angular": false
87
- * }
88
- * }
89
- * }
90
- * ```
91
- *
92
- * #### Config for Headless Chrome
93
- *
94
- * ```json
95
- * {
96
- * "helpers": {
97
- * "Protractor" : {
98
- * "url": "http://localhost",
99
- * "browser": "chrome",
100
- * "capabilities": {
101
- * "chromeOptions": {
102
- * "args": [ "--headless", "--disable-gpu", "--no-sandbox" ]
103
- * }
104
- * }
105
- * }
106
- * }
107
- * }
108
- * ```
109
- *
110
- * ## Access From Helpers
111
- *
112
- * Receive a WebDriverIO client from a custom helper by accessing `browser` property:
113
- *
114
- * ```js
115
- * this.helpers['Protractor'].browser
116
- * ```
117
- *
118
- * ## Methods
119
- */
120
- class Protractor extends Helper {
121
- constructor(config) {
122
- // process.env.SELENIUM_PROMISE_MANAGER = false; // eslint-disable-line
123
- super(config);
124
-
125
- this.isRunning = false;
126
- this._setConfig(config);
127
-
128
- console.log('Protractor helper is deprecated as well as Protractor itself.\nThis helper will be removed in next major release');
129
- }
130
-
131
- _validateConfig(config) {
132
- const defaults = {
133
- browser: 'chrome',
134
- url: 'http://localhost',
135
- seleniumAddress: 'http://localhost:4444/wd/hub',
136
- fullPageScreenshots: false,
137
- rootElement: 'body',
138
- allScriptsTimeout: 10000,
139
- scriptTimeout: 10000,
140
- waitForTimeout: 1000, // ms
141
- windowSize: null,
142
- getPageTimeout: 10000,
143
- driver: 'hosted',
144
- capabilities: {},
145
- angular: true,
146
- restart: true,
147
- };
148
-
149
- config = Object.assign(defaults, config);
150
-
151
- if (!config.allScriptsTimeout) config.allScriptsTimeout = config.scriptsTimeout;
152
- if (!config.scriptTimeout) config.scriptTimeout = config.scriptsTimeout;
153
- if (config.proxy) config.capabilities.proxy = config.proxy;
154
- if (config.browser) config.capabilities.browserName = config.browser;
155
-
156
- config.waitForTimeoutInSeconds = config.waitForTimeout / 1000; // convert to seconds
157
- return config;
158
- }
159
-
160
- async _init() {
161
- process.on('unhandledRejection', (reason) => {
162
- if (reason.message.indexOf('ECONNREFUSED') > 0) {
163
- this.browser = null;
164
- }
165
- });
166
-
167
- Runner = require('protractor/built/runner').Runner;
168
- ProtractorBy = require('protractor').ProtractorBy;
169
- Key = require('protractor').Key;
170
- Button = require('protractor').Button;
171
- ProtractorExpectedConditions = require('protractor').ProtractorExpectedConditions;
172
-
173
- return Promise.resolve();
174
- }
175
-
176
- static _checkRequirements() {
177
- try {
178
- require('protractor');
179
- require('assert').ok(require('protractor/built/runner').Runner);
180
- } catch (e) {
181
- return ['protractor@^5.3.0'];
182
- }
183
- }
184
-
185
- static _config() {
186
- return [
187
- { name: 'url', message: 'Base url of site to be tested', default: 'http://localhost' },
188
- { name: 'driver', message: 'Protractor driver (local, direct, session, hosted, sauce, browserstack)', default: 'hosted' },
189
- { name: 'browser', message: 'Browser in which testing will be performed', default: 'chrome' },
190
- { name: 'rootElement', message: 'Root element of AngularJS application', default: 'body' },
191
- {
192
- name: 'angular', message: 'Enable AngularJS synchronization', default: false, type: 'confirm',
193
- },
194
-
195
- ];
196
- }
197
-
198
- async _beforeStep() {
199
- if (!this.insideAngular) {
200
- return this.amOutsideAngularApp();
201
- }
202
- }
203
-
204
- async _beforeSuite() {
205
- if (!this.options.restart && !this.options.manualStart && !this.isRunning) {
206
- this.debugSection('Session', 'Starting singleton browser session');
207
- return this._startBrowser();
208
- }
209
- }
210
-
211
- async _startBrowser() {
212
- try {
213
- const runner = new Runner(this.options);
214
- this.browser = runner.createBrowser();
215
- await this.browser.ready;
216
- } catch (err) {
217
- if (err.toString().indexOf('ECONNREFUSED')) {
218
- throw new ConnectionRefused(err);
219
- }
220
- throw err;
221
- }
222
- if (this.options.angular) {
223
- await this.amInsideAngularApp();
224
- } else {
225
- await this.amOutsideAngularApp();
226
- }
227
-
228
- loadGlobals(this.browser);
229
-
230
- if (this.options.windowSize === 'maximize') {
231
- await this.resizeWindow(this.options.windowSize);
232
- } else if (this.options.windowSize) {
233
- const size = this.options.windowSize.split('x');
234
- await this.resizeWindow(parseInt(size[0], 10), parseInt(size[1], 10));
235
- }
236
- this.context = this.options.rootElement;
237
- this.isRunning = true;
238
- return this.browser.ready;
239
- }
240
-
241
- async _before() {
242
- if (this.options.restart && !this.options.manualStart) return this._startBrowser();
243
- if (!this.isRunning && !this.options.manualStart) return this._startBrowser();
244
- }
245
-
246
- async _after() {
247
- if (!this.browser) return;
248
- if (!this.isRunning) return;
249
- if (this.options.restart) {
250
- this.isRunning = false;
251
- return this.browser.quit();
252
- }
253
- if (this.options.keepBrowserState) return;
254
-
255
- const dialog = await this.grabPopupText();
256
- if (dialog) {
257
- await this.cancelPopup();
258
- }
259
- if (!this.options.keepCookies) {
260
- await this.browser.manage().deleteAllCookies();
261
- }
262
- let url;
263
- try {
264
- url = await this.browser.getCurrentUrl();
265
- } catch (err) {
266
- // Ignore, as above will throw if no webpage has been loaded
267
- }
268
- if (url && !/data:,/i.test(url)) {
269
- await this.browser.executeScript('localStorage.clear();');
270
- }
271
- return this.closeOtherTabs();
272
- }
273
-
274
- async _failed() {
275
- await this._withinEnd();
276
- }
277
-
278
- async _finishTest() {
279
- if (!this.options.restart && this.isRunning) return this.browser.quit();
280
- }
281
-
282
- async _withinBegin(locator) {
283
- withinStore.elFn = this.browser.findElement;
284
- withinStore.elsFn = this.browser.findElements;
285
-
286
- const frame = isFrameLocator(locator);
287
-
288
- if (frame) {
289
- if (Array.isArray(frame)) {
290
- withinStore.frame = frame.join('>');
291
- return this.switchTo(null)
292
- .then(() => frame.reduce((p, frameLocator) => p.then(() => this.switchTo(frameLocator)), Promise.resolve()));
293
- }
294
- withinStore.frame = frame;
295
- return this.switchTo(locator);
296
- }
297
-
298
- this.context = locator;
299
- const context = await global.element(guessLocator(locator) || global.by.css(locator));
300
- if (!context) throw new ElementNotFound(locator);
301
-
302
- this.browser.findElement = l => (l ? context.element(l).getWebElement() : context.getWebElement());
303
- this.browser.findElements = l => context.all(l).getWebElements();
304
- return context;
305
- }
306
-
307
- async _withinEnd() {
308
- if (!isWithin()) return;
309
- if (withinStore.frame) {
310
- withinStore = {};
311
- return this.switchTo(null);
312
- }
313
- this.browser.findElement = withinStore.elFn;
314
- this.browser.findElements = withinStore.elsFn;
315
- withinStore = {};
316
- this.context = this.options.rootElement;
317
- }
318
-
319
- _session() {
320
- const defaultSession = this.browser;
321
- return {
322
- start: async (opts) => {
323
- opts = this._validateConfig(Object.assign(this.options, opts));
324
- this.debugSection('New Browser', JSON.stringify(opts));
325
- const runner = new Runner(opts);
326
- const res = await this.browser.executeScript('return [window.outerWidth, window.outerHeight]');
327
- const browser = runner.createBrowser(null, this.browser);
328
- await browser.ready;
329
- await browser.waitForAngularEnabled(this.insideAngular);
330
- await browser.manage().window().setSize(parseInt(res[0], 10), parseInt(res[1], 10));
331
- return browser.ready;
332
- },
333
- stop: async (browser) => {
334
- return browser.close();
335
- },
336
- loadVars: async (browser) => {
337
- if (isWithin()) throw new Error('Can\'t start session inside within block');
338
- this.browser = browser;
339
- loadGlobals(this.browser);
340
- },
341
- restoreVars: async () => {
342
- if (isWithin()) await this._withinEnd();
343
- this.browser = defaultSession;
344
- loadGlobals(this.browser);
345
- },
346
- };
347
- }
348
-
349
- /**
350
- * Use [Protractor](https://www.protractortest.org/#/api) API inside a test.
351
- *
352
- * First argument is a description of an action.
353
- * Second argument is async function that gets this helper as parameter.
354
- *
355
- * { [`browser`](https://www.protractortest.org/#/api?view=ProtractorBrowser)) } object from Protractor API is available.
356
- *
357
- * ```js
358
- * I.useProtractorTo('change url via in-page navigation', async ({ browser }) {
359
- * await browser.setLocation('api');
360
- * });
361
- * ```
362
- *
363
- * @param {string} description used to show in logs.
364
- * @param {function} fn async functuion that executed with Protractor helper as argument
365
- */
366
- useProtractorTo(description, fn) {
367
- return this._useTo(...arguments);
368
- }
369
-
370
- /**
371
- * Switch to non-Angular mode,
372
- * start using WebDriver instead of Protractor in this session
373
- */
374
- async amOutsideAngularApp() {
375
- if (!this.browser) return;
376
- await this.browser.waitForAngularEnabled(false);
377
- return Promise.resolve(this.insideAngular = false);
378
- }
379
-
380
- /**
381
- * Enters Angular mode (switched on by default)
382
- * Should be used after "amOutsideAngularApp"
383
- */
384
- async amInsideAngularApp() {
385
- await this.browser.waitForAngularEnabled(true);
386
- return Promise.resolve(this.insideAngular = true);
387
- }
388
-
389
- /**
390
- * Get elements by different locator types, including strict locator
391
- * Should be used in custom helpers:
392
- *
393
- * ```js
394
- * this.helpers['Protractor']._locate({name: 'password'}).then //...
395
- * ```
396
- * To use SmartWait and wait for element to appear on a page, add `true` as second arg:
397
- *
398
- * ```js
399
- * this.helpers['Protractor']._locate({name: 'password'}, true).then //...
400
- * ```
401
- *
402
- */
403
- async _locate(locator, smartWait = false) {
404
- return this._smartWait(() => this.browser.findElements(guessLocator(locator) || global.by.css(locator)), smartWait);
405
- }
406
-
407
- async _smartWait(fn, enabled = true) {
408
- if (!this.options.smartWait || !enabled) return fn();
409
- await this.browser.manage().timeouts().implicitlyWait(this.options.smartWait);
410
- const res = await fn();
411
- await this.browser.manage().timeouts().implicitlyWait(0);
412
- return res;
413
- }
414
-
415
- /**
416
- * Find a checkbox by providing human readable text:
417
- *
418
- * ```js
419
- * this.helpers['Protractor']._locateCheckable('I agree with terms and conditions').then // ...
420
- * ```
421
- */
422
- async _locateCheckable(locator) {
423
- return findCheckable.call(this, this.browser, locator);
424
- }
425
-
426
- /**
427
- * Find a clickable element by providing human readable text:
428
- *
429
- * ```js
430
- * this.helpers['Protractor']._locateClickable('Next page').then // ...
431
- * ```
432
- */
433
- async _locateClickable(locator) {
434
- return findClickable.call(this, this.browser, locator);
435
- }
436
-
437
- /**
438
- * Find field elements by providing human readable text:
439
- *
440
- * ```js
441
- * this.helpers['Protractor']._locateFields('Your email').then // ...
442
- * ```
443
- */
444
- async _locateFields(locator) {
445
- return findFields.call(this, this.browser, locator);
446
- }
447
-
448
- /**
449
- * Opens a web page in a browser. Requires relative or absolute url.
450
- * If url starts with `/`, opens a web page of a site defined in `url` config parameter.
451
- *
452
- * ```js
453
- * I.amOnPage('/'); // opens main page of website
454
- * I.amOnPage('https://github.com'); // opens github
455
- * I.amOnPage('/login'); // opens a login page
456
- * ```
457
- *
458
- * @param {string} url url path or global url.
459
- * @return {void} automatically synchronized promise with recorder #!
460
- */
461
- async amOnPage(url) {
462
- if (!(/^\w+\:\/\//.test(url))) {
463
- url = this.options.url + url;
464
- }
465
- const res = await this.browser.get(url);
466
- this.debug(`Visited ${url}`);
467
- return res;
468
- }
469
-
470
- /**
471
- * Perform a click on a link or a button, given by a locator.
472
- * If a fuzzy locator is given, the page will be searched for a button, link, or image matching the locator string.
473
- * For buttons, the "value" attribute, "name" attribute, and inner text are searched. For links, the link text is searched.
474
- * For images, the "alt" attribute and inner text of any parent links are searched.
475
- *
476
- * The second parameter is a context (CSS or XPath locator) to narrow the search.
477
- *
478
- * ```js
479
- * // simple link
480
- * I.click('Logout');
481
- * // button of form
482
- * I.click('Submit');
483
- * // CSS button
484
- * I.click('#form input[type=submit]');
485
- * // XPath
486
- * I.click('//form/*[@type=submit]');
487
- * // link in context
488
- * I.click('Logout', '#nav');
489
- * // using strict locator
490
- * I.click({css: 'nav a.login'});
491
- * ```
492
- *
493
- * @param {CodeceptJS.LocatorOrString} locator clickable link or button located by text, or any element located by CSS|XPath|strict locator.
494
- * @param {?CodeceptJS.LocatorOrString | null} [context=null] (optional, `null` by default) element to search in CSS|XPath|Strict locator.
495
- * ⚠️ returns a _promise_ which is synchronized internally by recorder
496
- *
497
- */
498
- async click(locator, context = null) {
499
- let matcher = this.browser;
500
- if (context) {
501
- const els = await this._locate(context, true);
502
- assertElementExists(els, context);
503
- matcher = els[0];
504
- }
505
- const el = await findClickable.call(this, matcher, locator);
506
- return el.click();
507
- }
508
-
509
- /**
510
- * Performs a double-click on an element matched by link|button|label|CSS or XPath.
511
- * Context can be specified as second parameter to narrow search.
512
- *
513
- * ```js
514
- * I.doubleClick('Edit');
515
- * I.doubleClick('Edit', '.actions');
516
- * I.doubleClick({css: 'button.accept'});
517
- * I.doubleClick('.btn.edit');
518
- * ```
519
- *
520
- * @param {CodeceptJS.LocatorOrString} locator clickable link or button located by text, or any element located by CSS|XPath|strict locator.
521
- * @param {?CodeceptJS.LocatorOrString} [context=null] (optional, `null` by default) element to search in CSS|XPath|Strict locator.
522
- * ⚠️ returns a _promise_ which is synchronized internally by recorder
523
- *
524
- */
525
- async doubleClick(locator, context = null) {
526
- let matcher = this.browser;
527
- if (context) {
528
- const els = await this._locate(context, true);
529
- assertElementExists(els, context);
530
- matcher = els[0];
531
- }
532
- const el = await findClickable.call(this, matcher, locator);
533
- return this.browser.actions().doubleClick(el).perform();
534
- }
535
-
536
- /**
537
- * Performs right click on a clickable element matched by semantic locator, CSS or XPath.
538
- *
539
- * ```js
540
- * // right click element with id el
541
- * I.rightClick('#el');
542
- * // right click link or button with text "Click me"
543
- * I.rightClick('Click me');
544
- * // right click button with text "Click me" inside .context
545
- * I.rightClick('Click me', '.context');
546
- * ```
547
- *
548
- * @param {CodeceptJS.LocatorOrString} locator clickable element located by CSS|XPath|strict locator.
549
- * @param {?CodeceptJS.LocatorOrString} [context=null] (optional, `null` by default) element located by CSS|XPath|strict locator.
550
- * ⚠️ returns a _promise_ which is synchronized internally by recorder
551
- *
552
- */
553
- async rightClick(locator, context = null) {
554
- /**
555
- * just press button if no selector is given
556
- */
557
- if (locator === undefined) {
558
- return this.browser.actions().click(Button.RIGHT).perform();
559
- }
560
- let matcher = this.browser;
561
- if (context) {
562
- const els = await this._locate(context, true);
563
- assertElementExists(els, context);
564
- matcher = els[0];
565
- }
566
- const el = await findClickable.call(this, matcher, locator);
567
-
568
- await this.browser.actions().mouseMove(el).perform();
569
- return this.browser.actions().click(Button.RIGHT).perform();
570
- }
571
-
572
- /**
573
- * Moves cursor to element matched by locator.
574
- * Extra shift can be set with offsetX and offsetY options.
575
- *
576
- * ```js
577
- * I.moveCursorTo('.tooltip');
578
- * I.moveCursorTo('#submit', 5,5);
579
- * ```
580
- *
581
- * @param {CodeceptJS.LocatorOrString} locator located by CSS|XPath|strict locator.
582
- * @param {number} [offsetX=0] (optional, `0` by default) X-axis offset.
583
- * @param {number} [offsetY=0] (optional, `0` by default) Y-axis offset.
584
- * ⚠️ returns a _promise_ which is synchronized internally by recorder
585
- *
586
- */
587
- async moveCursorTo(locator, offsetX = null, offsetY = null) {
588
- let offset = null;
589
- if (offsetX !== null || offsetY !== null) {
590
- offset = { x: offsetX, y: offsetY };
591
- }
592
- const els = await this._locate(locator, true);
593
- assertElementExists(els, locator);
594
- return this.browser.actions().mouseMove(els[0], offset).perform();
595
- }
596
-
597
- /**
598
- * Checks that a page contains a visible text.
599
- * Use context parameter to narrow down the search.
600
- *
601
- * ```js
602
- * I.see('Welcome'); // text welcome on a page
603
- * I.see('Welcome', '.content'); // text inside .content div
604
- * I.see('Register', {css: 'form.register'}); // use strict locator
605
- * ```
606
- * @param {string} text expected on page.
607
- * @param {?CodeceptJS.LocatorOrString} [context=null] (optional, `null` by default) element located by CSS|Xpath|strict locator in which to search for text.
608
- * ⚠️ returns a _promise_ which is synchronized internally by recorder
609
- *
610
- */
611
- async see(text, context = null) {
612
- return proceedSee.call(this, 'assert', text, context);
613
- }
614
-
615
- /**
616
- * Checks that text is equal to provided one.
617
- *
618
- * ```js
619
- * I.seeTextEquals('text', 'h1');
620
- * ```
621
- *
622
- * @param {string} text element value to check.
623
- * @param {CodeceptJS.LocatorOrString?} [context=null] element located by CSS|XPath|strict locator.
624
- * ⚠️ returns a _promise_ which is synchronized internally by recorder
625
- *
626
- */
627
- async seeTextEquals(text, context = null) {
628
- return proceedSee.call(this, 'assert', text, context, true);
629
- }
630
-
631
- /**
632
- * Opposite to `see`. Checks that a text is not present on a page.
633
- * Use context parameter to narrow down the search.
634
- *
635
- * ```js
636
- * I.dontSee('Login'); // assume we are already logged in.
637
- * I.dontSee('Login', '.nav'); // no login inside .nav element
638
- * ```
639
- *
640
- * @param {string} text which is not present.
641
- * @param {CodeceptJS.LocatorOrString} [context] (optional) element located by CSS|XPath|strict locator in which to perfrom search.
642
- * ⚠️ returns a _promise_ which is synchronized internally by recorder
643
- *
644
- */
645
- dontSee(text, context = null) {
646
- return proceedSee.call(this, 'negate', text, context);
647
- }
648
-
649
- /**
650
- * Get JS log from browser. Log buffer is reset after each request.
651
- * Resumes test execution, so **should be used inside an async function with `await`** operator.
652
- *
653
- * ```js
654
- * let logs = await I.grabBrowserLogs();
655
- * console.log(JSON.stringify(logs))
656
- * ```
657
- *
658
- * @returns {Promise<object[]>|undefined} all browser logs
659
- *
660
- */
661
- async grabBrowserLogs() {
662
- return this.browser.manage().logs().get('browser');
663
- }
664
-
665
- /**
666
- * Get current URL from browser.
667
- * Resumes test execution, so should be used inside an async function.
668
- *
669
- * ```js
670
- * let url = await I.grabCurrentUrl();
671
- * console.log(`Current URL is [${url}]`);
672
- * ```
673
- *
674
- * @returns {Promise<string>} current URL
675
- */
676
- async grabCurrentUrl() {
677
- return this.browser.getCurrentUrl();
678
- }
679
-
680
- /**
681
- * Selects an option in a drop-down select.
682
- * Field is searched by label | name | CSS | XPath.
683
- * Option is selected by visible text or by value.
684
- *
685
- * ```js
686
- * I.selectOption('Choose Plan', 'Monthly'); // select by label
687
- * I.selectOption('subscription', 'Monthly'); // match option by text
688
- * I.selectOption('subscription', '0'); // or by value
689
- * I.selectOption('//form/select[@name=account]','Premium');
690
- * I.selectOption('form select[name=account]', 'Premium');
691
- * I.selectOption({css: 'form select[name=account]'}, 'Premium');
692
- * ```
693
- *
694
- * Provide an array for the second argument to select multiple options.
695
- *
696
- * ```js
697
- * I.selectOption('Which OS do you use?', ['Android', 'iOS']);
698
- * ```
699
- * @param {LocatorOrString} select field located by label|name|CSS|XPath|strict locator.
700
- * @param {string|Array<*>} option visible text or value of option.
701
- * ⚠️ returns a _promise_ which is synchronized internally by recorder
702
- *
703
- */
704
- async selectOption(select, option) {
705
- const fields = await findFields(this.browser, select);
706
- assertElementExists(fields, select, 'Selectable field');
707
- if (!Array.isArray(option)) {
708
- option = [option];
709
- }
710
- const field = fields[0];
711
- const promises = [];
712
- for (const key in option) {
713
- const opt = xpathLocator.literal(option[key]);
714
- let els = await field.findElements(global.by.xpath(Locator.select.byVisibleText(opt)));
715
- if (!els.length) {
716
- els = await field.findElements(global.by.xpath(Locator.select.byValue(opt)));
717
- }
718
- els.forEach(el => promises.push(el.click()));
719
- }
720
-
721
- return Promise.all(promises);
722
- }
723
-
724
- /**
725
- * Fills a text field or textarea, after clearing its value, with the given string.
726
- * Field is located by name, label, CSS, or XPath.
727
- *
728
- * ```js
729
- * // by label
730
- * I.fillField('Email', 'hello@world.com');
731
- * // by name
732
- * I.fillField('password', secret('123456'));
733
- * // by CSS
734
- * I.fillField('form#login input[name=username]', 'John');
735
- * // or by strict locator
736
- * I.fillField({css: 'form#login input[name=username]'}, 'John');
737
- * ```
738
- * @param {CodeceptJS.LocatorOrString} field located by label|name|CSS|XPath|strict locator.
739
- * @param {CodeceptJS.StringOrSecret} value text value to fill.
740
- * ⚠️ returns a _promise_ which is synchronized internally by recorder
741
- *
742
- */
743
- async fillField(field, value) {
744
- const els = await findFields(this.browser, field);
745
- await els[0].clear();
746
- return els[0].sendKeys(value.toString());
747
- }
748
-
749
- /**
750
- * Presses a key on a focused element.
751
- * Special keys like 'Enter', 'Control', [etc](https://code.google.com/p/selenium/wiki/JsonWireProtocol#/session/:sessionId/element/:id/value)
752
- * will be replaced with corresponding unicode.
753
- * If modifier key is used (Control, Command, Alt, Shift) in array, it will be released afterwards.
754
- *
755
- * ```js
756
- * I.pressKey('Enter');
757
- * I.pressKey(['Control','a']);
758
- * ```
759
- *
760
- * @param {string|string[]} key key or array of keys to press.
761
- * ⚠️ returns a _promise_ which is synchronized internally by recorder
762
- *
763
- * {{ keys }}
764
- */
765
- async pressKey(key) {
766
- let modifier;
767
- if (Array.isArray(key) && ~['Control', 'Command', 'Shift', 'Alt'].indexOf(key[0])) { // eslint-disable-line no-bitwise
768
- modifier = Key[key[0].toUpperCase()];
769
- key = key[1];
770
- }
771
-
772
- // guess special key in Selenium Webdriver list
773
- if (Key[key.toUpperCase()]) {
774
- key = Key[key.toUpperCase()];
775
- }
776
-
777
- const action = this.browser.actions();
778
- if (modifier) action.keyDown(modifier);
779
- action.sendKeys(key);
780
- if (modifier) action.keyUp(modifier);
781
- return action.perform();
782
- }
783
-
784
- /**
785
- * Attaches a file to element located by label, name, CSS or XPath
786
- * Path to file is relative current codecept directory (where codecept.conf.ts or codecept.conf.js is located).
787
- * File will be uploaded to remote system (if tests are running remotely).
788
- *
789
- * ```js
790
- * I.attachFile('Avatar', 'data/avatar.jpg');
791
- * I.attachFile('form input[name=avatar]', 'data/avatar.jpg');
792
- * ```
793
- *
794
- * @param {CodeceptJS.LocatorOrString} locator field located by label|name|CSS|XPath|strict locator.
795
- * @param {string} pathToFile local file path relative to codecept.conf.ts or codecept.conf.js config file.
796
- * ⚠️ returns a _promise_ which is synchronized internally by recorder
797
- *
798
- */
799
- async attachFile(locator, pathToFile) {
800
- const file = path.join(global.codecept_dir, pathToFile);
801
- if (!fileExists(file)) {
802
- throw new Error(`File at ${file} can not be found on local system`);
803
- }
804
- const els = await findFields(this.browser, locator);
805
- assertElementExists(els, locator, 'Field');
806
- if (this.options.browser !== 'phantomjs') {
807
- const remote = require('selenium-webdriver/remote');
808
- this.browser.setFileDetector(new remote.FileDetector());
809
- }
810
- return els[0].sendKeys(file);
811
- }
812
-
813
- /**
814
- * Checks that the given input field or textarea equals to given value.
815
- * For fuzzy locators, fields are matched by label text, the "name" attribute, CSS, and XPath.
816
- *
817
- * ```js
818
- * I.seeInField('Username', 'davert');
819
- * I.seeInField({css: 'form textarea'},'Type your comment here');
820
- * I.seeInField('form input[type=hidden]','hidden_value');
821
- * I.seeInField('#searchform input','Search');
822
- * ```
823
- * @param {CodeceptJS.LocatorOrString} field located by label|name|CSS|XPath|strict locator.
824
- * @param {string} value value to check.
825
- * ⚠️ returns a _promise_ which is synchronized internally by recorder
826
- *
827
- */
828
- async seeInField(field, value) {
829
- return proceedSeeInField.call(this, 'assert', field, value);
830
- }
831
-
832
- /**
833
- * Checks that value of input field or textarea doesn't equal to given value
834
- * Opposite to `seeInField`.
835
- *
836
- * ```js
837
- * I.dontSeeInField('email', 'user@user.com'); // field by name
838
- * I.dontSeeInField({ css: 'form input.email' }, 'user@user.com'); // field by CSS
839
- * ```
840
- *
841
- * @param {CodeceptJS.LocatorOrString} field located by label|name|CSS|XPath|strict locator.
842
- * @param {string} value value to check.
843
- * ⚠️ returns a _promise_ which is synchronized internally by recorder
844
- *
845
- */
846
- async dontSeeInField(field, value) {
847
- return proceedSeeInField.call(this, 'negate', field, value);
848
- }
849
-
850
- /**
851
- * Appends text to a input field or textarea.
852
- * Field is located by name, label, CSS or XPath
853
- *
854
- * ```js
855
- * I.appendField('#myTextField', 'appended');
856
- * ```
857
- * @param {CodeceptJS.LocatorOrString} field located by label|name|CSS|XPath|strict locator
858
- * @param {string} value text value to append.
859
- * ⚠️ returns a _promise_ which is synchronized internally by recorder
860
- *
861
- */
862
- async appendField(field, value) {
863
- const els = await findFields(this.browser, field);
864
- assertElementExists(els, field, 'Field');
865
- return els[0].sendKeys(value);
866
- }
867
-
868
- /**
869
- * Clears a `<textarea>` or text `<input>` element's value.
870
- *
871
- * ```js
872
- * I.clearField('Email');
873
- * I.clearField('user[email]');
874
- * I.clearField('#email');
875
- * ```
876
- * @param {LocatorOrString} editable field located by label|name|CSS|XPath|strict locator.
877
- * ⚠️ returns a _promise_ which is synchronized internally by recorder.
878
- *
879
- */
880
- async clearField(field) {
881
- const els = await findFields(this.browser, field);
882
- assertElementExists(els, field, 'Field');
883
- return els[0].clear();
884
- }
885
-
886
- /**
887
- * Selects a checkbox or radio button.
888
- * Element is located by label or name or CSS or XPath.
889
- *
890
- * The second parameter is a context (CSS or XPath locator) to narrow the search.
891
- *
892
- * ```js
893
- * I.checkOption('#agree');
894
- * I.checkOption('I Agree to Terms and Conditions');
895
- * I.checkOption('agree', '//form');
896
- * ```
897
- * @param {CodeceptJS.LocatorOrString} field checkbox located by label | name | CSS | XPath | strict locator.
898
- * @param {?CodeceptJS.LocatorOrString} [context=null] (optional, `null` by default) element located by CSS | XPath | strict locator.
899
- * ⚠️ returns a _promise_ which is synchronized internally by recorder
900
- *
901
- */
902
- async checkOption(field, context = null) {
903
- let matcher = this.browser;
904
- if (context) {
905
- const els = await this._locate(context, true);
906
- assertElementExists(els, context);
907
- matcher = els[0];
908
- }
909
- const els = await findCheckable(matcher, field);
910
- assertElementExists(els, field, 'Checkbox or radio');
911
- const isSelected = await els[0].isSelected();
912
- if (!isSelected) return els[0].click();
913
- }
914
-
915
- /**
916
- * Unselects a checkbox or radio button.
917
- * Element is located by label or name or CSS or XPath.
918
- *
919
- * The second parameter is a context (CSS or XPath locator) to narrow the search.
920
- *
921
- * ```js
922
- * I.uncheckOption('#agree');
923
- * I.uncheckOption('I Agree to Terms and Conditions');
924
- * I.uncheckOption('agree', '//form');
925
- * ```
926
- * @param {CodeceptJS.LocatorOrString} field checkbox located by label | name | CSS | XPath | strict locator.
927
- * @param {?CodeceptJS.LocatorOrString} [context=null] (optional, `null` by default) element located by CSS | XPath | strict locator.
928
- * ⚠️ returns a _promise_ which is synchronized internally by recorder
929
- *
930
- */
931
- async uncheckOption(field, context = null) {
932
- let matcher = this.browser;
933
- if (context) {
934
- const els = await this._locate(context, true);
935
- assertElementExists(els, context);
936
- matcher = els[0];
937
- }
938
- const els = await findCheckable(matcher, field);
939
- assertElementExists(els, field, 'Checkbox or radio');
940
- const isSelected = await els[0].isSelected();
941
- if (isSelected) return els[0].click();
942
- }
943
-
944
- /**
945
- * Verifies that the specified checkbox is checked.
946
- *
947
- * ```js
948
- * I.seeCheckboxIsChecked('Agree');
949
- * I.seeCheckboxIsChecked('#agree'); // I suppose user agreed to terms
950
- * I.seeCheckboxIsChecked({css: '#signup_form input[type=checkbox]'});
951
- * ```
952
- *
953
- * @param {CodeceptJS.LocatorOrString} field located by label|name|CSS|XPath|strict locator.
954
- * ⚠️ returns a _promise_ which is synchronized internally by recorder
955
- *
956
- */
957
- async seeCheckboxIsChecked(field) {
958
- return proceedIsChecked.call(this, 'assert', field);
959
- }
960
-
961
- /**
962
- * Verifies that the specified checkbox is not checked.
963
- *
964
- * ```js
965
- * I.dontSeeCheckboxIsChecked('#agree'); // located by ID
966
- * I.dontSeeCheckboxIsChecked('I agree to terms'); // located by label
967
- * I.dontSeeCheckboxIsChecked('agree'); // located by name
968
- * ```
969
- *
970
- * @param {CodeceptJS.LocatorOrString} field located by label|name|CSS|XPath|strict locator.
971
- * ⚠️ returns a _promise_ which is synchronized internally by recorder
972
- *
973
- */
974
- async dontSeeCheckboxIsChecked(field) {
975
- return proceedIsChecked.call(this, 'negate', field);
976
- }
977
-
978
- /**
979
- * Retrieves all texts from an element located by CSS or XPath and returns it to test.
980
- * Resumes test execution, so **should be used inside async with `await`** operator.
981
- *
982
- * ```js
983
- * let pins = await I.grabTextFromAll('#pin li');
984
- * ```
985
- *
986
- * @param {CodeceptJS.LocatorOrString} locator element located by CSS|XPath|strict locator.
987
- * @returns {Promise<string[]>} attribute value
988
- *
989
- */
990
- async grabTextFromAll(locator) {
991
- const els = await this._locate(locator);
992
- const texts = [];
993
- for (const el of els) {
994
- texts.push(await el.getText());
995
- }
996
- return texts;
997
- }
998
-
999
- /**
1000
- * Retrieves a text from an element located by CSS or XPath and returns it to test.
1001
- * Resumes test execution, so **should be used inside async with `await`** operator.
1002
- *
1003
- * ```js
1004
- * let pin = await I.grabTextFrom('#pin');
1005
- * ```
1006
- * If multiple elements found returns first element.
1007
- *
1008
- * @param {CodeceptJS.LocatorOrString} locator element located by CSS|XPath|strict locator.
1009
- * @returns {Promise<string>} attribute value
1010
- *
1011
- */
1012
- async grabTextFrom(locator) {
1013
- const texts = await this.grabTextFromAll(locator);
1014
- assertElementExists(texts, locator);
1015
- if (texts.length > 1) {
1016
- this.debugSection('GrabText', `Using first element out of ${texts.length}`);
1017
- }
1018
-
1019
- return texts[0];
1020
- }
1021
-
1022
- /**
1023
- * Retrieves all the innerHTML from elements located by CSS or XPath and returns it to test.
1024
- * Resumes test execution, so **should be used inside async function with `await`** operator.
1025
- *
1026
- * ```js
1027
- * let postHTMLs = await I.grabHTMLFromAll('.post');
1028
- * ```
1029
- *
1030
- * @param {CodeceptJS.LocatorOrString} element located by CSS|XPath|strict locator.
1031
- * @returns {Promise<string[]>} HTML code for an element
1032
- *
1033
- */
1034
- async grabHTMLFromAll(locator) {
1035
- const els = await this._locate(locator);
1036
-
1037
- const html = await Promise.all(els.map((el) => {
1038
- return this.browser.executeScript('return arguments[0].innerHTML;', el);
1039
- }));
1040
-
1041
- return html;
1042
- }
1043
-
1044
- /**
1045
- * Retrieves the innerHTML from an element located by CSS or XPath and returns it to test.
1046
- * Resumes test execution, so **should be used inside async function with `await`** operator.
1047
- * If more than one element is found - HTML of first element is returned.
1048
- *
1049
- * ```js
1050
- * let postHTML = await I.grabHTMLFrom('#post');
1051
- * ```
1052
- *
1053
- * @param {CodeceptJS.LocatorOrString} element located by CSS|XPath|strict locator.
1054
- * @returns {Promise<string>} HTML code for an element
1055
- *
1056
- */
1057
- async grabHTMLFrom(locator) {
1058
- const html = await this.grabHTMLFromAll(locator);
1059
- assertElementExists(html, locator);
1060
- if (html.length > 1) {
1061
- this.debugSection('GrabHTMl', `Using first element out of ${html.length}`);
1062
- }
1063
-
1064
- return html[0];
1065
- }
1066
-
1067
- /**
1068
- * Retrieves an array of value from a form located by CSS or XPath and returns it to test.
1069
- * Resumes test execution, so **should be used inside async function with `await`** operator.
1070
- *
1071
- * ```js
1072
- * let inputs = await I.grabValueFromAll('//form/input');
1073
- * ```
1074
- * @param {CodeceptJS.LocatorOrString} locator field located by label|name|CSS|XPath|strict locator.
1075
- * @returns {Promise<string[]>} attribute value
1076
- *
1077
- */
1078
- async grabValueFromAll(locator) {
1079
- const els = await findFields(this.browser, locator);
1080
- const values = await Promise.all(els.map(el => el.getAttribute('value')));
1081
-
1082
- return values;
1083
- }
1084
-
1085
- /**
1086
- * Retrieves a value from a form element located by CSS or XPath and returns it to test.
1087
- * Resumes test execution, so **should be used inside async function with `await`** operator.
1088
- * If more than one element is found - value of first element is returned.
1089
- *
1090
- * ```js
1091
- * let email = await I.grabValueFrom('input[name=email]');
1092
- * ```
1093
- * @param {CodeceptJS.LocatorOrString} locator field located by label|name|CSS|XPath|strict locator.
1094
- * @returns {Promise<string>} attribute value
1095
- *
1096
- */
1097
- async grabValueFrom(locator) {
1098
- const values = await this.grabValueFromAll(locator);
1099
- assertElementExists(values, locator, 'Field');
1100
- if (values.length > 1) {
1101
- this.debugSection('GrabValue', `Using first element out of ${values.length}`);
1102
- }
1103
-
1104
- return values[0];
1105
- }
1106
-
1107
- /**
1108
- * Grab array of CSS properties for given locator
1109
- * Resumes test execution, so **should be used inside an async function with `await`** operator.
1110
- *
1111
- * ```js
1112
- * const values = await I.grabCssPropertyFromAll('h3', 'font-weight');
1113
- * ```
1114
- *
1115
- * @param {CodeceptJS.LocatorOrString} locator element located by CSS|XPath|strict locator.
1116
- * @param {string} cssProperty CSS property name.
1117
- * @returns {Promise<string[]>} CSS value
1118
- *
1119
- */
1120
- async grabCssPropertyFromAll(locator, cssProperty) {
1121
- const els = await this._locate(locator, true);
1122
- const values = await Promise.all(els.map(el => el.getCssValue(cssProperty)));
1123
-
1124
- return values;
1125
- }
1126
-
1127
- /**
1128
- * Grab CSS property for given locator
1129
- * Resumes test execution, so **should be used inside an async function with `await`** operator.
1130
- * If more than one element is found - value of first element is returned.
1131
- *
1132
- * ```js
1133
- * const value = await I.grabCssPropertyFrom('h3', 'font-weight');
1134
- * ```
1135
- *
1136
- * @param {CodeceptJS.LocatorOrString} locator element located by CSS|XPath|strict locator.
1137
- * @param {string} cssProperty CSS property name.
1138
- * @returns {Promise<string>} CSS value
1139
- *
1140
- */
1141
- async grabCssPropertyFrom(locator, cssProperty) {
1142
- const cssValues = await this.grabCssPropertyFromAll(locator, cssProperty);
1143
- assertElementExists(cssValues, locator);
1144
-
1145
- if (cssValues.length > 1) {
1146
- this.debugSection('GrabCSS', `Using first element out of ${cssValues.length}`);
1147
- }
1148
-
1149
- return cssValues[0];
1150
- }
1151
-
1152
- /**
1153
- * Retrieves an array of attributes from elements located by CSS or XPath and returns it to test.
1154
- * Resumes test execution, so **should be used inside async with `await`** operator.
1155
- *
1156
- * ```js
1157
- * let hints = await I.grabAttributeFromAll('.tooltip', 'title');
1158
- * ```
1159
- * @param {CodeceptJS.LocatorOrString} locator element located by CSS|XPath|strict locator.
1160
- * @param {string} attr attribute name.
1161
- * @returns {Promise<string[]>} attribute value
1162
- *
1163
- */
1164
- async grabAttributeFromAll(locator, attr) {
1165
- const els = await this._locate(locator);
1166
- const array = [];
1167
-
1168
- for (let index = 0; index < els.length; index++) {
1169
- const el = els[index];
1170
- array.push(await el.getAttribute(attr));
1171
- }
1172
- return array;
1173
- }
1174
-
1175
- /**
1176
- * Retrieves an attribute from an element located by CSS or XPath and returns it to test.
1177
- * Resumes test execution, so **should be used inside async with `await`** operator.
1178
- * If more than one element is found - attribute of first element is returned.
1179
- *
1180
- * ```js
1181
- * let hint = await I.grabAttributeFrom('#tooltip', 'title');
1182
- * ```
1183
- * @param {CodeceptJS.LocatorOrString} locator element located by CSS|XPath|strict locator.
1184
- * @param {string} attr attribute name.
1185
- * @returns {Promise<string>} attribute value
1186
- *
1187
- */
1188
- async grabAttributeFrom(locator, attr) {
1189
- const attrs = await this.grabAttributeFromAll(locator, attr);
1190
- assertElementExists(attrs, locator);
1191
- if (attrs.length > 1) {
1192
- this.debugSection('GrabAttribute', `Using first element out of ${attrs.length}`);
1193
- }
1194
-
1195
- return attrs[0];
1196
- }
1197
-
1198
- /**
1199
- * Checks that title contains text.
1200
- *
1201
- * ```js
1202
- * I.seeInTitle('Home Page');
1203
- * ```
1204
- *
1205
- * @param {string} text text value to check.
1206
- * ⚠️ returns a _promise_ which is synchronized internally by recorder
1207
- *
1208
- */
1209
- async seeInTitle(text) {
1210
- return this.browser.getTitle().then(title => stringIncludes('web page title').assert(text, title));
1211
- }
1212
-
1213
- /**
1214
- * Checks that title is equal to provided one.
1215
- *
1216
- * ```js
1217
- * I.seeTitleEquals('Test title.');
1218
- * ```
1219
- *
1220
- * @param {string} text value to check.
1221
- * ⚠️ returns a _promise_ which is synchronized internally by recorder
1222
- *
1223
- */
1224
- async seeTitleEquals(text) {
1225
- const title = await this.browser.getTitle();
1226
- return equals('web page title').assert(title, text);
1227
- }
1228
-
1229
- /**
1230
- * Checks that title does not contain text.
1231
- *
1232
- * ```js
1233
- * I.dontSeeInTitle('Error');
1234
- * ```
1235
- *
1236
- * @param {string} text value to check.
1237
- * ⚠️ returns a _promise_ which is synchronized internally by recorder
1238
- *
1239
- */
1240
- async dontSeeInTitle(text) {
1241
- return this.browser.getTitle().then(title => stringIncludes('web page title').negate(text, title));
1242
- }
1243
-
1244
- /**
1245
- * Retrieves a page title and returns it to test.
1246
- * Resumes test execution, so **should be used inside async with `await`** operator.
1247
- *
1248
- * ```js
1249
- * let title = await I.grabTitle();
1250
- * ```
1251
- *
1252
- * @returns {Promise<string>} title
1253
- */
1254
- async grabTitle() {
1255
- return this.browser.getTitle().then((title) => {
1256
- this.debugSection('Title', title);
1257
- return title;
1258
- });
1259
- }
1260
-
1261
- /**
1262
- * Checks that a given Element is visible
1263
- * Element is located by CSS or XPath.
1264
- *
1265
- * ```js
1266
- * I.seeElement('#modal');
1267
- * ```
1268
- * @param {CodeceptJS.LocatorOrString} locator located by CSS|XPath|strict locator.
1269
- * ⚠️ returns a _promise_ which is synchronized internally by recorder
1270
- *
1271
- */
1272
- async seeElement(locator) {
1273
- let els = await this._locate(locator, true);
1274
- els = await Promise.all(els.map(el => el.isDisplayed()));
1275
- return empty('elements').negate(els.filter(v => v).fill('ELEMENT'));
1276
- }
1277
-
1278
- /**
1279
- * Opposite to `seeElement`. Checks that element is not visible (or in DOM)
1280
- *
1281
- * ```js
1282
- * I.dontSeeElement('.modal'); // modal is not shown
1283
- * ```
1284
- *
1285
- * @param {CodeceptJS.LocatorOrString} locator located by CSS|XPath|Strict locator.
1286
- * ⚠️ returns a _promise_ which is synchronized internally by recorder
1287
- *
1288
- */
1289
- async dontSeeElement(locator) {
1290
- let els = await this._locate(locator, false);
1291
- els = await Promise.all(els.map(el => el.isDisplayed()));
1292
- return empty('elements').assert(els.filter(v => v).fill('ELEMENT'));
1293
- }
1294
-
1295
- /**
1296
- * Checks that a given Element is present in the DOM
1297
- * Element is located by CSS or XPath.
1298
- *
1299
- * ```js
1300
- * I.seeElementInDOM('#modal');
1301
- * ```
1302
- * @param {CodeceptJS.LocatorOrString} locator element located by CSS|XPath|strict locator.
1303
- * ⚠️ returns a _promise_ which is synchronized internally by recorder
1304
- *
1305
- */
1306
- async seeElementInDOM(locator) {
1307
- return this.browser.findElements(guessLocator(locator) || global.by.css(locator)).then(els => empty('elements').negate(els.fill('ELEMENT')));
1308
- }
1309
-
1310
- /**
1311
- * Opposite to `seeElementInDOM`. Checks that element is not on page.
1312
- *
1313
- * ```js
1314
- * I.dontSeeElementInDOM('.nav'); // checks that element is not on page visible or not
1315
- * ```
1316
- *
1317
- * @param {CodeceptJS.LocatorOrString} locator located by CSS|XPath|Strict locator.
1318
- * ⚠️ returns a _promise_ which is synchronized internally by recorder
1319
- *
1320
- */
1321
- async dontSeeElementInDOM(locator) {
1322
- return this.browser.findElements(guessLocator(locator) || global.by.css(locator)).then(els => empty('elements').assert(els.fill('ELEMENT')));
1323
- }
1324
-
1325
- /**
1326
- * Checks that the current page contains the given string in its raw source code.
1327
- *
1328
- * ```js
1329
- * I.seeInSource('<h1>Green eggs &amp; ham</h1>');
1330
- * ```
1331
- * @param {string} text value to check.
1332
- * ⚠️ returns a _promise_ which is synchronized internally by recorder
1333
- *
1334
- */
1335
- async seeInSource(text) {
1336
- return this.browser.getPageSource().then(source => stringIncludes('HTML source of a page').assert(text, source));
1337
- }
1338
-
1339
- /**
1340
- * Retrieves page source and returns it to test.
1341
- * Resumes test execution, so **should be used inside async function with `await`** operator.
1342
- *
1343
- * ```js
1344
- * let pageSource = await I.grabSource();
1345
- * ```
1346
- *
1347
- * @returns {Promise<string>} source code
1348
- */
1349
- async grabSource() {
1350
- return this.browser.getPageSource();
1351
- }
1352
-
1353
- /**
1354
- * Checks that the current page does not contains the given string in its raw source code.
1355
- *
1356
- * ```js
1357
- * I.dontSeeInSource('<!--'); // no comments in source
1358
- * ```
1359
- *
1360
- * @param {string} value to check.
1361
- * ⚠️ returns a _promise_ which is synchronized internally by recorder
1362
- *
1363
- */
1364
- async dontSeeInSource(text) {
1365
- return this.browser.getPageSource().then(source => stringIncludes('HTML source of a page').negate(text, source));
1366
- }
1367
-
1368
- /**
1369
- * Asserts that an element appears a given number of times in the DOM.
1370
- * Element is located by label or name or CSS or XPath.
1371
- *
1372
- *
1373
- * ```js
1374
- * I.seeNumberOfElements('#submitBtn', 1);
1375
- * ```
1376
- *
1377
- * @param {CodeceptJS.LocatorOrString} locator element located by CSS|XPath|strict locator.
1378
- * @param {number} num number of elements.
1379
- * ⚠️ returns a _promise_ which is synchronized internally by recorder
1380
- *
1381
- */
1382
- async seeNumberOfElements(locator, num) {
1383
- const elements = await this._locate(locator);
1384
- return equals(`expected number of elements (${(new Locator(locator))}) is ${num}, but found ${elements.length}`).assert(elements.length, num);
1385
- }
1386
-
1387
- /**
1388
- * Asserts that an element is visible a given number of times.
1389
- * Element is located by CSS or XPath.
1390
- *
1391
- * ```js
1392
- * I.seeNumberOfVisibleElements('.buttons', 3);
1393
- * ```
1394
- *
1395
- * @param {CodeceptJS.LocatorOrString} locator element located by CSS|XPath|strict locator.
1396
- * @param {number} num number of elements.
1397
- * ⚠️ returns a _promise_ which is synchronized internally by recorder
1398
- *
1399
- */
1400
- async seeNumberOfVisibleElements(locator, num) {
1401
- const res = await this.grabNumberOfVisibleElements(locator);
1402
- return equals(`expected number of visible elements (${(new Locator(locator))}) is ${num}, but found ${res}`).assert(res, num);
1403
- }
1404
-
1405
- /**
1406
- * Grab number of visible elements by locator.
1407
- * Resumes test execution, so **should be used inside async function with `await`** operator.
1408
- *
1409
- * ```js
1410
- * let numOfElements = await I.grabNumberOfVisibleElements('p');
1411
- * ```
1412
- *
1413
- * @param {CodeceptJS.LocatorOrString} locator located by CSS|XPath|strict locator.
1414
- * @returns {Promise<number>} number of visible elements
1415
- */
1416
- async grabNumberOfVisibleElements(locator) {
1417
- let els = await this._locate(locator);
1418
- els = await Promise.all(els.map(el => el.isDisplayed()));
1419
- return els.length;
1420
- }
1421
-
1422
- /**
1423
- * Checks that all elements with given locator have given CSS properties.
1424
- *
1425
- * ```js
1426
- * I.seeCssPropertiesOnElements('h3', { 'font-weight': "bold"});
1427
- * ```
1428
- *
1429
- * @param {CodeceptJS.LocatorOrString} locator located by CSS|XPath|strict locator.
1430
- * @param {object} cssProperties object with CSS properties and their values to check.
1431
- * ⚠️ returns a _promise_ which is synchronized internally by recorder
1432
- *
1433
- */
1434
- async seeCssPropertiesOnElements(locator, cssProperties) {
1435
- const els = await this._locate(locator);
1436
- assertElementExists(els, locator);
1437
-
1438
- const cssPropertiesCamelCase = convertCssPropertiesToCamelCase(cssProperties);
1439
-
1440
- const attributeNames = Object.keys(cssPropertiesCamelCase);
1441
- const expectedValues = attributeNames.map(name => cssPropertiesCamelCase[name]);
1442
- const missingAttributes = [];
1443
-
1444
- for (const el of els) {
1445
- const attributeValues = await Promise.all(attributeNames.map(attr => el.getCssValue(attr)));
1446
-
1447
- const missing = attributeValues.filter((actual, i) => {
1448
- const prop = attributeNames[i];
1449
- let propValue = actual;
1450
- if (isColorProperty(prop) && propValue) {
1451
- propValue = convertColorToRGBA(propValue);
1452
- }
1453
- return propValue !== expectedValues[i];
1454
- });
1455
- if (missing.length) {
1456
- missingAttributes.push(...missing);
1457
- }
1458
- }
1459
- return equals(`all elements (${(new Locator(locator))}) to have CSS property ${JSON.stringify(cssProperties)}`).assert(missingAttributes.length, 0);
1460
- }
1461
-
1462
- /**
1463
- * Checks that all elements with given locator have given attributes.
1464
- *
1465
- * ```js
1466
- * I.seeAttributesOnElements('//form', { method: "post"});
1467
- * ```
1468
- *
1469
- * @param {CodeceptJS.LocatorOrString} locator located by CSS|XPath|strict locator.
1470
- * @param {object} attributes attributes and their values to check.
1471
- * ⚠️ returns a _promise_ which is synchronized internally by recorder
1472
- *
1473
- */
1474
- async seeAttributesOnElements(locator, attributes) {
1475
- const els = await this._locate(locator);
1476
- assertElementExists(els, locator);
1477
-
1478
- const attributeNames = Object.keys(attributes);
1479
- const expectedValues = attributeNames.map(name => attributes[name]);
1480
- const missingAttributes = [];
1481
-
1482
- for (const el of els) {
1483
- const attributeValues = await Promise.all(attributeNames.map(attr => el.getAttribute(attr)));
1484
- const missing = attributeValues.filter((actual, i) => {
1485
- if (expectedValues[i] instanceof RegExp) {
1486
- return expectedValues[i].test(actual);
1487
- }
1488
- return actual !== expectedValues[i];
1489
- });
1490
- if (missing.length) {
1491
- missingAttributes.push(...missing);
1492
- }
1493
- }
1494
-
1495
- return equals(`all elements (${(new Locator(locator))}) to have attributes ${JSON.stringify(attributes)}`).assert(missingAttributes.length, 0);
1496
- }
1497
-
1498
- /**
1499
- * Executes sync script on a page.
1500
- * Pass arguments to function as additional parameters.
1501
- * Will return execution result to a test.
1502
- * In this case you should use async function and await to receive results.
1503
- *
1504
- * Example with jQuery DatePicker:
1505
- *
1506
- * ```js
1507
- * // change date of jQuery DatePicker
1508
- * I.executeScript(function() {
1509
- * // now we are inside browser context
1510
- * $('date').datetimepicker('setDate', new Date());
1511
- * });
1512
- * ```
1513
- * Can return values. Don't forget to use `await` to get them.
1514
- *
1515
- * ```js
1516
- * let date = await I.executeScript(function(el) {
1517
- * // only basic types can be returned
1518
- * return $(el).datetimepicker('getDate').toString();
1519
- * }, '#date'); // passing jquery selector
1520
- * ```
1521
- *
1522
- * @param {string|function} fn function to be executed in browser context.
1523
- * @param {...any} args to be passed to function.
1524
- * ⚠️ returns a _promise_ which is synchronized internally by recorder
1525
- *
1526
- */
1527
- async executeScript() {
1528
- return this.browser.executeScript.apply(this.browser, arguments);
1529
- }
1530
-
1531
- /**
1532
- * Executes async script on page.
1533
- * Provided function should execute a passed callback (as first argument) to signal it is finished.
1534
- *
1535
- * Example: In Vue.js to make components completely rendered we are waiting for [nextTick](https://vuejs.org/v2/api/#Vue-nextTick).
1536
- *
1537
- * ```js
1538
- * I.executeAsyncScript(function(done) {
1539
- * Vue.nextTick(done); // waiting for next tick
1540
- * });
1541
- * ```
1542
- *
1543
- * By passing value to `done()` function you can return values.
1544
- * Additional arguments can be passed as well, while `done` function is always last parameter in arguments list.
1545
- *
1546
- * ```js
1547
- * let val = await I.executeAsyncScript(function(url, done) {
1548
- * // in browser context
1549
- * $.ajax(url, { success: (data) => done(data); }
1550
- * }, 'http://ajax.callback.url/');
1551
- * ```
1552
- *
1553
- * @param {string|function} fn function to be executed in browser context.
1554
- * @param {...any} args to be passed to function.
1555
- * ⚠️ returns a _promise_ which is synchronized internally by recorder
1556
- *
1557
- */
1558
- async executeAsyncScript() {
1559
- this.browser.manage().timeouts().setScriptTimeout(this.options.scriptTimeout);
1560
- return this.browser.executeAsyncScript.apply(this.browser, arguments);
1561
- }
1562
-
1563
- /**
1564
- * Checks that current url contains a provided fragment.
1565
- *
1566
- * ```js
1567
- * I.seeInCurrentUrl('/register'); // we are on registration page
1568
- * ```
1569
- *
1570
- * @param {string} url a fragment to check
1571
- * ⚠️ returns a _promise_ which is synchronized internally by recorder
1572
- *
1573
- */
1574
- async seeInCurrentUrl(url) {
1575
- return this.browser.getCurrentUrl().then(currentUrl => stringIncludes('url').assert(url, currentUrl));
1576
- }
1577
-
1578
- /**
1579
- * Checks that current url does not contain a provided fragment.
1580
- *
1581
- * @param {string} url value to check.
1582
- * ⚠️ returns a _promise_ which is synchronized internally by recorder
1583
- *
1584
- */
1585
- async dontSeeInCurrentUrl(url) {
1586
- return this.browser.getCurrentUrl().then(currentUrl => stringIncludes('url').negate(url, currentUrl));
1587
- }
1588
-
1589
- /**
1590
- * Checks that current url is equal to provided one.
1591
- * If a relative url provided, a configured url will be prepended to it.
1592
- * So both examples will work:
1593
- *
1594
- * ```js
1595
- * I.seeCurrentUrlEquals('/register');
1596
- * I.seeCurrentUrlEquals('http://my.site.com/register');
1597
- * ```
1598
- *
1599
- * @param {string} url value to check.
1600
- * ⚠️ returns a _promise_ which is synchronized internally by recorder
1601
- *
1602
- */
1603
- async seeCurrentUrlEquals(url) {
1604
- return this.browser.getCurrentUrl().then(currentUrl => urlEquals(this.options.url).assert(url, currentUrl));
1605
- }
1606
-
1607
- /**
1608
- * Checks that current url is not equal to provided one.
1609
- * If a relative url provided, a configured url will be prepended to it.
1610
- *
1611
- * ```js
1612
- * I.dontSeeCurrentUrlEquals('/login'); // relative url are ok
1613
- * I.dontSeeCurrentUrlEquals('http://mysite.com/login'); // absolute urls are also ok
1614
- * ```
1615
- *
1616
- * @param {string} url value to check.
1617
- * ⚠️ returns a _promise_ which is synchronized internally by recorder
1618
- *
1619
- */
1620
- async dontSeeCurrentUrlEquals(url) {
1621
- return this.browser.getCurrentUrl().then(currentUrl => urlEquals(this.options.url).negate(url, currentUrl));
1622
- }
1623
-
1624
- /**
1625
- * Saves screenshot of the specified locator to ouput folder (set in codecept.conf.ts or codecept.conf.js).
1626
- * Filename is relative to output folder.
1627
- *
1628
- * ```js
1629
- * I.saveElementScreenshot(`#submit`,'debug.png');
1630
- * ```
1631
- *
1632
- * @param {CodeceptJS.LocatorOrString} locator element located by CSS|XPath|strict locator.
1633
- * @param {string} fileName file name to save.
1634
- * ⚠️ returns a _promise_ which is synchronized internally by recorder
1635
- *
1636
- *
1637
- */
1638
- async saveElementScreenshot(locator, fileName) {
1639
- const outputFile = screenshotOutputFolder(fileName);
1640
-
1641
- const writeFile = (png, outputFile) => {
1642
- const fs = require('fs');
1643
- const stream = fs.createWriteStream(outputFile);
1644
- stream.write(Buffer.from(png, 'base64'));
1645
- stream.end();
1646
- return new Promise(resolve => stream.on('finish', resolve));
1647
- };
1648
-
1649
- const res = await this._locate(locator);
1650
- assertElementExists(res, locator);
1651
- if (res.length > 1) this.debug(`[Elements] Using first element out of ${res.length}`);
1652
- const elem = res[0];
1653
- this.debug(`Screenshot of ${(new Locator(locator))} element has been saved to ${outputFile}`);
1654
- const png = await elem.takeScreenshot();
1655
- return writeFile(png, outputFile);
1656
- }
1657
-
1658
- /**
1659
- * Saves a screenshot to ouput folder (set in codecept.conf.ts or codecept.conf.js).
1660
- * Filename is relative to output folder.
1661
- * 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.
1662
- *
1663
- * ```js
1664
- * I.saveScreenshot('debug.png');
1665
- * I.saveScreenshot('debug.png', true) //resizes to available scrollHeight and scrollWidth before taking screenshot
1666
- * ```
1667
- *
1668
- * @param {string} fileName file name to save.
1669
- * @param {boolean} [fullPage=false] (optional, `false` by default) flag to enable fullscreen screenshot mode.
1670
- * ⚠️ returns a _promise_ which is synchronized internally by recorder
1671
- *
1672
- */
1673
- async saveScreenshot(fileName, fullPage = false) {
1674
- const outputFile = screenshotOutputFolder(fileName);
1675
-
1676
- const writeFile = (png, outputFile) => {
1677
- const fs = require('fs');
1678
- const stream = fs.createWriteStream(outputFile);
1679
- stream.write(Buffer.from(png, 'base64'));
1680
- stream.end();
1681
- return new Promise(resolve => stream.on('finish', resolve));
1682
- };
1683
-
1684
- if (!fullPage) {
1685
- this.debug(`Screenshot has been saved to ${outputFile}`);
1686
- const png = await this.browser.takeScreenshot();
1687
- return writeFile(png, outputFile);
1688
- }
1689
-
1690
- let { width, height } = await this.browser.executeScript(() => ({ // eslint-disable-line
1691
- height: document.body.scrollHeight,
1692
- width: document.body.scrollWidth,
1693
- }));
1694
-
1695
- if (height < 100) height = 500;
1696
-
1697
- await this.browser.manage().window().setSize(width, height);
1698
- this.debug(`Screenshot has been saved to ${outputFile}, size: ${width}x${height}`);
1699
- const png = await this.browser.takeScreenshot();
1700
- return writeFile(png, outputFile);
1701
- }
1702
-
1703
- /**
1704
- * Clears a cookie by name,
1705
- * if none provided clears all cookies.
1706
- *
1707
- * ```js
1708
- * I.clearCookie();
1709
- * I.clearCookie('test');
1710
- * ```
1711
- *
1712
- * @param {?string} [cookie=null] (optional, `null` by default) cookie name
1713
- * ⚠️ returns a _promise_ which is synchronized internally by recorder
1714
- *
1715
- */
1716
- async clearCookie(cookie = null) {
1717
- if (!cookie) {
1718
- return this.browser.manage().deleteAllCookies();
1719
- }
1720
- return this.browser.manage().deleteCookie(cookie);
1721
- }
1722
-
1723
- /**
1724
- * Checks that cookie with given name exists.
1725
- *
1726
- * ```js
1727
- * I.seeCookie('Auth');
1728
- * ```
1729
- *
1730
- * @param {string} name cookie name.
1731
- * ⚠️ returns a _promise_ which is synchronized internally by recorder
1732
- *
1733
- */
1734
- async seeCookie(name) {
1735
- return this.browser.manage().getCookie(name).then(res => truth(`cookie ${name}`, 'to be set').assert(res));
1736
- }
1737
-
1738
- /**
1739
- * Checks that cookie with given name does not exist.
1740
- *
1741
- * ```js
1742
- * I.dontSeeCookie('auth'); // no auth cookie
1743
- * ```
1744
- *
1745
- * @param {string} name cookie name.
1746
- * ⚠️ returns a _promise_ which is synchronized internally by recorder
1747
- *
1748
- */
1749
- async dontSeeCookie(name) {
1750
- return this.browser.manage().getCookie(name).then(res => truth(`cookie ${name}`, 'to be set').negate(res));
1751
- }
1752
-
1753
- /**
1754
- * Gets a cookie object by name.
1755
- * If none provided gets all cookies.
1756
- * Resumes test execution, so **should be used inside async function with `await`** operator.
1757
- *
1758
- * ```js
1759
- * let cookie = await I.grabCookie('auth');
1760
- * assert(cookie.value, '123456');
1761
- * ```
1762
- *
1763
- * @param {?string} [name=null] cookie name.
1764
- * @returns {Promise<string>|Promise<string[]>} attribute value
1765
- *
1766
- *
1767
- * Returns cookie in JSON [format](https://code.google.com/p/selenium/wiki/JsonWireProtocol#Cookie_JSON_Object).
1768
- */
1769
- async grabCookie(name) {
1770
- if (!name) return this.browser.manage().getCookies();
1771
- return this.browser.manage().getCookie(name);
1772
- }
1773
-
1774
- /**
1775
- * Accepts the active JavaScript native popup window, as created by window.alert|window.confirm|window.prompt.
1776
- * Don't confuse popups with modal windows, as created by [various
1777
- * libraries](http://jster.net/category/windows-modals-popups). Appium: support only web testing
1778
- */
1779
- async acceptPopup() {
1780
- return this.browser.switchTo().alert().accept();
1781
- }
1782
-
1783
- /**
1784
- * Dismisses the active JavaScript popup, as created by window.alert|window.confirm|window.prompt.
1785
- */
1786
- async cancelPopup() {
1787
- return this.browser.switchTo().alert().dismiss();
1788
- }
1789
-
1790
- /**
1791
- * Checks that the active JavaScript popup, as created by `window.alert|window.confirm|window.prompt`, contains the
1792
- * given string.
1793
- *
1794
- * ```js
1795
- * I.seeInPopup('Popup text');
1796
- * ```
1797
- * @param {string} text value to check.
1798
- * ⚠️ returns a _promise_ which is synchronized internally by recorder
1799
- *
1800
- */
1801
- async seeInPopup(text) {
1802
- const popupAlert = await this.browser.switchTo().alert();
1803
- const res = await popupAlert.getText();
1804
- if (res === null) {
1805
- throw new Error('Popup is not opened');
1806
- }
1807
- stringIncludes('text in popup').assert(text, res);
1808
- }
1809
-
1810
- /**
1811
- * Grab the text within the popup. If no popup is visible then it will return null
1812
- *
1813
- * ```js
1814
- * await I.grabPopupText();
1815
- * ```
1816
- */
1817
- async grabPopupText() {
1818
- try {
1819
- const dialog = await this.browser.switchTo().alert();
1820
-
1821
- if (dialog) {
1822
- return dialog.getText();
1823
- }
1824
- } catch (e) {
1825
- if (e.message.match(/no.*?(alert|modal)/i)) {
1826
- // Don't throw an error
1827
- return null;
1828
- }
1829
- throw e;
1830
- }
1831
- }
1832
-
1833
- /**
1834
- * Resize the current window to provided width and height.
1835
- * First parameter can be set to `maximize`.
1836
- *
1837
- * @param {number} width width in pixels or `maximize`.
1838
- * @param {number} height height in pixels.
1839
- * ⚠️ returns a _promise_ which is synchronized internally by recorder
1840
- *
1841
- */
1842
- async resizeWindow(width, height) {
1843
- if (width === 'maximize') {
1844
- const res = await this.browser.executeScript('return [screen.width, screen.height]');
1845
- return this.browser.manage().window().setSize(parseInt(res[0], 10), parseInt(res[1], 10));
1846
- }
1847
- return this.browser.manage().window().setSize(parseInt(width, 10), parseInt(height, 10));
1848
- }
1849
-
1850
- /**
1851
- * Drag an item to a destination element.
1852
- *
1853
- * ```js
1854
- * I.dragAndDrop('#dragHandle', '#container');
1855
- * ```
1856
- *
1857
- * @param {LocatorOrString} srcElement located by CSS|XPath|strict locator.
1858
- * @param {LocatorOrString} destElement located by CSS|XPath|strict locator.
1859
- * ⚠️ returns a _promise_ which is synchronized internally by recorder
1860
- *
1861
- */
1862
- async dragAndDrop(srcElement, destElement) {
1863
- const srcEl = await this._locate(srcElement, true);
1864
- const destEl = await this._locate(destElement, true);
1865
- assertElementExists(srcEl, srcElement);
1866
- assertElementExists(destEl, destElement);
1867
- return this.browser
1868
- .actions()
1869
- .dragAndDrop(srcEl[0], destEl[0])
1870
- .perform();
1871
- }
1872
-
1873
- /**
1874
- * Close all tabs except for the current one.
1875
- *
1876
- * ```js
1877
- * I.closeOtherTabs();
1878
- * ```
1879
- */
1880
- async closeOtherTabs() {
1881
- const client = this.browser;
1882
-
1883
- const handles = await client.getAllWindowHandles();
1884
- const currentHandle = await client.getWindowHandle();
1885
- const otherHandles = handles.filter(handle => handle !== currentHandle);
1886
-
1887
- if (!otherHandles || !otherHandles.length) return;
1888
- let p = Promise.resolve();
1889
- otherHandles.forEach((handle) => {
1890
- p = p.then(() => client.switchTo().window(handle).then(() => client.close()));
1891
- });
1892
- p = p.then(() => client.switchTo().window(currentHandle));
1893
- return p;
1894
- }
1895
-
1896
- /**
1897
- * Close current tab
1898
- *
1899
- * ```js
1900
- * I.closeCurrentTab();
1901
- * ```
1902
- */
1903
- async closeCurrentTab() {
1904
- const client = this.browser;
1905
-
1906
- const currentHandle = await client.getWindowHandle();
1907
- const nextHandle = await this._getWindowHandle(-1);
1908
-
1909
- await client.switchTo().window(currentHandle);
1910
- await client.close();
1911
- return client.switchTo().window(nextHandle);
1912
- }
1913
-
1914
- /**
1915
- * Get the window handle relative to the current handle. i.e. the next handle or the previous.
1916
- * @param {Number} offset Offset from current handle index. i.e. offset < 0 will go to the previous handle and positive number will go to the next window handle in sequence.
1917
- */
1918
- async _getWindowHandle(offset = 0) {
1919
- const client = this.browser;
1920
- const handles = await client.getAllWindowHandles();
1921
- const index = handles.indexOf(await client.getWindowHandle());
1922
- const nextIndex = index + offset;
1923
-
1924
- return handles[nextIndex];
1925
- // return handles[(index + offset) % handles.length];
1926
- }
1927
-
1928
- /**
1929
- * Open new tab and switch to it
1930
- *
1931
- * ```js
1932
- * I.openNewTab();
1933
- * ```
1934
- */
1935
- async openNewTab() {
1936
- const client = this.browser;
1937
- await this.executeScript('window.open("about:blank")');
1938
- const handles = await client.getAllWindowHandles();
1939
- await client.switchTo().window(handles[handles.length - 1]);
1940
- }
1941
-
1942
- /**
1943
- * Switch focus to a particular tab by its number. It waits tabs loading and then switch tab
1944
- *
1945
- * ```js
1946
- * I.switchToNextTab();
1947
- * I.switchToNextTab(2);
1948
- * ```
1949
- */
1950
- async switchToNextTab(num = 1) {
1951
- const client = this.browser;
1952
- const newHandle = await this._getWindowHandle(num);
1953
-
1954
- if (!newHandle) {
1955
- throw new Error(`There is no ability to switch to next tab with offset ${num}`);
1956
- }
1957
- return client.switchTo().window(newHandle);
1958
- }
1959
-
1960
- /**
1961
- * Switch focus to a particular tab by its number. It waits tabs loading and then switch tab
1962
- *
1963
- * ```js
1964
- * I.switchToPreviousTab();
1965
- * I.switchToPreviousTab(2);
1966
- * ```
1967
- */
1968
- async switchToPreviousTab(num = 1) {
1969
- const client = this.browser;
1970
- const newHandle = await this._getWindowHandle(-1 * num);
1971
-
1972
- if (!newHandle) {
1973
- throw new Error(`There is no ability to switch to previous tab with offset ${num}`);
1974
- }
1975
- return client.switchTo().window(newHandle);
1976
- }
1977
-
1978
- /**
1979
- * Grab number of open tabs.
1980
- * Resumes test execution, so **should be used inside async function with `await`** operator.
1981
- *
1982
- * ```js
1983
- * let tabs = await I.grabNumberOfOpenTabs();
1984
- * ```
1985
- *
1986
- * @returns {Promise<number>} number of open tabs
1987
- *
1988
- */
1989
- async grabNumberOfOpenTabs() {
1990
- const pages = await this.browser.getAllWindowHandles();
1991
- return pages.length;
1992
- }
1993
-
1994
- /**
1995
- * Switches frame or in case of null locator reverts to parent.
1996
- *
1997
- * ```js
1998
- * I.switchTo('iframe'); // switch to first iframe
1999
- * I.switchTo(); // switch back to main page
2000
- * ```
2001
- *
2002
- * @param {?CodeceptJS.LocatorOrString} [locator=null] (optional, `null` by default) element located by CSS|XPath|strict locator.
2003
- * ⚠️ returns a _promise_ which is synchronized internally by recorder
2004
- *
2005
- */
2006
- async switchTo(locator) {
2007
- if (Number.isInteger(locator)) {
2008
- return this.browser.switchTo().frame(locator);
2009
- }
2010
- if (!locator) {
2011
- return this.browser.switchTo().frame(null);
2012
- }
2013
-
2014
- const els = await this._locate(withStrictLocator.call(this, locator), true);
2015
- assertElementExists(els, locator);
2016
- return this.browser.switchTo().frame(els[0]);
2017
- }
2018
-
2019
- /**
2020
- * Pauses execution for a number of seconds.
2021
- *
2022
- * ```js
2023
- * I.wait(2); // wait 2 secs
2024
- * ```
2025
- *
2026
- * @param {number} sec number of second to wait.
2027
- * ⚠️ returns a _promise_ which is synchronized internally by recorder
2028
- *
2029
- */
2030
- wait(sec) {
2031
- return this.browser.sleep(sec * 1000);
2032
- }
2033
-
2034
- /**
2035
- * Waits for element to be present on page (by default waits for 1sec).
2036
- * Element can be located by CSS or XPath.
2037
- *
2038
- * ```js
2039
- * I.waitForElement('.btn.continue');
2040
- * I.waitForElement('.btn.continue', 5); // wait for 5 secs
2041
- * ```
2042
- *
2043
- * @param {CodeceptJS.LocatorOrString} locator element located by CSS|XPath|strict locator.
2044
- * @param {number} [sec] (optional, `1` by default) time in seconds to wait
2045
- * ⚠️ returns a _promise_ which is synchronized internally by recorder
2046
- *
2047
- */
2048
- async waitForElement(locator, sec = null) {
2049
- const aSec = sec || this.options.waitForTimeoutInSeconds;
2050
- const el = global.element(guessLocator(locator) || global.by.css(locator));
2051
- return this.browser.wait(EC.presenceOf(el), aSec * 1000);
2052
- }
2053
-
2054
- async waitUntilExists(locator, sec = null) {
2055
- console.log(`waitUntilExists deprecated:
2056
- * use 'waitForElement' to wait for element to be attached
2057
- * use 'waitForDetached to wait for element to be removed'`);
2058
- return this.waitForDetached(locator, sec);
2059
- }
2060
-
2061
- /**
2062
- * Waits for an element to become not attached to the DOM on a page (by default waits for 1sec).
2063
- * Element can be located by CSS or XPath.
2064
- *
2065
- * ```js
2066
- * I.waitForDetached('#popup');
2067
- * ```
2068
- *
2069
- * @param {CodeceptJS.LocatorOrString} locator element located by CSS|XPath|strict locator.
2070
- * @param {number} [sec=1] (optional, `1` by default) time in seconds to wait
2071
- * ⚠️ returns a _promise_ which is synchronized internally by recorder
2072
- *
2073
- */
2074
- async waitForDetached(locator, sec = null) {
2075
- const aSec = sec || this.options.waitForTimeoutInSeconds;
2076
- const el = global.element(guessLocator(locator) || global.by.css(locator));
2077
- return this.browser.wait(EC.not(EC.presenceOf(el)), aSec * 1000).catch((err) => {
2078
- if (err.message && err.message.indexOf('Wait timed out after') > -1) {
2079
- throw new Error(`element (${JSON.stringify(locator)}) still on page after ${sec} sec`);
2080
- } else throw err;
2081
- });
2082
- }
2083
-
2084
- /**
2085
- * Waits for element to become clickable for number of seconds.
2086
- *
2087
- * ```js
2088
- * I.waitForClickable('#link');
2089
- * ```
2090
- */
2091
- async waitForClickable(locator, sec = null) {
2092
- const aSec = sec || this.options.waitForTimeoutInSeconds;
2093
- const el = global.element(guessLocator(locator) || global.by.css(locator));
2094
- return this.browser.wait(EC.elementToBeClickable(el), aSec * 1000);
2095
- }
2096
-
2097
- /**
2098
- * Waits for an element to become visible on a page (by default waits for 1sec).
2099
- * Element can be located by CSS or XPath.
2100
- *
2101
- * ```js
2102
- * I.waitForVisible('#popup');
2103
- * ```
2104
- *
2105
- * @param {CodeceptJS.LocatorOrString} locator element located by CSS|XPath|strict locator.
2106
- * @param {number} [sec=1] (optional, `1` by default) time in seconds to wait
2107
- * ⚠️ returns a _promise_ which is synchronized internally by recorder
2108
- *
2109
- */
2110
- async waitForVisible(locator, sec = null) {
2111
- const aSec = sec || this.options.waitForTimeoutInSeconds;
2112
- const el = global.element(guessLocator(locator) || global.by.css(locator));
2113
- return this.browser.wait(EC.visibilityOf(el), aSec * 1000);
2114
- }
2115
-
2116
- /**
2117
- * Waits for an element to hide (by default waits for 1sec).
2118
- * Element can be located by CSS or XPath.
2119
- *
2120
- * ```js
2121
- * I.waitToHide('#popup');
2122
- * ```
2123
- *
2124
- * @param {CodeceptJS.LocatorOrString} locator element located by CSS|XPath|strict locator.
2125
- * @param {number} [sec=1] (optional, `1` by default) time in seconds to wait
2126
- * ⚠️ returns a _promise_ which is synchronized internally by recorder
2127
- *
2128
- */
2129
- async waitToHide(locator, sec = null) {
2130
- return this.waitForInvisible(locator, sec);
2131
- }
2132
-
2133
- /**
2134
- * Waits for an element to be removed or become invisible on a page (by default waits for 1sec).
2135
- * Element can be located by CSS or XPath.
2136
- *
2137
- * ```js
2138
- * I.waitForInvisible('#popup');
2139
- * ```
2140
- *
2141
- * @param {CodeceptJS.LocatorOrString} locator element located by CSS|XPath|strict locator.
2142
- * @param {number} [sec=1] (optional, `1` by default) time in seconds to wait
2143
- * ⚠️ returns a _promise_ which is synchronized internally by recorder
2144
- *
2145
- */
2146
- async waitForInvisible(locator, sec = null) {
2147
- const aSec = sec || this.options.waitForTimeoutInSeconds;
2148
- const el = global.element(guessLocator(locator) || global.by.css(locator));
2149
- return this.browser.wait(EC.invisibilityOf(el), aSec * 1000);
2150
- }
2151
-
2152
- async waitForStalenessOf(locator, sec = null) {
2153
- console.log(`waitForStalenessOf deprecated.
2154
- * Use waitForDetached to wait for element to be removed from page
2155
- * Use waitForInvisible to wait for element to be hidden on page`);
2156
- return this.waitForInvisible(locator, sec);
2157
- }
2158
-
2159
- /**
2160
- * Waits for a specified number of elements on the page.
2161
- *
2162
- * ```js
2163
- * I.waitNumberOfVisibleElements('a', 3);
2164
- * ```
2165
- *
2166
- * @param {CodeceptJS.LocatorOrString} locator element located by CSS|XPath|strict locator.
2167
- * @param {number} num number of elements.
2168
- * @param {number} [sec=1] (optional, `1` by default) time in seconds to wait
2169
- * ⚠️ returns a _promise_ which is synchronized internally by recorder
2170
- *
2171
- */
2172
- async waitNumberOfVisibleElements(locator, num, sec = null) {
2173
- function visibilityCountOf(loc, expectedCount) {
2174
- return function () {
2175
- return global.element.all(loc)
2176
- .filter(el => el.isDisplayed())
2177
- .count()
2178
- .then(count => count === expectedCount);
2179
- };
2180
- }
2181
-
2182
- const aSec = sec || this.options.waitForTimeoutInSeconds;
2183
- const guessLoc = guessLocator(locator) || global.by.css(locator);
2184
-
2185
- return this.browser.wait(visibilityCountOf(guessLoc, num), aSec * 1000)
2186
- .catch(() => {
2187
- throw Error(`The number of elements (${(new Locator(locator))}) is not ${num} after ${aSec} sec`);
2188
- });
2189
- }
2190
-
2191
- /**
2192
- * Waits for element to become enabled (by default waits for 1sec).
2193
- * Element can be located by CSS or XPath.
2194
- *
2195
- * @param {CodeceptJS.LocatorOrString} locator element located by CSS|XPath|strict locator.
2196
- * @param {number} [sec=1] (optional) time in seconds to wait, 1 by default.
2197
- * ⚠️ returns a _promise_ which is synchronized internally by recorder
2198
- *
2199
- */
2200
- async waitForEnabled(locator, sec = null) {
2201
- const aSec = sec || this.options.waitForTimeoutInSeconds;
2202
- const el = global.element(guessLocator(locator) || global.by.css(locator));
2203
-
2204
- return this.browser.wait(EC.elementToBeClickable(el), aSec * 1000)
2205
- .catch(() => {
2206
- throw Error(`element (${(new Locator(locator))}) still not enabled after ${aSec} sec`);
2207
- });
2208
- }
2209
-
2210
- /**
2211
- * Waits for the specified value to be in value attribute.
2212
- *
2213
- * ```js
2214
- * I.waitForValue('//input', "GoodValue");
2215
- * ```
2216
- *
2217
- * @param {LocatorOrString} field input field.
2218
- * @param {string }value expected value.
2219
- * @param {number} [sec=1] (optional, `1` by default) time in seconds to wait
2220
- * ⚠️ returns a _promise_ which is synchronized internally by recorder
2221
- *
2222
- */
2223
- async waitForValue(field, value, sec = null) {
2224
- const aSec = sec || this.options.waitForTimeoutInSeconds;
2225
-
2226
- const valueToBeInElementValue = (loc) => {
2227
- return async () => {
2228
- const els = await findFields(this.browser, loc);
2229
-
2230
- if (!els) {
2231
- return false;
2232
- }
2233
- const values = await Promise.all(els.map(el => el.getAttribute('value')));
2234
- return values.filter(part => part.indexOf(value) >= 0).length > 0;
2235
- };
2236
- };
2237
-
2238
- return this.browser.wait(valueToBeInElementValue(field, value), aSec * 1000)
2239
- .catch(() => {
2240
- throw Error(`element (${field}) is not in DOM or there is no element(${field}) with value "${value}" after ${aSec} sec`);
2241
- });
2242
- }
2243
-
2244
- /**
2245
- * Waits for a function to return true (waits for 1 sec by default).
2246
- * Running in browser context.
2247
- *
2248
- * ```js
2249
- * I.waitForFunction(fn[, [args[, timeout]])
2250
- * ```
2251
- *
2252
- * ```js
2253
- * I.waitForFunction(() => window.requests == 0);
2254
- * I.waitForFunction(() => window.requests == 0, 5); // waits for 5 sec
2255
- * I.waitForFunction((count) => window.requests == count, [3], 5) // pass args and wait for 5 sec
2256
- * ```
2257
- *
2258
- * @param {string|function} fn to be executed in browser context.
2259
- * @param {any[]|number} [argsOrSec] (optional, `1` by default) arguments for function or seconds.
2260
- * @param {number} [sec] (optional, `1` by default) time in seconds to wait
2261
- * ⚠️ returns a _promise_ which is synchronized internally by recorder
2262
- *
2263
- */
2264
- async waitForFunction(fn, argsOrSec = null, sec = null) {
2265
- let args = [];
2266
- if (argsOrSec) {
2267
- if (Array.isArray(argsOrSec)) {
2268
- args = argsOrSec;
2269
- } else if (typeof argsOrSec === 'number') {
2270
- sec = argsOrSec;
2271
- }
2272
- }
2273
-
2274
- const aSec = sec || this.options.waitForTimeoutInSeconds;
2275
- return this.browser.wait(() => this.browser.executeScript.call(this.browser, fn, ...args), aSec * 1000);
2276
- }
2277
-
2278
- /**
2279
- * Waiting for the part of the URL to match the expected. Useful for SPA to understand that page was changed.
2280
- *
2281
- * ```js
2282
- * I.waitInUrl('/info', 2);
2283
- * ```
2284
- *
2285
- * @param {string} urlPart value to check.
2286
- * @param {number} [sec=1] (optional, `1` by default) time in seconds to wait
2287
- * ⚠️ returns a _promise_ which is synchronized internally by recorder
2288
- *
2289
- */
2290
- async waitInUrl(urlPart, sec = null) {
2291
- const aSec = sec || this.options.waitForTimeoutInSeconds;
2292
- const waitTimeout = aSec * 1000;
2293
-
2294
- return this.browser.wait(EC.urlContains(urlPart), waitTimeout)
2295
- .catch(async (e) => {
2296
- const currUrl = await this.browser.getCurrentUrl();
2297
- if (/wait timed out after/i.test(e.message)) {
2298
- throw new Error(`expected url to include ${urlPart}, but found ${currUrl}`);
2299
- } else {
2300
- throw e;
2301
- }
2302
- });
2303
- }
2304
-
2305
- /**
2306
- * Waits for the entire URL to match the expected
2307
- *
2308
- * ```js
2309
- * I.waitUrlEquals('/info', 2);
2310
- * I.waitUrlEquals('http://127.0.0.1:8000/info');
2311
- * ```
2312
- *
2313
- * @param {string} urlPart value to check.
2314
- * @param {number} [sec=1] (optional, `1` by default) time in seconds to wait
2315
- * ⚠️ returns a _promise_ which is synchronized internally by recorder
2316
- *
2317
- */
2318
- async waitUrlEquals(urlPart, sec = null) {
2319
- const aSec = sec || this.options.waitForTimeoutInSeconds;
2320
- const waitTimeout = aSec * 1000;
2321
- const baseUrl = this.options.url;
2322
- if (urlPart.indexOf('http') < 0) {
2323
- urlPart = baseUrl + urlPart;
2324
- }
2325
-
2326
- return this.browser.wait(EC.urlIs(urlPart), waitTimeout)
2327
- .catch(async (e) => {
2328
- const currUrl = await this.browser.getCurrentUrl();
2329
- if (/wait timed out after/i.test(e.message)) {
2330
- throw new Error(`expected url to be ${urlPart}, but found ${currUrl}`);
2331
- } else {
2332
- throw e;
2333
- }
2334
- });
2335
- }
2336
-
2337
- /**
2338
- * Waits for a text to appear (by default waits for 1sec).
2339
- * Element can be located by CSS or XPath.
2340
- * Narrow down search results by providing context.
2341
- *
2342
- * ```js
2343
- * I.waitForText('Thank you, form has been submitted');
2344
- * I.waitForText('Thank you, form has been submitted', 5, '#modal');
2345
- * ```
2346
- *
2347
- * @param {string }text to wait for.
2348
- * @param {number} [sec=1] (optional, `1` by default) time in seconds to wait
2349
- * @param {CodeceptJS.LocatorOrString} [context] (optional) element located by CSS|XPath|strict locator.
2350
- * ⚠️ returns a _promise_ which is synchronized internally by recorder
2351
- *
2352
- */
2353
- async waitForText(text, sec = null, context = null) {
2354
- if (!context) {
2355
- context = this.context;
2356
- }
2357
- const el = global.element(guessLocator(context) || global.by.css(context));
2358
- const aSec = sec || this.options.waitForTimeoutInSeconds;
2359
- return this.browser.wait(EC.textToBePresentInElement(el, text), aSec * 1000);
2360
- }
2361
-
2362
- // ANGULAR SPECIFIC
2363
-
2364
- /**
2365
- * Moves to url
2366
- */
2367
- moveTo(path) {
2368
- return this.browser.setLocation(path);
2369
- }
2370
-
2371
- /**
2372
- * Reload the current page.
2373
- *
2374
- * ```js
2375
- * I.refreshPage();
2376
- * ```
2377
- * ⚠️ returns a _promise_ which is synchronized internally by recorder
2378
- *
2379
- */
2380
- refreshPage() {
2381
- return this.browser.refresh();
2382
- }
2383
-
2384
- /**
2385
- * Reloads page
2386
- */
2387
- refresh() {
2388
- console.log('Deprecated in favor of refreshPage');
2389
- return this.browser.refresh();
2390
- }
2391
-
2392
- /**
2393
- * Scrolls to element matched by locator.
2394
- * Extra shift can be set with offsetX and offsetY options.
2395
- *
2396
- * ```js
2397
- * I.scrollTo('footer');
2398
- * I.scrollTo('#submit', 5, 5);
2399
- * ```
2400
- *
2401
- * @param {CodeceptJS.LocatorOrString} locator located by CSS|XPath|strict locator.
2402
- * @param {number} [offsetX=0] (optional, `0` by default) X-axis offset.
2403
- * @param {number} [offsetY=0] (optional, `0` by default) Y-axis offset.
2404
- * ⚠️ returns a _promise_ which is synchronized internally by recorder
2405
- *
2406
- */
2407
- async scrollTo(locator, offsetX = 0, offsetY = 0) {
2408
- if (typeof locator === 'number' && typeof offsetX === 'number') {
2409
- offsetY = offsetX;
2410
- offsetX = locator;
2411
- locator = null;
2412
- }
2413
-
2414
- if (locator) {
2415
- const res = await this._locate(locator, true);
2416
- if (!res || res.length === 0) {
2417
- return truth(`elements of ${(new Locator(locator))}`, 'to be seen').assert(false);
2418
- }
2419
- const elem = res[0];
2420
- const location = await elem.getLocation();
2421
- /* eslint-disable prefer-arrow-callback */
2422
- return this.executeScript(function (x, y) { return window.scrollTo(x, y); }, location.x + offsetX, location.y + offsetY);
2423
- /* eslint-enable */
2424
- }
2425
-
2426
- /* eslint-disable prefer-arrow-callback, comma-dangle */
2427
- return this.executeScript(function (x, y) { return window.scrollTo(x, y); }, offsetX, offsetY);
2428
- /* eslint-enable */
2429
- }
2430
-
2431
- /**
2432
- * Scroll page to the top.
2433
- *
2434
- * ```js
2435
- * I.scrollPageToTop();
2436
- * ```
2437
- * ⚠️ returns a _promise_ which is synchronized internally by recorder
2438
- *
2439
- */
2440
- async scrollPageToTop() {
2441
- return this.executeScript('window.scrollTo(0, 0);');
2442
- }
2443
-
2444
- /**
2445
- * Scroll page to the bottom.
2446
- *
2447
- * ```js
2448
- * I.scrollPageToBottom();
2449
- * ```
2450
- * ⚠️ returns a _promise_ which is synchronized internally by recorder
2451
- *
2452
- */
2453
- async scrollPageToBottom() {
2454
- /* eslint-disable prefer-arrow-callback, comma-dangle */
2455
- return this.executeScript(function () {
2456
- const body = document.body;
2457
- const html = document.documentElement;
2458
- window.scrollTo(0, Math.max(
2459
- body.scrollHeight, body.offsetHeight,
2460
- html.clientHeight, html.scrollHeight, html.offsetHeight
2461
- ));
2462
- });
2463
- /* eslint-enable */
2464
- }
2465
-
2466
- /**
2467
- * Retrieves a page scroll position and returns it to test.
2468
- * Resumes test execution, so **should be used inside an async function with `await`** operator.
2469
- *
2470
- * ```js
2471
- * let { x, y } = await I.grabPageScrollPosition();
2472
- * ```
2473
- *
2474
- * @returns {Promise<PageScrollPosition>} scroll position
2475
- *
2476
- */
2477
- async grabPageScrollPosition() {
2478
- /* eslint-disable comma-dangle */
2479
- function getScrollPosition() {
2480
- return {
2481
- x: window.pageXOffset,
2482
- y: window.pageYOffset
2483
- };
2484
- }
2485
- /* eslint-enable comma-dangle */
2486
- return this.executeScript(getScrollPosition);
2487
- }
2488
-
2489
- /**
2490
- * Injects Angular module.
2491
- *
2492
- * ```js
2493
- * I.haveModule('modName', function() {
2494
- * angular.module('modName', []).value('foo', 'bar');
2495
- * });
2496
- * ```
2497
- */
2498
- haveModule(modName, fn) {
2499
- return this.browser.addMockModule(modName, fn);
2500
- }
2501
-
2502
- /**
2503
- * Removes mocked Angular module. If modName not specified - clears all mock modules.
2504
- *
2505
- * ```js
2506
- * I.resetModule(); // clears all
2507
- * I.resetModule('modName');
2508
- * ```
2509
- */
2510
- resetModule(modName) {
2511
- if (!modName) {
2512
- return this.browser.clearMockModules();
2513
- }
2514
- return this.browser.removeMockModule(modName);
2515
- }
2516
-
2517
- /**
2518
- * Sets cookie(s).
2519
- *
2520
- * Can be a single cookie object or an array of cookies:
2521
- *
2522
- * ```js
2523
- * I.setCookie({name: 'auth', value: true});
2524
- *
2525
- * // as array
2526
- * I.setCookie([
2527
- * {name: 'auth', value: true},
2528
- * {name: 'agree', value: true}
2529
- * ]);
2530
- * ```
2531
- *
2532
- * @param {Cookie|Array<Cookie>} cookie a cookie object or array of cookie objects.
2533
- * ⚠️ returns a _promise_ which is synchronized internally by recorder
2534
- *
2535
- */
2536
- setCookie(cookie) {
2537
- return this.browser.manage().addCookie(cookie);
2538
- }
2539
- }
2540
-
2541
- module.exports = Protractor;
2542
-
2543
- async function findCheckable(client, locator) {
2544
- const matchedLocator = guessLocator(locator);
2545
- if (matchedLocator) {
2546
- return client.findElements(matchedLocator);
2547
- }
2548
- const literal = xpathLocator.literal(locator);
2549
- let els = await client.findElements(global.by.xpath(Locator.checkable.byText(literal)));
2550
- if (els.length) {
2551
- return els;
2552
- }
2553
- els = await client.findElements(global.by.xpath(Locator.checkable.byName(literal)));
2554
- if (els.length) {
2555
- return els;
2556
- }
2557
- return client.findElements(global.by.css(locator));
2558
- }
2559
-
2560
- function withStrictLocator(locator) {
2561
- locator = new Locator(locator);
2562
- if (locator.isAccessibilityId()) return withAccessiblitiyLocator.call(this, locator.value);
2563
- return locator.simplify();
2564
- }
2565
-
2566
- function withAccessiblitiyLocator(locator) {
2567
- if (this.isWeb === false) {
2568
- return `accessibility id:${locator.slice(1)}`;
2569
- }
2570
- return `[aria-label="${locator.slice(1)}"]`;
2571
- // hook before webdriverio supports native ~ locators in web
2572
- }
2573
-
2574
- async function findFields(client, locator) {
2575
- const matchedLocator = guessLocator(locator);
2576
- if (matchedLocator) {
2577
- return client.findElements(matchedLocator);
2578
- }
2579
- const literal = xpathLocator.literal(locator);
2580
-
2581
- let els = await client.findElements(global.by.xpath(Locator.field.labelEquals(literal)));
2582
- if (els.length) {
2583
- return els;
2584
- }
2585
-
2586
- els = await client.findElements(global.by.xpath(Locator.field.labelContains(literal)));
2587
- if (els.length) {
2588
- return els;
2589
- }
2590
- els = await client.findElements(global.by.xpath(Locator.field.byName(literal)));
2591
- if (els.length) {
2592
- return els;
2593
- }
2594
- return client.findElements(global.by.css(locator));
2595
- }
2596
-
2597
- async function proceedSee(assertType, text, context) {
2598
- let description;
2599
- let locator;
2600
- if (!context) {
2601
- if (this.context === this.options.rootElement) {
2602
- locator = guessLocator(this.context) || global.by.css(this.context);
2603
- description = 'web application';
2604
- } else {
2605
- // inside within block
2606
- locator = global.by.xpath('.//*');
2607
- description = `current context ${(new Locator(context)).toString()}`;
2608
- }
2609
- } else {
2610
- locator = guessLocator(context) || global.by.css(context);
2611
- description = `element ${(new Locator(context)).toString()}`;
2612
- }
2613
- const enableSmartWait = !!this.context && assertType === 'assert';
2614
- const els = await this._smartWait(() => this.browser.findElements(locator), enableSmartWait);
2615
- const promises = [];
2616
- let source = '';
2617
- els.forEach(el => promises.push(el.getText().then(elText => source += `| ${elText}`)));
2618
- await Promise.all(promises);
2619
- return stringIncludes(description)[assertType](text, source);
2620
- }
2621
-
2622
- async function proceedSeeInField(assertType, field, value) {
2623
- const els = await findFields(this.browser, field);
2624
- assertElementExists(els, field, 'Field');
2625
- const el = els[0];
2626
- const tag = await el.getTagName();
2627
- const fieldVal = await el.getAttribute('value');
2628
- if (tag === 'select') {
2629
- // locate option by values and check them
2630
- const literal = xpathLocator.literal(fieldVal);
2631
- const textEl = await el.findElement(global.by.xpath(Locator.select.byValue(literal)));
2632
- const text = await textEl.getText();
2633
- return equals(`select option by ${field}`)[assertType](value, text);
2634
- }
2635
- return stringIncludes(`field by ${field}`)[assertType](value, fieldVal);
2636
- }
2637
-
2638
- async function proceedIsChecked(assertType, option) {
2639
- const els = await findCheckable(this.browser, option);
2640
- assertElementExists(els, option, 'Option');
2641
- const elsSelected = [];
2642
- els.forEach(el => elsSelected.push(el.isSelected()));
2643
- const values = await Promise.all(elsSelected);
2644
- const selected = values.reduce((prev, cur) => prev || cur);
2645
- return truth(`checkable ${option}`, 'to be checked')[assertType](selected);
2646
- }
2647
-
2648
- async function findClickable(matcher, locator) {
2649
- locator = new Locator(locator);
2650
- if (!locator.isFuzzy()) {
2651
- const els = await this._locate(locator, true);
2652
- assertElementExists(els, locator.value);
2653
- return els[0];
2654
- }
2655
- const literal = xpathLocator.literal(locator.value);
2656
- const narrowLocator = Locator.clickable.narrow(literal);
2657
- let els = await matcher.findElements(global.by.xpath(narrowLocator));
2658
- if (els.length) {
2659
- return els[0];
2660
- }
2661
-
2662
- els = await matcher.findElements(global.by.xpath(Locator.clickable.wide(literal)));
2663
- if (els.length) {
2664
- return els[0];
2665
- }
2666
- return matcher.findElement(global.by.css(locator.value));
2667
- }
2668
-
2669
- function guessLocator(locator) {
2670
- const l = new Locator(locator);
2671
- if (l.isFuzzy()) return false;
2672
- if (l.type) return global.by[l.type](l.value);
2673
- return false;
2674
- }
2675
-
2676
- function assertElementExists(res, locator, prefix, suffix) {
2677
- if (!res.length) {
2678
- throw new ElementNotFound(locator, prefix, suffix);
2679
- }
2680
- }
2681
-
2682
- function isFrameLocator(locator) {
2683
- locator = new Locator(locator);
2684
- if (locator.isFrame()) return locator.value;
2685
- return false;
2686
- }
2687
-
2688
- function isWithin() {
2689
- return Object.keys(withinStore).length !== 0;
2690
- }
2691
-
2692
- function loadGlobals(browser) {
2693
- global.browser = browser;
2694
- global.$ = browser.$;
2695
- global.$$ = browser.$$;
2696
- global.element = browser.element;
2697
- global.by = global.By = new ProtractorBy();
2698
- global.ExpectedConditions = EC = new ProtractorExpectedConditions(browser);
2699
- }