codeceptjs 3.5.0 → 3.5.1-2.beta.7

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (273) hide show
  1. package/README.md +24 -25
  2. package/lib/actor.js +6 -3
  3. package/lib/ai.js +12 -3
  4. package/lib/cli.js +12 -2
  5. package/lib/codecept.js +4 -0
  6. package/lib/colorUtils.js +10 -0
  7. package/lib/command/definitions.js +2 -7
  8. package/lib/command/dryRun.js +2 -1
  9. package/lib/command/info.js +24 -0
  10. package/lib/command/init.js +51 -5
  11. package/lib/command/run-multiple/collection.js +17 -5
  12. package/lib/command/run-multiple.js +4 -2
  13. package/lib/command/run-workers.js +66 -4
  14. package/lib/command/run.js +7 -0
  15. package/lib/command/workers/runTests.js +39 -0
  16. package/lib/data/context.js +14 -6
  17. package/lib/event.js +4 -0
  18. package/lib/helper/ApiDataFactory.js +2 -1
  19. package/lib/helper/Appium.js +73 -24
  20. package/lib/helper/Expect.js +422 -0
  21. package/lib/helper/FileSystem.js +1 -1
  22. package/lib/helper/GraphQL.js +25 -0
  23. package/lib/helper/Nightmare.js +9 -4
  24. package/lib/helper/OpenAI.js +14 -10
  25. package/lib/helper/Playwright.js +1205 -288
  26. package/lib/helper/Protractor.js +11 -6
  27. package/lib/helper/Puppeteer.js +173 -61
  28. package/lib/helper/TestCafe.js +44 -9
  29. package/lib/helper/WebDriver.js +231 -82
  30. package/lib/helper/errors/ElementNotFound.js +2 -1
  31. package/lib/helper/extras/PlaywrightReactVueLocator.js +38 -0
  32. package/lib/helper/scripts/blurElement.js +17 -0
  33. package/lib/helper/scripts/focusElement.js +17 -0
  34. package/lib/helper/scripts/highlightElement.js +2 -2
  35. package/lib/html.js +3 -3
  36. package/lib/interfaces/bdd.js +1 -1
  37. package/lib/interfaces/gherkin.js +37 -3
  38. package/lib/interfaces/scenarioConfig.js +1 -0
  39. package/lib/locator.js +17 -4
  40. package/lib/mochaFactory.js +2 -1
  41. package/lib/output.js +1 -1
  42. package/lib/pause.js +12 -9
  43. package/lib/plugin/autoLogin.js +45 -10
  44. package/lib/plugin/heal.js +47 -17
  45. package/lib/plugin/retryFailedStep.js +10 -1
  46. package/lib/plugin/retryTo.js +2 -4
  47. package/lib/plugin/selenoid.js +6 -1
  48. package/lib/plugin/standardActingHelpers.js +0 -2
  49. package/lib/plugin/stepByStepReport.js +2 -2
  50. package/lib/plugin/tryTo.js +5 -7
  51. package/lib/plugin/wdio.js +0 -1
  52. package/lib/recorder.js +20 -9
  53. package/lib/session.js +1 -1
  54. package/lib/step.js +30 -11
  55. package/lib/ui.js +1 -0
  56. package/lib/utils.js +18 -1
  57. package/lib/workers.js +28 -3
  58. package/package.json +108 -98
  59. package/translations/de-DE.js +5 -0
  60. package/translations/fr-FR.js +14 -1
  61. package/translations/it-IT.js +1 -0
  62. package/translations/ja-JP.js +5 -0
  63. package/translations/pl-PL.js +5 -0
  64. package/translations/pt-BR.js +1 -0
  65. package/translations/ru-RU.js +1 -0
  66. package/translations/zh-CN.js +5 -0
  67. package/translations/zh-TW.js +5 -0
  68. package/typings/index.d.ts +8 -6
  69. package/typings/promiseBasedTypes.d.ts +784 -822
  70. package/typings/types.d.ts +1214 -727
  71. package/CHANGELOG.md +0 -2492
  72. package/docs/advanced.md +0 -351
  73. package/docs/ai.md +0 -246
  74. package/docs/api.md +0 -323
  75. package/docs/basics.md +0 -980
  76. package/docs/bdd.md +0 -535
  77. package/docs/best.md +0 -237
  78. package/docs/books.md +0 -37
  79. package/docs/bootstrap.md +0 -135
  80. package/docs/build/ApiDataFactory.js +0 -409
  81. package/docs/build/Appium.js +0 -1978
  82. package/docs/build/FileSystem.js +0 -228
  83. package/docs/build/GraphQL.js +0 -204
  84. package/docs/build/GraphQLDataFactory.js +0 -309
  85. package/docs/build/JSONResponse.js +0 -338
  86. package/docs/build/Mochawesome.js +0 -71
  87. package/docs/build/Nightmare.js +0 -2147
  88. package/docs/build/OpenAI.js +0 -122
  89. package/docs/build/Playwright.js +0 -4134
  90. package/docs/build/Polly.js +0 -42
  91. package/docs/build/Protractor.js +0 -2701
  92. package/docs/build/Puppeteer.js +0 -3743
  93. package/docs/build/REST.js +0 -344
  94. package/docs/build/SeleniumWebdriver.js +0 -76
  95. package/docs/build/TestCafe.js +0 -2059
  96. package/docs/build/WebDriver.js +0 -4042
  97. package/docs/changelog.md +0 -2501
  98. package/docs/commands.md +0 -254
  99. package/docs/community-helpers.md +0 -58
  100. package/docs/configuration.md +0 -157
  101. package/docs/continuous-integration.md +0 -22
  102. package/docs/custom-helpers.md +0 -306
  103. package/docs/data.md +0 -375
  104. package/docs/detox.md +0 -235
  105. package/docs/docker.md +0 -137
  106. package/docs/email.md +0 -183
  107. package/docs/examples.md +0 -149
  108. package/docs/helpers/ApiDataFactory.md +0 -266
  109. package/docs/helpers/Appium.md +0 -1317
  110. package/docs/helpers/Detox.md +0 -586
  111. package/docs/helpers/FileSystem.md +0 -152
  112. package/docs/helpers/GraphQL.md +0 -130
  113. package/docs/helpers/GraphQLDataFactory.md +0 -226
  114. package/docs/helpers/JSONResponse.md +0 -254
  115. package/docs/helpers/Mochawesome.md +0 -8
  116. package/docs/helpers/MockRequest.md +0 -377
  117. package/docs/helpers/Nightmare.md +0 -1258
  118. package/docs/helpers/OpenAI.md +0 -70
  119. package/docs/helpers/Playwright.md +0 -2250
  120. package/docs/helpers/Polly.md +0 -44
  121. package/docs/helpers/Puppeteer-firefox.md +0 -86
  122. package/docs/helpers/Puppeteer.md +0 -2147
  123. package/docs/helpers/REST.md +0 -218
  124. package/docs/helpers/TestCafe.md +0 -1224
  125. package/docs/helpers/WebDriver.md +0 -2325
  126. package/docs/hooks.md +0 -340
  127. package/docs/index.md +0 -111
  128. package/docs/installation.md +0 -75
  129. package/docs/internal-api.md +0 -265
  130. package/docs/locators.md +0 -331
  131. package/docs/mobile-react-native-locators.md +0 -67
  132. package/docs/mobile.md +0 -344
  133. package/docs/nightmare.md +0 -223
  134. package/docs/pageobjects.md +0 -291
  135. package/docs/parallel.md +0 -288
  136. package/docs/playwright.md +0 -609
  137. package/docs/plugins.md +0 -1225
  138. package/docs/puppeteer.md +0 -316
  139. package/docs/quickstart.md +0 -163
  140. package/docs/react.md +0 -69
  141. package/docs/reports.md +0 -392
  142. package/docs/secrets.md +0 -36
  143. package/docs/shadow.md +0 -68
  144. package/docs/shared/keys.mustache +0 -31
  145. package/docs/shared/react.mustache +0 -1
  146. package/docs/testcafe.md +0 -174
  147. package/docs/translation.md +0 -247
  148. package/docs/tutorial.md +0 -271
  149. package/docs/typescript.md +0 -180
  150. package/docs/ui.md +0 -59
  151. package/docs/videos.md +0 -28
  152. package/docs/visual.md +0 -202
  153. package/docs/vue.md +0 -121
  154. package/docs/webapi/amOnPage.mustache +0 -11
  155. package/docs/webapi/appendField.mustache +0 -11
  156. package/docs/webapi/attachFile.mustache +0 -12
  157. package/docs/webapi/checkOption.mustache +0 -13
  158. package/docs/webapi/clearCookie.mustache +0 -10
  159. package/docs/webapi/clearField.mustache +0 -9
  160. package/docs/webapi/click.mustache +0 -25
  161. package/docs/webapi/clickLink.mustache +0 -8
  162. package/docs/webapi/closeCurrentTab.mustache +0 -7
  163. package/docs/webapi/closeOtherTabs.mustache +0 -8
  164. package/docs/webapi/dontSee.mustache +0 -11
  165. package/docs/webapi/dontSeeCheckboxIsChecked.mustache +0 -10
  166. package/docs/webapi/dontSeeCookie.mustache +0 -8
  167. package/docs/webapi/dontSeeCurrentUrlEquals.mustache +0 -10
  168. package/docs/webapi/dontSeeElement.mustache +0 -8
  169. package/docs/webapi/dontSeeElementInDOM.mustache +0 -8
  170. package/docs/webapi/dontSeeInCurrentUrl.mustache +0 -4
  171. package/docs/webapi/dontSeeInField.mustache +0 -11
  172. package/docs/webapi/dontSeeInSource.mustache +0 -8
  173. package/docs/webapi/dontSeeInTitle.mustache +0 -8
  174. package/docs/webapi/doubleClick.mustache +0 -13
  175. package/docs/webapi/downloadFile.mustache +0 -12
  176. package/docs/webapi/dragAndDrop.mustache +0 -9
  177. package/docs/webapi/dragSlider.mustache +0 -11
  178. package/docs/webapi/executeAsyncScript.mustache +0 -24
  179. package/docs/webapi/executeScript.mustache +0 -26
  180. package/docs/webapi/fillField.mustache +0 -16
  181. package/docs/webapi/forceClick.mustache +0 -28
  182. package/docs/webapi/forceRightClick.mustache +0 -18
  183. package/docs/webapi/grabAllWindowHandles.mustache +0 -7
  184. package/docs/webapi/grabAttributeFrom.mustache +0 -10
  185. package/docs/webapi/grabAttributeFromAll.mustache +0 -9
  186. package/docs/webapi/grabBrowserLogs.mustache +0 -9
  187. package/docs/webapi/grabCookie.mustache +0 -11
  188. package/docs/webapi/grabCssPropertyFrom.mustache +0 -11
  189. package/docs/webapi/grabCssPropertyFromAll.mustache +0 -10
  190. package/docs/webapi/grabCurrentUrl.mustache +0 -9
  191. package/docs/webapi/grabCurrentWindowHandle.mustache +0 -6
  192. package/docs/webapi/grabDataFromPerformanceTiming.mustache +0 -20
  193. package/docs/webapi/grabElementBoundingRect.mustache +0 -20
  194. package/docs/webapi/grabGeoLocation.mustache +0 -8
  195. package/docs/webapi/grabHTMLFrom.mustache +0 -10
  196. package/docs/webapi/grabHTMLFromAll.mustache +0 -9
  197. package/docs/webapi/grabNumberOfOpenTabs.mustache +0 -8
  198. package/docs/webapi/grabNumberOfVisibleElements.mustache +0 -9
  199. package/docs/webapi/grabPageScrollPosition.mustache +0 -8
  200. package/docs/webapi/grabPopupText.mustache +0 -5
  201. package/docs/webapi/grabSource.mustache +0 -8
  202. package/docs/webapi/grabTextFrom.mustache +0 -10
  203. package/docs/webapi/grabTextFromAll.mustache +0 -9
  204. package/docs/webapi/grabTitle.mustache +0 -8
  205. package/docs/webapi/grabValueFrom.mustache +0 -9
  206. package/docs/webapi/grabValueFromAll.mustache +0 -8
  207. package/docs/webapi/moveCursorTo.mustache +0 -12
  208. package/docs/webapi/openNewTab.mustache +0 -7
  209. package/docs/webapi/pressKey.mustache +0 -12
  210. package/docs/webapi/pressKeyDown.mustache +0 -12
  211. package/docs/webapi/pressKeyUp.mustache +0 -12
  212. package/docs/webapi/pressKeyWithKeyNormalization.mustache +0 -60
  213. package/docs/webapi/refreshPage.mustache +0 -6
  214. package/docs/webapi/resizeWindow.mustache +0 -6
  215. package/docs/webapi/rightClick.mustache +0 -14
  216. package/docs/webapi/saveElementScreenshot.mustache +0 -10
  217. package/docs/webapi/saveScreenshot.mustache +0 -12
  218. package/docs/webapi/say.mustache +0 -10
  219. package/docs/webapi/scrollIntoView.mustache +0 -11
  220. package/docs/webapi/scrollPageToBottom.mustache +0 -6
  221. package/docs/webapi/scrollPageToTop.mustache +0 -6
  222. package/docs/webapi/scrollTo.mustache +0 -12
  223. package/docs/webapi/see.mustache +0 -11
  224. package/docs/webapi/seeAttributesOnElements.mustache +0 -9
  225. package/docs/webapi/seeCheckboxIsChecked.mustache +0 -10
  226. package/docs/webapi/seeCookie.mustache +0 -8
  227. package/docs/webapi/seeCssPropertiesOnElements.mustache +0 -9
  228. package/docs/webapi/seeCurrentUrlEquals.mustache +0 -11
  229. package/docs/webapi/seeElement.mustache +0 -8
  230. package/docs/webapi/seeElementInDOM.mustache +0 -8
  231. package/docs/webapi/seeInCurrentUrl.mustache +0 -8
  232. package/docs/webapi/seeInField.mustache +0 -12
  233. package/docs/webapi/seeInPopup.mustache +0 -8
  234. package/docs/webapi/seeInSource.mustache +0 -7
  235. package/docs/webapi/seeInTitle.mustache +0 -8
  236. package/docs/webapi/seeNumberOfElements.mustache +0 -11
  237. package/docs/webapi/seeNumberOfVisibleElements.mustache +0 -10
  238. package/docs/webapi/seeTextEquals.mustache +0 -9
  239. package/docs/webapi/seeTitleEquals.mustache +0 -8
  240. package/docs/webapi/selectOption.mustache +0 -21
  241. package/docs/webapi/setCookie.mustache +0 -16
  242. package/docs/webapi/setGeoLocation.mustache +0 -12
  243. package/docs/webapi/switchTo.mustache +0 -9
  244. package/docs/webapi/switchToNextTab.mustache +0 -10
  245. package/docs/webapi/switchToPreviousTab.mustache +0 -10
  246. package/docs/webapi/type.mustache +0 -21
  247. package/docs/webapi/uncheckOption.mustache +0 -13
  248. package/docs/webapi/wait.mustache +0 -8
  249. package/docs/webapi/waitForClickable.mustache +0 -11
  250. package/docs/webapi/waitForDetached.mustache +0 -10
  251. package/docs/webapi/waitForElement.mustache +0 -11
  252. package/docs/webapi/waitForEnabled.mustache +0 -6
  253. package/docs/webapi/waitForFunction.mustache +0 -17
  254. package/docs/webapi/waitForInvisible.mustache +0 -10
  255. package/docs/webapi/waitForText.mustache +0 -13
  256. package/docs/webapi/waitForValue.mustache +0 -10
  257. package/docs/webapi/waitForVisible.mustache +0 -10
  258. package/docs/webapi/waitInUrl.mustache +0 -9
  259. package/docs/webapi/waitNumberOfVisibleElements.mustache +0 -10
  260. package/docs/webapi/waitToHide.mustache +0 -10
  261. package/docs/webapi/waitUrlEquals.mustache +0 -10
  262. package/docs/webdriver.md +0 -657
  263. package/docs/wiki/Books-&-Posts.md +0 -27
  264. package/docs/wiki/Community-Helpers-&-Plugins.md +0 -49
  265. package/docs/wiki/Converting-Playwright-to-Istanbul-Coverage.md +0 -29
  266. package/docs/wiki/Examples.md +0 -139
  267. package/docs/wiki/Google-Summer-of-Code-(GSoC)-2020.md +0 -68
  268. package/docs/wiki/Home.md +0 -16
  269. package/docs/wiki/Release-Process.md +0 -24
  270. package/docs/wiki/Roadmap.md +0 -23
  271. package/docs/wiki/Tests.md +0 -1393
  272. package/docs/wiki/Upgrading-to-CodeceptJS-3.md +0 -153
  273. package/docs/wiki/Videos.md +0 -19
@@ -1,2701 +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
- * // typing secret
857
- * I.appendField('password', secret('123456'));
858
- * ```
859
- * @param {CodeceptJS.LocatorOrString} field located by label|name|CSS|XPath|strict locator
860
- * @param {string} value text value to append.
861
- * ⚠️ returns a _promise_ which is synchronized internally by recorder
862
- *
863
- */
864
- async appendField(field, value) {
865
- const els = await findFields(this.browser, field);
866
- assertElementExists(els, field, 'Field');
867
- return els[0].sendKeys(value.toString());
868
- }
869
-
870
- /**
871
- * Clears a `<textarea>` or text `<input>` element's value.
872
- *
873
- * ```js
874
- * I.clearField('Email');
875
- * I.clearField('user[email]');
876
- * I.clearField('#email');
877
- * ```
878
- * @param {LocatorOrString} editable field located by label|name|CSS|XPath|strict locator.
879
- * ⚠️ returns a _promise_ which is synchronized internally by recorder.
880
- *
881
- */
882
- async clearField(field) {
883
- const els = await findFields(this.browser, field);
884
- assertElementExists(els, field, 'Field');
885
- return els[0].clear();
886
- }
887
-
888
- /**
889
- * Selects a checkbox or radio button.
890
- * Element is located by label or name or CSS or XPath.
891
- *
892
- * The second parameter is a context (CSS or XPath locator) to narrow the search.
893
- *
894
- * ```js
895
- * I.checkOption('#agree');
896
- * I.checkOption('I Agree to Terms and Conditions');
897
- * I.checkOption('agree', '//form');
898
- * ```
899
- * @param {CodeceptJS.LocatorOrString} field checkbox located by label | name | CSS | XPath | strict locator.
900
- * @param {?CodeceptJS.LocatorOrString} [context=null] (optional, `null` by default) element located by CSS | XPath | strict locator.
901
- * ⚠️ returns a _promise_ which is synchronized internally by recorder
902
- *
903
- */
904
- async checkOption(field, context = null) {
905
- let matcher = this.browser;
906
- if (context) {
907
- const els = await this._locate(context, true);
908
- assertElementExists(els, context);
909
- matcher = els[0];
910
- }
911
- const els = await findCheckable(matcher, field);
912
- assertElementExists(els, field, 'Checkbox or radio');
913
- const isSelected = await els[0].isSelected();
914
- if (!isSelected) return els[0].click();
915
- }
916
-
917
- /**
918
- * Unselects a checkbox or radio button.
919
- * Element is located by label or name or CSS or XPath.
920
- *
921
- * The second parameter is a context (CSS or XPath locator) to narrow the search.
922
- *
923
- * ```js
924
- * I.uncheckOption('#agree');
925
- * I.uncheckOption('I Agree to Terms and Conditions');
926
- * I.uncheckOption('agree', '//form');
927
- * ```
928
- * @param {CodeceptJS.LocatorOrString} field checkbox located by label | name | CSS | XPath | strict locator.
929
- * @param {?CodeceptJS.LocatorOrString} [context=null] (optional, `null` by default) element located by CSS | XPath | strict locator.
930
- * ⚠️ returns a _promise_ which is synchronized internally by recorder
931
- *
932
- */
933
- async uncheckOption(field, context = null) {
934
- let matcher = this.browser;
935
- if (context) {
936
- const els = await this._locate(context, true);
937
- assertElementExists(els, context);
938
- matcher = els[0];
939
- }
940
- const els = await findCheckable(matcher, field);
941
- assertElementExists(els, field, 'Checkbox or radio');
942
- const isSelected = await els[0].isSelected();
943
- if (isSelected) return els[0].click();
944
- }
945
-
946
- /**
947
- * Verifies that the specified checkbox is checked.
948
- *
949
- * ```js
950
- * I.seeCheckboxIsChecked('Agree');
951
- * I.seeCheckboxIsChecked('#agree'); // I suppose user agreed to terms
952
- * I.seeCheckboxIsChecked({css: '#signup_form input[type=checkbox]'});
953
- * ```
954
- *
955
- * @param {CodeceptJS.LocatorOrString} field located by label|name|CSS|XPath|strict locator.
956
- * ⚠️ returns a _promise_ which is synchronized internally by recorder
957
- *
958
- */
959
- async seeCheckboxIsChecked(field) {
960
- return proceedIsChecked.call(this, 'assert', field);
961
- }
962
-
963
- /**
964
- * Verifies that the specified checkbox is not checked.
965
- *
966
- * ```js
967
- * I.dontSeeCheckboxIsChecked('#agree'); // located by ID
968
- * I.dontSeeCheckboxIsChecked('I agree to terms'); // located by label
969
- * I.dontSeeCheckboxIsChecked('agree'); // located by name
970
- * ```
971
- *
972
- * @param {CodeceptJS.LocatorOrString} field located by label|name|CSS|XPath|strict locator.
973
- * ⚠️ returns a _promise_ which is synchronized internally by recorder
974
- *
975
- */
976
- async dontSeeCheckboxIsChecked(field) {
977
- return proceedIsChecked.call(this, 'negate', field);
978
- }
979
-
980
- /**
981
- * Retrieves all texts from an element located by CSS or XPath and returns it to test.
982
- * Resumes test execution, so **should be used inside async with `await`** operator.
983
- *
984
- * ```js
985
- * let pins = await I.grabTextFromAll('#pin li');
986
- * ```
987
- *
988
- * @param {CodeceptJS.LocatorOrString} locator element located by CSS|XPath|strict locator.
989
- * @returns {Promise<string[]>} attribute value
990
- *
991
- */
992
- async grabTextFromAll(locator) {
993
- const els = await this._locate(locator);
994
- const texts = [];
995
- for (const el of els) {
996
- texts.push(await el.getText());
997
- }
998
- return texts;
999
- }
1000
-
1001
- /**
1002
- * Retrieves a text from an element located by CSS or XPath and returns it to test.
1003
- * Resumes test execution, so **should be used inside async with `await`** operator.
1004
- *
1005
- * ```js
1006
- * let pin = await I.grabTextFrom('#pin');
1007
- * ```
1008
- * If multiple elements found returns first element.
1009
- *
1010
- * @param {CodeceptJS.LocatorOrString} locator element located by CSS|XPath|strict locator.
1011
- * @returns {Promise<string>} attribute value
1012
- *
1013
- */
1014
- async grabTextFrom(locator) {
1015
- const texts = await this.grabTextFromAll(locator);
1016
- assertElementExists(texts, locator);
1017
- if (texts.length > 1) {
1018
- this.debugSection('GrabText', `Using first element out of ${texts.length}`);
1019
- }
1020
-
1021
- return texts[0];
1022
- }
1023
-
1024
- /**
1025
- * Retrieves all the innerHTML from elements located by CSS or XPath and returns it to test.
1026
- * Resumes test execution, so **should be used inside async function with `await`** operator.
1027
- *
1028
- * ```js
1029
- * let postHTMLs = await I.grabHTMLFromAll('.post');
1030
- * ```
1031
- *
1032
- * @param {CodeceptJS.LocatorOrString} element located by CSS|XPath|strict locator.
1033
- * @returns {Promise<string[]>} HTML code for an element
1034
- *
1035
- */
1036
- async grabHTMLFromAll(locator) {
1037
- const els = await this._locate(locator);
1038
-
1039
- const html = await Promise.all(els.map((el) => {
1040
- return this.browser.executeScript('return arguments[0].innerHTML;', el);
1041
- }));
1042
-
1043
- return html;
1044
- }
1045
-
1046
- /**
1047
- * Retrieves the innerHTML from an element located by CSS or XPath and returns it to test.
1048
- * Resumes test execution, so **should be used inside async function with `await`** operator.
1049
- * If more than one element is found - HTML of first element is returned.
1050
- *
1051
- * ```js
1052
- * let postHTML = await I.grabHTMLFrom('#post');
1053
- * ```
1054
- *
1055
- * @param {CodeceptJS.LocatorOrString} element located by CSS|XPath|strict locator.
1056
- * @returns {Promise<string>} HTML code for an element
1057
- *
1058
- */
1059
- async grabHTMLFrom(locator) {
1060
- const html = await this.grabHTMLFromAll(locator);
1061
- assertElementExists(html, locator);
1062
- if (html.length > 1) {
1063
- this.debugSection('GrabHTMl', `Using first element out of ${html.length}`);
1064
- }
1065
-
1066
- return html[0];
1067
- }
1068
-
1069
- /**
1070
- * Retrieves an array of value from a form located by CSS or XPath and returns it to test.
1071
- * Resumes test execution, so **should be used inside async function with `await`** operator.
1072
- *
1073
- * ```js
1074
- * let inputs = await I.grabValueFromAll('//form/input');
1075
- * ```
1076
- * @param {CodeceptJS.LocatorOrString} locator field located by label|name|CSS|XPath|strict locator.
1077
- * @returns {Promise<string[]>} attribute value
1078
- *
1079
- */
1080
- async grabValueFromAll(locator) {
1081
- const els = await findFields(this.browser, locator);
1082
- const values = await Promise.all(els.map(el => el.getAttribute('value')));
1083
-
1084
- return values;
1085
- }
1086
-
1087
- /**
1088
- * Retrieves a value from a form element located by CSS or XPath and returns it to test.
1089
- * Resumes test execution, so **should be used inside async function with `await`** operator.
1090
- * If more than one element is found - value of first element is returned.
1091
- *
1092
- * ```js
1093
- * let email = await I.grabValueFrom('input[name=email]');
1094
- * ```
1095
- * @param {CodeceptJS.LocatorOrString} locator field located by label|name|CSS|XPath|strict locator.
1096
- * @returns {Promise<string>} attribute value
1097
- *
1098
- */
1099
- async grabValueFrom(locator) {
1100
- const values = await this.grabValueFromAll(locator);
1101
- assertElementExists(values, locator, 'Field');
1102
- if (values.length > 1) {
1103
- this.debugSection('GrabValue', `Using first element out of ${values.length}`);
1104
- }
1105
-
1106
- return values[0];
1107
- }
1108
-
1109
- /**
1110
- * Grab array of CSS properties for given locator
1111
- * Resumes test execution, so **should be used inside an async function with `await`** operator.
1112
- *
1113
- * ```js
1114
- * const values = await I.grabCssPropertyFromAll('h3', 'font-weight');
1115
- * ```
1116
- *
1117
- * @param {CodeceptJS.LocatorOrString} locator element located by CSS|XPath|strict locator.
1118
- * @param {string} cssProperty CSS property name.
1119
- * @returns {Promise<string[]>} CSS value
1120
- *
1121
- */
1122
- async grabCssPropertyFromAll(locator, cssProperty) {
1123
- const els = await this._locate(locator, true);
1124
- const values = await Promise.all(els.map(el => el.getCssValue(cssProperty)));
1125
-
1126
- return values;
1127
- }
1128
-
1129
- /**
1130
- * Grab CSS property for given locator
1131
- * Resumes test execution, so **should be used inside an async function with `await`** operator.
1132
- * If more than one element is found - value of first element is returned.
1133
- *
1134
- * ```js
1135
- * const value = await I.grabCssPropertyFrom('h3', 'font-weight');
1136
- * ```
1137
- *
1138
- * @param {CodeceptJS.LocatorOrString} locator element located by CSS|XPath|strict locator.
1139
- * @param {string} cssProperty CSS property name.
1140
- * @returns {Promise<string>} CSS value
1141
- *
1142
- */
1143
- async grabCssPropertyFrom(locator, cssProperty) {
1144
- const cssValues = await this.grabCssPropertyFromAll(locator, cssProperty);
1145
- assertElementExists(cssValues, locator);
1146
-
1147
- if (cssValues.length > 1) {
1148
- this.debugSection('GrabCSS', `Using first element out of ${cssValues.length}`);
1149
- }
1150
-
1151
- return cssValues[0];
1152
- }
1153
-
1154
- /**
1155
- * Retrieves an array of attributes from elements located by CSS or XPath and returns it to test.
1156
- * Resumes test execution, so **should be used inside async with `await`** operator.
1157
- *
1158
- * ```js
1159
- * let hints = await I.grabAttributeFromAll('.tooltip', 'title');
1160
- * ```
1161
- * @param {CodeceptJS.LocatorOrString} locator element located by CSS|XPath|strict locator.
1162
- * @param {string} attr attribute name.
1163
- * @returns {Promise<string[]>} attribute value
1164
- *
1165
- */
1166
- async grabAttributeFromAll(locator, attr) {
1167
- const els = await this._locate(locator);
1168
- const array = [];
1169
-
1170
- for (let index = 0; index < els.length; index++) {
1171
- const el = els[index];
1172
- array.push(await el.getAttribute(attr));
1173
- }
1174
- return array;
1175
- }
1176
-
1177
- /**
1178
- * Retrieves an attribute from an element located by CSS or XPath and returns it to test.
1179
- * Resumes test execution, so **should be used inside async with `await`** operator.
1180
- * If more than one element is found - attribute of first element is returned.
1181
- *
1182
- * ```js
1183
- * let hint = await I.grabAttributeFrom('#tooltip', 'title');
1184
- * ```
1185
- * @param {CodeceptJS.LocatorOrString} locator element located by CSS|XPath|strict locator.
1186
- * @param {string} attr attribute name.
1187
- * @returns {Promise<string>} attribute value
1188
- *
1189
- */
1190
- async grabAttributeFrom(locator, attr) {
1191
- const attrs = await this.grabAttributeFromAll(locator, attr);
1192
- assertElementExists(attrs, locator);
1193
- if (attrs.length > 1) {
1194
- this.debugSection('GrabAttribute', `Using first element out of ${attrs.length}`);
1195
- }
1196
-
1197
- return attrs[0];
1198
- }
1199
-
1200
- /**
1201
- * Checks that title contains text.
1202
- *
1203
- * ```js
1204
- * I.seeInTitle('Home Page');
1205
- * ```
1206
- *
1207
- * @param {string} text text value to check.
1208
- * ⚠️ returns a _promise_ which is synchronized internally by recorder
1209
- *
1210
- */
1211
- async seeInTitle(text) {
1212
- return this.browser.getTitle().then(title => stringIncludes('web page title').assert(text, title));
1213
- }
1214
-
1215
- /**
1216
- * Checks that title is equal to provided one.
1217
- *
1218
- * ```js
1219
- * I.seeTitleEquals('Test title.');
1220
- * ```
1221
- *
1222
- * @param {string} text value to check.
1223
- * ⚠️ returns a _promise_ which is synchronized internally by recorder
1224
- *
1225
- */
1226
- async seeTitleEquals(text) {
1227
- const title = await this.browser.getTitle();
1228
- return equals('web page title').assert(title, text);
1229
- }
1230
-
1231
- /**
1232
- * Checks that title does not contain text.
1233
- *
1234
- * ```js
1235
- * I.dontSeeInTitle('Error');
1236
- * ```
1237
- *
1238
- * @param {string} text value to check.
1239
- * ⚠️ returns a _promise_ which is synchronized internally by recorder
1240
- *
1241
- */
1242
- async dontSeeInTitle(text) {
1243
- return this.browser.getTitle().then(title => stringIncludes('web page title').negate(text, title));
1244
- }
1245
-
1246
- /**
1247
- * Retrieves a page title and returns it to test.
1248
- * Resumes test execution, so **should be used inside async with `await`** operator.
1249
- *
1250
- * ```js
1251
- * let title = await I.grabTitle();
1252
- * ```
1253
- *
1254
- * @returns {Promise<string>} title
1255
- */
1256
- async grabTitle() {
1257
- return this.browser.getTitle().then((title) => {
1258
- this.debugSection('Title', title);
1259
- return title;
1260
- });
1261
- }
1262
-
1263
- /**
1264
- * Checks that a given Element is visible
1265
- * Element is located by CSS or XPath.
1266
- *
1267
- * ```js
1268
- * I.seeElement('#modal');
1269
- * ```
1270
- * @param {CodeceptJS.LocatorOrString} locator located by CSS|XPath|strict locator.
1271
- * ⚠️ returns a _promise_ which is synchronized internally by recorder
1272
- *
1273
- */
1274
- async seeElement(locator) {
1275
- let els = await this._locate(locator, true);
1276
- els = await Promise.all(els.map(el => el.isDisplayed()));
1277
- return empty('elements').negate(els.filter(v => v).fill('ELEMENT'));
1278
- }
1279
-
1280
- /**
1281
- * Opposite to `seeElement`. Checks that element is not visible (or in DOM)
1282
- *
1283
- * ```js
1284
- * I.dontSeeElement('.modal'); // modal is not shown
1285
- * ```
1286
- *
1287
- * @param {CodeceptJS.LocatorOrString} locator located by CSS|XPath|Strict locator.
1288
- * ⚠️ returns a _promise_ which is synchronized internally by recorder
1289
- *
1290
- */
1291
- async dontSeeElement(locator) {
1292
- let els = await this._locate(locator, false);
1293
- els = await Promise.all(els.map(el => el.isDisplayed()));
1294
- return empty('elements').assert(els.filter(v => v).fill('ELEMENT'));
1295
- }
1296
-
1297
- /**
1298
- * Checks that a given Element is present in the DOM
1299
- * Element is located by CSS or XPath.
1300
- *
1301
- * ```js
1302
- * I.seeElementInDOM('#modal');
1303
- * ```
1304
- * @param {CodeceptJS.LocatorOrString} locator element located by CSS|XPath|strict locator.
1305
- * ⚠️ returns a _promise_ which is synchronized internally by recorder
1306
- *
1307
- */
1308
- async seeElementInDOM(locator) {
1309
- return this.browser.findElements(guessLocator(locator) || global.by.css(locator)).then(els => empty('elements').negate(els.fill('ELEMENT')));
1310
- }
1311
-
1312
- /**
1313
- * Opposite to `seeElementInDOM`. Checks that element is not on page.
1314
- *
1315
- * ```js
1316
- * I.dontSeeElementInDOM('.nav'); // checks that element is not on page visible or not
1317
- * ```
1318
- *
1319
- * @param {CodeceptJS.LocatorOrString} locator located by CSS|XPath|Strict locator.
1320
- * ⚠️ returns a _promise_ which is synchronized internally by recorder
1321
- *
1322
- */
1323
- async dontSeeElementInDOM(locator) {
1324
- return this.browser.findElements(guessLocator(locator) || global.by.css(locator)).then(els => empty('elements').assert(els.fill('ELEMENT')));
1325
- }
1326
-
1327
- /**
1328
- * Checks that the current page contains the given string in its raw source code.
1329
- *
1330
- * ```js
1331
- * I.seeInSource('<h1>Green eggs &amp; ham</h1>');
1332
- * ```
1333
- * @param {string} text value to check.
1334
- * ⚠️ returns a _promise_ which is synchronized internally by recorder
1335
- *
1336
- */
1337
- async seeInSource(text) {
1338
- return this.browser.getPageSource().then(source => stringIncludes('HTML source of a page').assert(text, source));
1339
- }
1340
-
1341
- /**
1342
- * Retrieves page source and returns it to test.
1343
- * Resumes test execution, so **should be used inside async function with `await`** operator.
1344
- *
1345
- * ```js
1346
- * let pageSource = await I.grabSource();
1347
- * ```
1348
- *
1349
- * @returns {Promise<string>} source code
1350
- */
1351
- async grabSource() {
1352
- return this.browser.getPageSource();
1353
- }
1354
-
1355
- /**
1356
- * Checks that the current page does not contains the given string in its raw source code.
1357
- *
1358
- * ```js
1359
- * I.dontSeeInSource('<!--'); // no comments in source
1360
- * ```
1361
- *
1362
- * @param {string} value to check.
1363
- * ⚠️ returns a _promise_ which is synchronized internally by recorder
1364
- *
1365
- */
1366
- async dontSeeInSource(text) {
1367
- return this.browser.getPageSource().then(source => stringIncludes('HTML source of a page').negate(text, source));
1368
- }
1369
-
1370
- /**
1371
- * Asserts that an element appears a given number of times in the DOM.
1372
- * Element is located by label or name or CSS or XPath.
1373
- *
1374
- *
1375
- * ```js
1376
- * I.seeNumberOfElements('#submitBtn', 1);
1377
- * ```
1378
- *
1379
- * @param {CodeceptJS.LocatorOrString} locator element located by CSS|XPath|strict locator.
1380
- * @param {number} num number of elements.
1381
- * ⚠️ returns a _promise_ which is synchronized internally by recorder
1382
- *
1383
- */
1384
- async seeNumberOfElements(locator, num) {
1385
- const elements = await this._locate(locator);
1386
- return equals(`expected number of elements (${(new Locator(locator))}) is ${num}, but found ${elements.length}`).assert(elements.length, num);
1387
- }
1388
-
1389
- /**
1390
- * Asserts that an element is visible a given number of times.
1391
- * Element is located by CSS or XPath.
1392
- *
1393
- * ```js
1394
- * I.seeNumberOfVisibleElements('.buttons', 3);
1395
- * ```
1396
- *
1397
- * @param {CodeceptJS.LocatorOrString} locator element located by CSS|XPath|strict locator.
1398
- * @param {number} num number of elements.
1399
- * ⚠️ returns a _promise_ which is synchronized internally by recorder
1400
- *
1401
- */
1402
- async seeNumberOfVisibleElements(locator, num) {
1403
- const res = await this.grabNumberOfVisibleElements(locator);
1404
- return equals(`expected number of visible elements (${(new Locator(locator))}) is ${num}, but found ${res}`).assert(res, num);
1405
- }
1406
-
1407
- /**
1408
- * Grab number of visible elements by locator.
1409
- * Resumes test execution, so **should be used inside async function with `await`** operator.
1410
- *
1411
- * ```js
1412
- * let numOfElements = await I.grabNumberOfVisibleElements('p');
1413
- * ```
1414
- *
1415
- * @param {CodeceptJS.LocatorOrString} locator located by CSS|XPath|strict locator.
1416
- * @returns {Promise<number>} number of visible elements
1417
- */
1418
- async grabNumberOfVisibleElements(locator) {
1419
- let els = await this._locate(locator);
1420
- els = await Promise.all(els.map(el => el.isDisplayed()));
1421
- return els.length;
1422
- }
1423
-
1424
- /**
1425
- * Checks that all elements with given locator have given CSS properties.
1426
- *
1427
- * ```js
1428
- * I.seeCssPropertiesOnElements('h3', { 'font-weight': "bold"});
1429
- * ```
1430
- *
1431
- * @param {CodeceptJS.LocatorOrString} locator located by CSS|XPath|strict locator.
1432
- * @param {object} cssProperties object with CSS properties and their values to check.
1433
- * ⚠️ returns a _promise_ which is synchronized internally by recorder
1434
- *
1435
- */
1436
- async seeCssPropertiesOnElements(locator, cssProperties) {
1437
- const els = await this._locate(locator);
1438
- assertElementExists(els, locator);
1439
-
1440
- const cssPropertiesCamelCase = convertCssPropertiesToCamelCase(cssProperties);
1441
-
1442
- const attributeNames = Object.keys(cssPropertiesCamelCase);
1443
- const expectedValues = attributeNames.map(name => cssPropertiesCamelCase[name]);
1444
- const missingAttributes = [];
1445
-
1446
- for (const el of els) {
1447
- const attributeValues = await Promise.all(attributeNames.map(attr => el.getCssValue(attr)));
1448
-
1449
- const missing = attributeValues.filter((actual, i) => {
1450
- const prop = attributeNames[i];
1451
- let propValue = actual;
1452
- if (isColorProperty(prop) && propValue) {
1453
- propValue = convertColorToRGBA(propValue);
1454
- }
1455
- return propValue !== expectedValues[i];
1456
- });
1457
- if (missing.length) {
1458
- missingAttributes.push(...missing);
1459
- }
1460
- }
1461
- return equals(`all elements (${(new Locator(locator))}) to have CSS property ${JSON.stringify(cssProperties)}`).assert(missingAttributes.length, 0);
1462
- }
1463
-
1464
- /**
1465
- * Checks that all elements with given locator have given attributes.
1466
- *
1467
- * ```js
1468
- * I.seeAttributesOnElements('//form', { method: "post"});
1469
- * ```
1470
- *
1471
- * @param {CodeceptJS.LocatorOrString} locator located by CSS|XPath|strict locator.
1472
- * @param {object} attributes attributes and their values to check.
1473
- * ⚠️ returns a _promise_ which is synchronized internally by recorder
1474
- *
1475
- */
1476
- async seeAttributesOnElements(locator, attributes) {
1477
- const els = await this._locate(locator);
1478
- assertElementExists(els, locator);
1479
-
1480
- const attributeNames = Object.keys(attributes);
1481
- const expectedValues = attributeNames.map(name => attributes[name]);
1482
- const missingAttributes = [];
1483
-
1484
- for (const el of els) {
1485
- const attributeValues = await Promise.all(attributeNames.map(attr => el.getAttribute(attr)));
1486
- const missing = attributeValues.filter((actual, i) => {
1487
- if (expectedValues[i] instanceof RegExp) {
1488
- return expectedValues[i].test(actual);
1489
- }
1490
- return actual !== expectedValues[i];
1491
- });
1492
- if (missing.length) {
1493
- missingAttributes.push(...missing);
1494
- }
1495
- }
1496
-
1497
- return equals(`all elements (${(new Locator(locator))}) to have attributes ${JSON.stringify(attributes)}`).assert(missingAttributes.length, 0);
1498
- }
1499
-
1500
- /**
1501
- * Executes sync script on a page.
1502
- * Pass arguments to function as additional parameters.
1503
- * Will return execution result to a test.
1504
- * In this case you should use async function and await to receive results.
1505
- *
1506
- * Example with jQuery DatePicker:
1507
- *
1508
- * ```js
1509
- * // change date of jQuery DatePicker
1510
- * I.executeScript(function() {
1511
- * // now we are inside browser context
1512
- * $('date').datetimepicker('setDate', new Date());
1513
- * });
1514
- * ```
1515
- * Can return values. Don't forget to use `await` to get them.
1516
- *
1517
- * ```js
1518
- * let date = await I.executeScript(function(el) {
1519
- * // only basic types can be returned
1520
- * return $(el).datetimepicker('getDate').toString();
1521
- * }, '#date'); // passing jquery selector
1522
- * ```
1523
- *
1524
- * @param {string|function} fn function to be executed in browser context.
1525
- * @param {...any} args to be passed to function.
1526
- * ⚠️ returns a _promise_ which is synchronized internally by recorder
1527
- *
1528
- */
1529
- async executeScript() {
1530
- return this.browser.executeScript.apply(this.browser, arguments);
1531
- }
1532
-
1533
- /**
1534
- * Executes async script on page.
1535
- * Provided function should execute a passed callback (as first argument) to signal it is finished.
1536
- *
1537
- * Example: In Vue.js to make components completely rendered we are waiting for [nextTick](https://vuejs.org/v2/api/#Vue-nextTick).
1538
- *
1539
- * ```js
1540
- * I.executeAsyncScript(function(done) {
1541
- * Vue.nextTick(done); // waiting for next tick
1542
- * });
1543
- * ```
1544
- *
1545
- * By passing value to `done()` function you can return values.
1546
- * Additional arguments can be passed as well, while `done` function is always last parameter in arguments list.
1547
- *
1548
- * ```js
1549
- * let val = await I.executeAsyncScript(function(url, done) {
1550
- * // in browser context
1551
- * $.ajax(url, { success: (data) => done(data); }
1552
- * }, 'http://ajax.callback.url/');
1553
- * ```
1554
- *
1555
- * @param {string|function} fn function to be executed in browser context.
1556
- * @param {...any} args to be passed to function.
1557
- * ⚠️ returns a _promise_ which is synchronized internally by recorder
1558
- *
1559
- */
1560
- async executeAsyncScript() {
1561
- this.browser.manage().timeouts().setScriptTimeout(this.options.scriptTimeout);
1562
- return this.browser.executeAsyncScript.apply(this.browser, arguments);
1563
- }
1564
-
1565
- /**
1566
- * Checks that current url contains a provided fragment.
1567
- *
1568
- * ```js
1569
- * I.seeInCurrentUrl('/register'); // we are on registration page
1570
- * ```
1571
- *
1572
- * @param {string} url a fragment to check
1573
- * ⚠️ returns a _promise_ which is synchronized internally by recorder
1574
- *
1575
- */
1576
- async seeInCurrentUrl(url) {
1577
- return this.browser.getCurrentUrl().then(currentUrl => stringIncludes('url').assert(url, currentUrl));
1578
- }
1579
-
1580
- /**
1581
- * Checks that current url does not contain a provided fragment.
1582
- *
1583
- * @param {string} url value to check.
1584
- * ⚠️ returns a _promise_ which is synchronized internally by recorder
1585
- *
1586
- */
1587
- async dontSeeInCurrentUrl(url) {
1588
- return this.browser.getCurrentUrl().then(currentUrl => stringIncludes('url').negate(url, currentUrl));
1589
- }
1590
-
1591
- /**
1592
- * Checks that current url is equal to provided one.
1593
- * If a relative url provided, a configured url will be prepended to it.
1594
- * So both examples will work:
1595
- *
1596
- * ```js
1597
- * I.seeCurrentUrlEquals('/register');
1598
- * I.seeCurrentUrlEquals('http://my.site.com/register');
1599
- * ```
1600
- *
1601
- * @param {string} url value to check.
1602
- * ⚠️ returns a _promise_ which is synchronized internally by recorder
1603
- *
1604
- */
1605
- async seeCurrentUrlEquals(url) {
1606
- return this.browser.getCurrentUrl().then(currentUrl => urlEquals(this.options.url).assert(url, currentUrl));
1607
- }
1608
-
1609
- /**
1610
- * Checks that current url is not equal to provided one.
1611
- * If a relative url provided, a configured url will be prepended to it.
1612
- *
1613
- * ```js
1614
- * I.dontSeeCurrentUrlEquals('/login'); // relative url are ok
1615
- * I.dontSeeCurrentUrlEquals('http://mysite.com/login'); // absolute urls are also ok
1616
- * ```
1617
- *
1618
- * @param {string} url value to check.
1619
- * ⚠️ returns a _promise_ which is synchronized internally by recorder
1620
- *
1621
- */
1622
- async dontSeeCurrentUrlEquals(url) {
1623
- return this.browser.getCurrentUrl().then(currentUrl => urlEquals(this.options.url).negate(url, currentUrl));
1624
- }
1625
-
1626
- /**
1627
- * Saves screenshot of the specified locator to ouput folder (set in codecept.conf.ts or codecept.conf.js).
1628
- * Filename is relative to output folder.
1629
- *
1630
- * ```js
1631
- * I.saveElementScreenshot(`#submit`,'debug.png');
1632
- * ```
1633
- *
1634
- * @param {CodeceptJS.LocatorOrString} locator element located by CSS|XPath|strict locator.
1635
- * @param {string} fileName file name to save.
1636
- * ⚠️ returns a _promise_ which is synchronized internally by recorder
1637
- *
1638
- *
1639
- */
1640
- async saveElementScreenshot(locator, fileName) {
1641
- const outputFile = screenshotOutputFolder(fileName);
1642
-
1643
- const writeFile = (png, outputFile) => {
1644
- const fs = require('fs');
1645
- const stream = fs.createWriteStream(outputFile);
1646
- stream.write(Buffer.from(png, 'base64'));
1647
- stream.end();
1648
- return new Promise(resolve => stream.on('finish', resolve));
1649
- };
1650
-
1651
- const res = await this._locate(locator);
1652
- assertElementExists(res, locator);
1653
- if (res.length > 1) this.debug(`[Elements] Using first element out of ${res.length}`);
1654
- const elem = res[0];
1655
- this.debug(`Screenshot of ${(new Locator(locator))} element has been saved to ${outputFile}`);
1656
- const png = await elem.takeScreenshot();
1657
- return writeFile(png, outputFile);
1658
- }
1659
-
1660
- /**
1661
- * Saves a screenshot to ouput folder (set in codecept.conf.ts or codecept.conf.js).
1662
- * Filename is relative to output folder.
1663
- * 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.
1664
- *
1665
- * ```js
1666
- * I.saveScreenshot('debug.png');
1667
- * I.saveScreenshot('debug.png', true) //resizes to available scrollHeight and scrollWidth before taking screenshot
1668
- * ```
1669
- *
1670
- * @param {string} fileName file name to save.
1671
- * @param {boolean} [fullPage=false] (optional, `false` by default) flag to enable fullscreen screenshot mode.
1672
- * ⚠️ returns a _promise_ which is synchronized internally by recorder
1673
- *
1674
- */
1675
- async saveScreenshot(fileName, fullPage = false) {
1676
- const outputFile = screenshotOutputFolder(fileName);
1677
-
1678
- const writeFile = (png, outputFile) => {
1679
- const fs = require('fs');
1680
- const stream = fs.createWriteStream(outputFile);
1681
- stream.write(Buffer.from(png, 'base64'));
1682
- stream.end();
1683
- return new Promise(resolve => stream.on('finish', resolve));
1684
- };
1685
-
1686
- if (!fullPage) {
1687
- this.debug(`Screenshot has been saved to ${outputFile}`);
1688
- const png = await this.browser.takeScreenshot();
1689
- return writeFile(png, outputFile);
1690
- }
1691
-
1692
- let { width, height } = await this.browser.executeScript(() => ({ // eslint-disable-line
1693
- height: document.body.scrollHeight,
1694
- width: document.body.scrollWidth,
1695
- }));
1696
-
1697
- if (height < 100) height = 500;
1698
-
1699
- await this.browser.manage().window().setSize(width, height);
1700
- this.debug(`Screenshot has been saved to ${outputFile}, size: ${width}x${height}`);
1701
- const png = await this.browser.takeScreenshot();
1702
- return writeFile(png, outputFile);
1703
- }
1704
-
1705
- /**
1706
- * Clears a cookie by name,
1707
- * if none provided clears all cookies.
1708
- *
1709
- * ```js
1710
- * I.clearCookie();
1711
- * I.clearCookie('test');
1712
- * ```
1713
- *
1714
- * @param {?string} [cookie=null] (optional, `null` by default) cookie name
1715
- * ⚠️ returns a _promise_ which is synchronized internally by recorder
1716
- *
1717
- */
1718
- async clearCookie(cookie = null) {
1719
- if (!cookie) {
1720
- return this.browser.manage().deleteAllCookies();
1721
- }
1722
- return this.browser.manage().deleteCookie(cookie);
1723
- }
1724
-
1725
- /**
1726
- * Checks that cookie with given name exists.
1727
- *
1728
- * ```js
1729
- * I.seeCookie('Auth');
1730
- * ```
1731
- *
1732
- * @param {string} name cookie name.
1733
- * ⚠️ returns a _promise_ which is synchronized internally by recorder
1734
- *
1735
- */
1736
- async seeCookie(name) {
1737
- return this.browser.manage().getCookie(name).then(res => truth(`cookie ${name}`, 'to be set').assert(res));
1738
- }
1739
-
1740
- /**
1741
- * Checks that cookie with given name does not exist.
1742
- *
1743
- * ```js
1744
- * I.dontSeeCookie('auth'); // no auth cookie
1745
- * ```
1746
- *
1747
- * @param {string} name cookie name.
1748
- * ⚠️ returns a _promise_ which is synchronized internally by recorder
1749
- *
1750
- */
1751
- async dontSeeCookie(name) {
1752
- return this.browser.manage().getCookie(name).then(res => truth(`cookie ${name}`, 'to be set').negate(res));
1753
- }
1754
-
1755
- /**
1756
- * Gets a cookie object by name.
1757
- * If none provided gets all cookies.
1758
- * Resumes test execution, so **should be used inside async function with `await`** operator.
1759
- *
1760
- * ```js
1761
- * let cookie = await I.grabCookie('auth');
1762
- * assert(cookie.value, '123456');
1763
- * ```
1764
- *
1765
- * @param {?string} [name=null] cookie name.
1766
- * @returns {Promise<string>|Promise<string[]>} attribute value
1767
- *
1768
- *
1769
- * Returns cookie in JSON [format](https://code.google.com/p/selenium/wiki/JsonWireProtocol#Cookie_JSON_Object).
1770
- */
1771
- async grabCookie(name) {
1772
- if (!name) return this.browser.manage().getCookies();
1773
- return this.browser.manage().getCookie(name);
1774
- }
1775
-
1776
- /**
1777
- * Accepts the active JavaScript native popup window, as created by window.alert|window.confirm|window.prompt.
1778
- * Don't confuse popups with modal windows, as created by [various
1779
- * libraries](http://jster.net/category/windows-modals-popups). Appium: support only web testing
1780
- */
1781
- async acceptPopup() {
1782
- return this.browser.switchTo().alert().accept();
1783
- }
1784
-
1785
- /**
1786
- * Dismisses the active JavaScript popup, as created by window.alert|window.confirm|window.prompt.
1787
- */
1788
- async cancelPopup() {
1789
- return this.browser.switchTo().alert().dismiss();
1790
- }
1791
-
1792
- /**
1793
- * Checks that the active JavaScript popup, as created by `window.alert|window.confirm|window.prompt`, contains the
1794
- * given string.
1795
- *
1796
- * ```js
1797
- * I.seeInPopup('Popup text');
1798
- * ```
1799
- * @param {string} text value to check.
1800
- * ⚠️ returns a _promise_ which is synchronized internally by recorder
1801
- *
1802
- */
1803
- async seeInPopup(text) {
1804
- const popupAlert = await this.browser.switchTo().alert();
1805
- const res = await popupAlert.getText();
1806
- if (res === null) {
1807
- throw new Error('Popup is not opened');
1808
- }
1809
- stringIncludes('text in popup').assert(text, res);
1810
- }
1811
-
1812
- /**
1813
- * Grab the text within the popup. If no popup is visible then it will return null
1814
- *
1815
- * ```js
1816
- * await I.grabPopupText();
1817
- * ```
1818
- */
1819
- async grabPopupText() {
1820
- try {
1821
- const dialog = await this.browser.switchTo().alert();
1822
-
1823
- if (dialog) {
1824
- return dialog.getText();
1825
- }
1826
- } catch (e) {
1827
- if (e.message.match(/no.*?(alert|modal)/i)) {
1828
- // Don't throw an error
1829
- return null;
1830
- }
1831
- throw e;
1832
- }
1833
- }
1834
-
1835
- /**
1836
- * Resize the current window to provided width and height.
1837
- * First parameter can be set to `maximize`.
1838
- *
1839
- * @param {number} width width in pixels or `maximize`.
1840
- * @param {number} height height in pixels.
1841
- * ⚠️ returns a _promise_ which is synchronized internally by recorder
1842
- *
1843
- */
1844
- async resizeWindow(width, height) {
1845
- if (width === 'maximize') {
1846
- const res = await this.browser.executeScript('return [screen.width, screen.height]');
1847
- return this.browser.manage().window().setSize(parseInt(res[0], 10), parseInt(res[1], 10));
1848
- }
1849
- return this.browser.manage().window().setSize(parseInt(width, 10), parseInt(height, 10));
1850
- }
1851
-
1852
- /**
1853
- * Drag an item to a destination element.
1854
- *
1855
- * ```js
1856
- * I.dragAndDrop('#dragHandle', '#container');
1857
- * ```
1858
- *
1859
- * @param {LocatorOrString} srcElement located by CSS|XPath|strict locator.
1860
- * @param {LocatorOrString} destElement located by CSS|XPath|strict locator.
1861
- * ⚠️ returns a _promise_ which is synchronized internally by recorder
1862
- *
1863
- */
1864
- async dragAndDrop(srcElement, destElement) {
1865
- const srcEl = await this._locate(srcElement, true);
1866
- const destEl = await this._locate(destElement, true);
1867
- assertElementExists(srcEl, srcElement);
1868
- assertElementExists(destEl, destElement);
1869
- return this.browser
1870
- .actions()
1871
- .dragAndDrop(srcEl[0], destEl[0])
1872
- .perform();
1873
- }
1874
-
1875
- /**
1876
- * Close all tabs except for the current one.
1877
- *
1878
- * ```js
1879
- * I.closeOtherTabs();
1880
- * ```
1881
- */
1882
- async closeOtherTabs() {
1883
- const client = this.browser;
1884
-
1885
- const handles = await client.getAllWindowHandles();
1886
- const currentHandle = await client.getWindowHandle();
1887
- const otherHandles = handles.filter(handle => handle !== currentHandle);
1888
-
1889
- if (!otherHandles || !otherHandles.length) return;
1890
- let p = Promise.resolve();
1891
- otherHandles.forEach((handle) => {
1892
- p = p.then(() => client.switchTo().window(handle).then(() => client.close()));
1893
- });
1894
- p = p.then(() => client.switchTo().window(currentHandle));
1895
- return p;
1896
- }
1897
-
1898
- /**
1899
- * Close current tab
1900
- *
1901
- * ```js
1902
- * I.closeCurrentTab();
1903
- * ```
1904
- */
1905
- async closeCurrentTab() {
1906
- const client = this.browser;
1907
-
1908
- const currentHandle = await client.getWindowHandle();
1909
- const nextHandle = await this._getWindowHandle(-1);
1910
-
1911
- await client.switchTo().window(currentHandle);
1912
- await client.close();
1913
- return client.switchTo().window(nextHandle);
1914
- }
1915
-
1916
- /**
1917
- * Get the window handle relative to the current handle. i.e. the next handle or the previous.
1918
- * @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.
1919
- */
1920
- async _getWindowHandle(offset = 0) {
1921
- const client = this.browser;
1922
- const handles = await client.getAllWindowHandles();
1923
- const index = handles.indexOf(await client.getWindowHandle());
1924
- const nextIndex = index + offset;
1925
-
1926
- return handles[nextIndex];
1927
- // return handles[(index + offset) % handles.length];
1928
- }
1929
-
1930
- /**
1931
- * Open new tab and switch to it
1932
- *
1933
- * ```js
1934
- * I.openNewTab();
1935
- * ```
1936
- */
1937
- async openNewTab() {
1938
- const client = this.browser;
1939
- await this.executeScript('window.open("about:blank")');
1940
- const handles = await client.getAllWindowHandles();
1941
- await client.switchTo().window(handles[handles.length - 1]);
1942
- }
1943
-
1944
- /**
1945
- * Switch focus to a particular tab by its number. It waits tabs loading and then switch tab
1946
- *
1947
- * ```js
1948
- * I.switchToNextTab();
1949
- * I.switchToNextTab(2);
1950
- * ```
1951
- */
1952
- async switchToNextTab(num = 1) {
1953
- const client = this.browser;
1954
- const newHandle = await this._getWindowHandle(num);
1955
-
1956
- if (!newHandle) {
1957
- throw new Error(`There is no ability to switch to next tab with offset ${num}`);
1958
- }
1959
- return client.switchTo().window(newHandle);
1960
- }
1961
-
1962
- /**
1963
- * Switch focus to a particular tab by its number. It waits tabs loading and then switch tab
1964
- *
1965
- * ```js
1966
- * I.switchToPreviousTab();
1967
- * I.switchToPreviousTab(2);
1968
- * ```
1969
- */
1970
- async switchToPreviousTab(num = 1) {
1971
- const client = this.browser;
1972
- const newHandle = await this._getWindowHandle(-1 * num);
1973
-
1974
- if (!newHandle) {
1975
- throw new Error(`There is no ability to switch to previous tab with offset ${num}`);
1976
- }
1977
- return client.switchTo().window(newHandle);
1978
- }
1979
-
1980
- /**
1981
- * Grab number of open tabs.
1982
- * Resumes test execution, so **should be used inside async function with `await`** operator.
1983
- *
1984
- * ```js
1985
- * let tabs = await I.grabNumberOfOpenTabs();
1986
- * ```
1987
- *
1988
- * @returns {Promise<number>} number of open tabs
1989
- *
1990
- */
1991
- async grabNumberOfOpenTabs() {
1992
- const pages = await this.browser.getAllWindowHandles();
1993
- return pages.length;
1994
- }
1995
-
1996
- /**
1997
- * Switches frame or in case of null locator reverts to parent.
1998
- *
1999
- * ```js
2000
- * I.switchTo('iframe'); // switch to first iframe
2001
- * I.switchTo(); // switch back to main page
2002
- * ```
2003
- *
2004
- * @param {?CodeceptJS.LocatorOrString} [locator=null] (optional, `null` by default) element located by CSS|XPath|strict locator.
2005
- * ⚠️ returns a _promise_ which is synchronized internally by recorder
2006
- *
2007
- */
2008
- async switchTo(locator) {
2009
- if (Number.isInteger(locator)) {
2010
- return this.browser.switchTo().frame(locator);
2011
- }
2012
- if (!locator) {
2013
- return this.browser.switchTo().frame(null);
2014
- }
2015
-
2016
- const els = await this._locate(withStrictLocator.call(this, locator), true);
2017
- assertElementExists(els, locator);
2018
- return this.browser.switchTo().frame(els[0]);
2019
- }
2020
-
2021
- /**
2022
- * Pauses execution for a number of seconds.
2023
- *
2024
- * ```js
2025
- * I.wait(2); // wait 2 secs
2026
- * ```
2027
- *
2028
- * @param {number} sec number of second to wait.
2029
- * ⚠️ returns a _promise_ which is synchronized internally by recorder
2030
- *
2031
- */
2032
- wait(sec) {
2033
- return this.browser.sleep(sec * 1000);
2034
- }
2035
-
2036
- /**
2037
- * Waits for element to be present on page (by default waits for 1sec).
2038
- * Element can be located by CSS or XPath.
2039
- *
2040
- * ```js
2041
- * I.waitForElement('.btn.continue');
2042
- * I.waitForElement('.btn.continue', 5); // wait for 5 secs
2043
- * ```
2044
- *
2045
- * @param {CodeceptJS.LocatorOrString} locator element located by CSS|XPath|strict locator.
2046
- * @param {number} [sec] (optional, `1` by default) time in seconds to wait
2047
- * ⚠️ returns a _promise_ which is synchronized internally by recorder
2048
- *
2049
- */
2050
- async waitForElement(locator, sec = null) {
2051
- const aSec = sec || this.options.waitForTimeoutInSeconds;
2052
- const el = global.element(guessLocator(locator) || global.by.css(locator));
2053
- return this.browser.wait(EC.presenceOf(el), aSec * 1000);
2054
- }
2055
-
2056
- async waitUntilExists(locator, sec = null) {
2057
- console.log(`waitUntilExists deprecated:
2058
- * use 'waitForElement' to wait for element to be attached
2059
- * use 'waitForDetached to wait for element to be removed'`);
2060
- return this.waitForDetached(locator, sec);
2061
- }
2062
-
2063
- /**
2064
- * Waits for an element to become not attached to the DOM on a page (by default waits for 1sec).
2065
- * Element can be located by CSS or XPath.
2066
- *
2067
- * ```js
2068
- * I.waitForDetached('#popup');
2069
- * ```
2070
- *
2071
- * @param {CodeceptJS.LocatorOrString} locator element located by CSS|XPath|strict locator.
2072
- * @param {number} [sec=1] (optional, `1` by default) time in seconds to wait
2073
- * ⚠️ returns a _promise_ which is synchronized internally by recorder
2074
- *
2075
- */
2076
- async waitForDetached(locator, sec = null) {
2077
- const aSec = sec || this.options.waitForTimeoutInSeconds;
2078
- const el = global.element(guessLocator(locator) || global.by.css(locator));
2079
- return this.browser.wait(EC.not(EC.presenceOf(el)), aSec * 1000).catch((err) => {
2080
- if (err.message && err.message.indexOf('Wait timed out after') > -1) {
2081
- throw new Error(`element (${JSON.stringify(locator)}) still on page after ${sec} sec`);
2082
- } else throw err;
2083
- });
2084
- }
2085
-
2086
- /**
2087
- * Waits for element to become clickable for number of seconds.
2088
- *
2089
- * ```js
2090
- * I.waitForClickable('#link');
2091
- * ```
2092
- */
2093
- async waitForClickable(locator, sec = null) {
2094
- const aSec = sec || this.options.waitForTimeoutInSeconds;
2095
- const el = global.element(guessLocator(locator) || global.by.css(locator));
2096
- return this.browser.wait(EC.elementToBeClickable(el), aSec * 1000);
2097
- }
2098
-
2099
- /**
2100
- * Waits for an element to become visible on a page (by default waits for 1sec).
2101
- * Element can be located by CSS or XPath.
2102
- *
2103
- * ```js
2104
- * I.waitForVisible('#popup');
2105
- * ```
2106
- *
2107
- * @param {CodeceptJS.LocatorOrString} locator element located by CSS|XPath|strict locator.
2108
- * @param {number} [sec=1] (optional, `1` by default) time in seconds to wait
2109
- * ⚠️ returns a _promise_ which is synchronized internally by recorder
2110
- *
2111
- */
2112
- async waitForVisible(locator, sec = null) {
2113
- const aSec = sec || this.options.waitForTimeoutInSeconds;
2114
- const el = global.element(guessLocator(locator) || global.by.css(locator));
2115
- return this.browser.wait(EC.visibilityOf(el), aSec * 1000);
2116
- }
2117
-
2118
- /**
2119
- * Waits for an element to hide (by default waits for 1sec).
2120
- * Element can be located by CSS or XPath.
2121
- *
2122
- * ```js
2123
- * I.waitToHide('#popup');
2124
- * ```
2125
- *
2126
- * @param {CodeceptJS.LocatorOrString} locator element located by CSS|XPath|strict locator.
2127
- * @param {number} [sec=1] (optional, `1` by default) time in seconds to wait
2128
- * ⚠️ returns a _promise_ which is synchronized internally by recorder
2129
- *
2130
- */
2131
- async waitToHide(locator, sec = null) {
2132
- return this.waitForInvisible(locator, sec);
2133
- }
2134
-
2135
- /**
2136
- * Waits for an element to be removed or become invisible on a page (by default waits for 1sec).
2137
- * Element can be located by CSS or XPath.
2138
- *
2139
- * ```js
2140
- * I.waitForInvisible('#popup');
2141
- * ```
2142
- *
2143
- * @param {CodeceptJS.LocatorOrString} locator element located by CSS|XPath|strict locator.
2144
- * @param {number} [sec=1] (optional, `1` by default) time in seconds to wait
2145
- * ⚠️ returns a _promise_ which is synchronized internally by recorder
2146
- *
2147
- */
2148
- async waitForInvisible(locator, sec = null) {
2149
- const aSec = sec || this.options.waitForTimeoutInSeconds;
2150
- const el = global.element(guessLocator(locator) || global.by.css(locator));
2151
- return this.browser.wait(EC.invisibilityOf(el), aSec * 1000);
2152
- }
2153
-
2154
- async waitForStalenessOf(locator, sec = null) {
2155
- console.log(`waitForStalenessOf deprecated.
2156
- * Use waitForDetached to wait for element to be removed from page
2157
- * Use waitForInvisible to wait for element to be hidden on page`);
2158
- return this.waitForInvisible(locator, sec);
2159
- }
2160
-
2161
- /**
2162
- * Waits for a specified number of elements on the page.
2163
- *
2164
- * ```js
2165
- * I.waitNumberOfVisibleElements('a', 3);
2166
- * ```
2167
- *
2168
- * @param {CodeceptJS.LocatorOrString} locator element located by CSS|XPath|strict locator.
2169
- * @param {number} num number of elements.
2170
- * @param {number} [sec=1] (optional, `1` by default) time in seconds to wait
2171
- * ⚠️ returns a _promise_ which is synchronized internally by recorder
2172
- *
2173
- */
2174
- async waitNumberOfVisibleElements(locator, num, sec = null) {
2175
- function visibilityCountOf(loc, expectedCount) {
2176
- return function () {
2177
- return global.element.all(loc)
2178
- .filter(el => el.isDisplayed())
2179
- .count()
2180
- .then(count => count === expectedCount);
2181
- };
2182
- }
2183
-
2184
- const aSec = sec || this.options.waitForTimeoutInSeconds;
2185
- const guessLoc = guessLocator(locator) || global.by.css(locator);
2186
-
2187
- return this.browser.wait(visibilityCountOf(guessLoc, num), aSec * 1000)
2188
- .catch(() => {
2189
- throw Error(`The number of elements (${(new Locator(locator))}) is not ${num} after ${aSec} sec`);
2190
- });
2191
- }
2192
-
2193
- /**
2194
- * Waits for element to become enabled (by default waits for 1sec).
2195
- * Element can be located by CSS or XPath.
2196
- *
2197
- * @param {CodeceptJS.LocatorOrString} locator element located by CSS|XPath|strict locator.
2198
- * @param {number} [sec=1] (optional) time in seconds to wait, 1 by default.
2199
- * ⚠️ returns a _promise_ which is synchronized internally by recorder
2200
- *
2201
- */
2202
- async waitForEnabled(locator, sec = null) {
2203
- const aSec = sec || this.options.waitForTimeoutInSeconds;
2204
- const el = global.element(guessLocator(locator) || global.by.css(locator));
2205
-
2206
- return this.browser.wait(EC.elementToBeClickable(el), aSec * 1000)
2207
- .catch(() => {
2208
- throw Error(`element (${(new Locator(locator))}) still not enabled after ${aSec} sec`);
2209
- });
2210
- }
2211
-
2212
- /**
2213
- * Waits for the specified value to be in value attribute.
2214
- *
2215
- * ```js
2216
- * I.waitForValue('//input', "GoodValue");
2217
- * ```
2218
- *
2219
- * @param {LocatorOrString} field input field.
2220
- * @param {string }value expected value.
2221
- * @param {number} [sec=1] (optional, `1` by default) time in seconds to wait
2222
- * ⚠️ returns a _promise_ which is synchronized internally by recorder
2223
- *
2224
- */
2225
- async waitForValue(field, value, sec = null) {
2226
- const aSec = sec || this.options.waitForTimeoutInSeconds;
2227
-
2228
- const valueToBeInElementValue = (loc) => {
2229
- return async () => {
2230
- const els = await findFields(this.browser, loc);
2231
-
2232
- if (!els) {
2233
- return false;
2234
- }
2235
- const values = await Promise.all(els.map(el => el.getAttribute('value')));
2236
- return values.filter(part => part.indexOf(value) >= 0).length > 0;
2237
- };
2238
- };
2239
-
2240
- return this.browser.wait(valueToBeInElementValue(field, value), aSec * 1000)
2241
- .catch(() => {
2242
- throw Error(`element (${field}) is not in DOM or there is no element(${field}) with value "${value}" after ${aSec} sec`);
2243
- });
2244
- }
2245
-
2246
- /**
2247
- * Waits for a function to return true (waits for 1 sec by default).
2248
- * Running in browser context.
2249
- *
2250
- * ```js
2251
- * I.waitForFunction(fn[, [args[, timeout]])
2252
- * ```
2253
- *
2254
- * ```js
2255
- * I.waitForFunction(() => window.requests == 0);
2256
- * I.waitForFunction(() => window.requests == 0, 5); // waits for 5 sec
2257
- * I.waitForFunction((count) => window.requests == count, [3], 5) // pass args and wait for 5 sec
2258
- * ```
2259
- *
2260
- * @param {string|function} fn to be executed in browser context.
2261
- * @param {any[]|number} [argsOrSec] (optional, `1` by default) arguments for function or seconds.
2262
- * @param {number} [sec] (optional, `1` by default) time in seconds to wait
2263
- * ⚠️ returns a _promise_ which is synchronized internally by recorder
2264
- *
2265
- */
2266
- async waitForFunction(fn, argsOrSec = null, sec = null) {
2267
- let args = [];
2268
- if (argsOrSec) {
2269
- if (Array.isArray(argsOrSec)) {
2270
- args = argsOrSec;
2271
- } else if (typeof argsOrSec === 'number') {
2272
- sec = argsOrSec;
2273
- }
2274
- }
2275
-
2276
- const aSec = sec || this.options.waitForTimeoutInSeconds;
2277
- return this.browser.wait(() => this.browser.executeScript.call(this.browser, fn, ...args), aSec * 1000);
2278
- }
2279
-
2280
- /**
2281
- * Waiting for the part of the URL to match the expected. Useful for SPA to understand that page was changed.
2282
- *
2283
- * ```js
2284
- * I.waitInUrl('/info', 2);
2285
- * ```
2286
- *
2287
- * @param {string} urlPart value to check.
2288
- * @param {number} [sec=1] (optional, `1` by default) time in seconds to wait
2289
- * ⚠️ returns a _promise_ which is synchronized internally by recorder
2290
- *
2291
- */
2292
- async waitInUrl(urlPart, sec = null) {
2293
- const aSec = sec || this.options.waitForTimeoutInSeconds;
2294
- const waitTimeout = aSec * 1000;
2295
-
2296
- return this.browser.wait(EC.urlContains(urlPart), waitTimeout)
2297
- .catch(async (e) => {
2298
- const currUrl = await this.browser.getCurrentUrl();
2299
- if (/wait timed out after/i.test(e.message)) {
2300
- throw new Error(`expected url to include ${urlPart}, but found ${currUrl}`);
2301
- } else {
2302
- throw e;
2303
- }
2304
- });
2305
- }
2306
-
2307
- /**
2308
- * Waits for the entire URL to match the expected
2309
- *
2310
- * ```js
2311
- * I.waitUrlEquals('/info', 2);
2312
- * I.waitUrlEquals('http://127.0.0.1:8000/info');
2313
- * ```
2314
- *
2315
- * @param {string} urlPart value to check.
2316
- * @param {number} [sec=1] (optional, `1` by default) time in seconds to wait
2317
- * ⚠️ returns a _promise_ which is synchronized internally by recorder
2318
- *
2319
- */
2320
- async waitUrlEquals(urlPart, sec = null) {
2321
- const aSec = sec || this.options.waitForTimeoutInSeconds;
2322
- const waitTimeout = aSec * 1000;
2323
- const baseUrl = this.options.url;
2324
- if (urlPart.indexOf('http') < 0) {
2325
- urlPart = baseUrl + urlPart;
2326
- }
2327
-
2328
- return this.browser.wait(EC.urlIs(urlPart), waitTimeout)
2329
- .catch(async (e) => {
2330
- const currUrl = await this.browser.getCurrentUrl();
2331
- if (/wait timed out after/i.test(e.message)) {
2332
- throw new Error(`expected url to be ${urlPart}, but found ${currUrl}`);
2333
- } else {
2334
- throw e;
2335
- }
2336
- });
2337
- }
2338
-
2339
- /**
2340
- * Waits for a text to appear (by default waits for 1sec).
2341
- * Element can be located by CSS or XPath.
2342
- * Narrow down search results by providing context.
2343
- *
2344
- * ```js
2345
- * I.waitForText('Thank you, form has been submitted');
2346
- * I.waitForText('Thank you, form has been submitted', 5, '#modal');
2347
- * ```
2348
- *
2349
- * @param {string }text to wait for.
2350
- * @param {number} [sec=1] (optional, `1` by default) time in seconds to wait
2351
- * @param {CodeceptJS.LocatorOrString} [context] (optional) element located by CSS|XPath|strict locator.
2352
- * ⚠️ returns a _promise_ which is synchronized internally by recorder
2353
- *
2354
- */
2355
- async waitForText(text, sec = null, context = null) {
2356
- if (!context) {
2357
- context = this.context;
2358
- }
2359
- const el = global.element(guessLocator(context) || global.by.css(context));
2360
- const aSec = sec || this.options.waitForTimeoutInSeconds;
2361
- return this.browser.wait(EC.textToBePresentInElement(el, text), aSec * 1000);
2362
- }
2363
-
2364
- // ANGULAR SPECIFIC
2365
-
2366
- /**
2367
- * Moves to url
2368
- */
2369
- moveTo(path) {
2370
- return this.browser.setLocation(path);
2371
- }
2372
-
2373
- /**
2374
- * Reload the current page.
2375
- *
2376
- * ```js
2377
- * I.refreshPage();
2378
- * ```
2379
- * ⚠️ returns a _promise_ which is synchronized internally by recorder
2380
- *
2381
- */
2382
- refreshPage() {
2383
- return this.browser.refresh();
2384
- }
2385
-
2386
- /**
2387
- * Reloads page
2388
- */
2389
- refresh() {
2390
- console.log('Deprecated in favor of refreshPage');
2391
- return this.browser.refresh();
2392
- }
2393
-
2394
- /**
2395
- * Scrolls to element matched by locator.
2396
- * Extra shift can be set with offsetX and offsetY options.
2397
- *
2398
- * ```js
2399
- * I.scrollTo('footer');
2400
- * I.scrollTo('#submit', 5, 5);
2401
- * ```
2402
- *
2403
- * @param {CodeceptJS.LocatorOrString} locator located by CSS|XPath|strict locator.
2404
- * @param {number} [offsetX=0] (optional, `0` by default) X-axis offset.
2405
- * @param {number} [offsetY=0] (optional, `0` by default) Y-axis offset.
2406
- * ⚠️ returns a _promise_ which is synchronized internally by recorder
2407
- *
2408
- */
2409
- async scrollTo(locator, offsetX = 0, offsetY = 0) {
2410
- if (typeof locator === 'number' && typeof offsetX === 'number') {
2411
- offsetY = offsetX;
2412
- offsetX = locator;
2413
- locator = null;
2414
- }
2415
-
2416
- if (locator) {
2417
- const res = await this._locate(locator, true);
2418
- if (!res || res.length === 0) {
2419
- return truth(`elements of ${(new Locator(locator))}`, 'to be seen').assert(false);
2420
- }
2421
- const elem = res[0];
2422
- const location = await elem.getLocation();
2423
- /* eslint-disable prefer-arrow-callback */
2424
- return this.executeScript(function (x, y) { return window.scrollTo(x, y); }, location.x + offsetX, location.y + offsetY);
2425
- /* eslint-enable */
2426
- }
2427
-
2428
- /* eslint-disable prefer-arrow-callback, comma-dangle */
2429
- return this.executeScript(function (x, y) { return window.scrollTo(x, y); }, offsetX, offsetY);
2430
- /* eslint-enable */
2431
- }
2432
-
2433
- /**
2434
- * Scroll page to the top.
2435
- *
2436
- * ```js
2437
- * I.scrollPageToTop();
2438
- * ```
2439
- * ⚠️ returns a _promise_ which is synchronized internally by recorder
2440
- *
2441
- */
2442
- async scrollPageToTop() {
2443
- return this.executeScript('window.scrollTo(0, 0);');
2444
- }
2445
-
2446
- /**
2447
- * Scroll page to the bottom.
2448
- *
2449
- * ```js
2450
- * I.scrollPageToBottom();
2451
- * ```
2452
- * ⚠️ returns a _promise_ which is synchronized internally by recorder
2453
- *
2454
- */
2455
- async scrollPageToBottom() {
2456
- /* eslint-disable prefer-arrow-callback, comma-dangle */
2457
- return this.executeScript(function () {
2458
- const body = document.body;
2459
- const html = document.documentElement;
2460
- window.scrollTo(0, Math.max(
2461
- body.scrollHeight, body.offsetHeight,
2462
- html.clientHeight, html.scrollHeight, html.offsetHeight
2463
- ));
2464
- });
2465
- /* eslint-enable */
2466
- }
2467
-
2468
- /**
2469
- * Retrieves a page scroll position and returns it to test.
2470
- * Resumes test execution, so **should be used inside an async function with `await`** operator.
2471
- *
2472
- * ```js
2473
- * let { x, y } = await I.grabPageScrollPosition();
2474
- * ```
2475
- *
2476
- * @returns {Promise<PageScrollPosition>} scroll position
2477
- *
2478
- */
2479
- async grabPageScrollPosition() {
2480
- /* eslint-disable comma-dangle */
2481
- function getScrollPosition() {
2482
- return {
2483
- x: window.pageXOffset,
2484
- y: window.pageYOffset
2485
- };
2486
- }
2487
- /* eslint-enable comma-dangle */
2488
- return this.executeScript(getScrollPosition);
2489
- }
2490
-
2491
- /**
2492
- * Injects Angular module.
2493
- *
2494
- * ```js
2495
- * I.haveModule('modName', function() {
2496
- * angular.module('modName', []).value('foo', 'bar');
2497
- * });
2498
- * ```
2499
- */
2500
- haveModule(modName, fn) {
2501
- return this.browser.addMockModule(modName, fn);
2502
- }
2503
-
2504
- /**
2505
- * Removes mocked Angular module. If modName not specified - clears all mock modules.
2506
- *
2507
- * ```js
2508
- * I.resetModule(); // clears all
2509
- * I.resetModule('modName');
2510
- * ```
2511
- */
2512
- resetModule(modName) {
2513
- if (!modName) {
2514
- return this.browser.clearMockModules();
2515
- }
2516
- return this.browser.removeMockModule(modName);
2517
- }
2518
-
2519
- /**
2520
- * Sets cookie(s).
2521
- *
2522
- * Can be a single cookie object or an array of cookies:
2523
- *
2524
- * ```js
2525
- * I.setCookie({name: 'auth', value: true});
2526
- *
2527
- * // as array
2528
- * I.setCookie([
2529
- * {name: 'auth', value: true},
2530
- * {name: 'agree', value: true}
2531
- * ]);
2532
- * ```
2533
- *
2534
- * @param {Cookie|Array<Cookie>} cookie a cookie object or array of cookie objects.
2535
- * ⚠️ returns a _promise_ which is synchronized internally by recorder
2536
- *
2537
- */
2538
- setCookie(cookie) {
2539
- return this.browser.manage().addCookie(cookie);
2540
- }
2541
- }
2542
-
2543
- module.exports = Protractor;
2544
-
2545
- async function findCheckable(client, locator) {
2546
- const matchedLocator = guessLocator(locator);
2547
- if (matchedLocator) {
2548
- return client.findElements(matchedLocator);
2549
- }
2550
- const literal = xpathLocator.literal(locator);
2551
- let els = await client.findElements(global.by.xpath(Locator.checkable.byText(literal)));
2552
- if (els.length) {
2553
- return els;
2554
- }
2555
- els = await client.findElements(global.by.xpath(Locator.checkable.byName(literal)));
2556
- if (els.length) {
2557
- return els;
2558
- }
2559
- return client.findElements(global.by.css(locator));
2560
- }
2561
-
2562
- function withStrictLocator(locator) {
2563
- locator = new Locator(locator);
2564
- if (locator.isAccessibilityId()) return withAccessiblitiyLocator.call(this, locator.value);
2565
- return locator.simplify();
2566
- }
2567
-
2568
- function withAccessiblitiyLocator(locator) {
2569
- if (this.isWeb === false) {
2570
- return `accessibility id:${locator.slice(1)}`;
2571
- }
2572
- return `[aria-label="${locator.slice(1)}"]`;
2573
- // hook before webdriverio supports native ~ locators in web
2574
- }
2575
-
2576
- async function findFields(client, locator) {
2577
- const matchedLocator = guessLocator(locator);
2578
- if (matchedLocator) {
2579
- return client.findElements(matchedLocator);
2580
- }
2581
- const literal = xpathLocator.literal(locator);
2582
-
2583
- let els = await client.findElements(global.by.xpath(Locator.field.labelEquals(literal)));
2584
- if (els.length) {
2585
- return els;
2586
- }
2587
-
2588
- els = await client.findElements(global.by.xpath(Locator.field.labelContains(literal)));
2589
- if (els.length) {
2590
- return els;
2591
- }
2592
- els = await client.findElements(global.by.xpath(Locator.field.byName(literal)));
2593
- if (els.length) {
2594
- return els;
2595
- }
2596
- return client.findElements(global.by.css(locator));
2597
- }
2598
-
2599
- async function proceedSee(assertType, text, context) {
2600
- let description;
2601
- let locator;
2602
- if (!context) {
2603
- if (this.context === this.options.rootElement) {
2604
- locator = guessLocator(this.context) || global.by.css(this.context);
2605
- description = 'web application';
2606
- } else {
2607
- // inside within block
2608
- locator = global.by.xpath('.//*');
2609
- description = `current context ${(new Locator(context)).toString()}`;
2610
- }
2611
- } else {
2612
- locator = guessLocator(context) || global.by.css(context);
2613
- description = `element ${(new Locator(context)).toString()}`;
2614
- }
2615
- const enableSmartWait = !!this.context && assertType === 'assert';
2616
- const els = await this._smartWait(() => this.browser.findElements(locator), enableSmartWait);
2617
- const promises = [];
2618
- let source = '';
2619
- els.forEach(el => promises.push(el.getText().then(elText => source += `| ${elText}`)));
2620
- await Promise.all(promises);
2621
- return stringIncludes(description)[assertType](text, source);
2622
- }
2623
-
2624
- async function proceedSeeInField(assertType, field, value) {
2625
- const els = await findFields(this.browser, field);
2626
- assertElementExists(els, field, 'Field');
2627
- const el = els[0];
2628
- const tag = await el.getTagName();
2629
- const fieldVal = await el.getAttribute('value');
2630
- if (tag === 'select') {
2631
- // locate option by values and check them
2632
- const literal = xpathLocator.literal(fieldVal);
2633
- const textEl = await el.findElement(global.by.xpath(Locator.select.byValue(literal)));
2634
- const text = await textEl.getText();
2635
- return equals(`select option by ${field}`)[assertType](value, text);
2636
- }
2637
- return stringIncludes(`field by ${field}`)[assertType](value, fieldVal);
2638
- }
2639
-
2640
- async function proceedIsChecked(assertType, option) {
2641
- const els = await findCheckable(this.browser, option);
2642
- assertElementExists(els, option, 'Option');
2643
- const elsSelected = [];
2644
- els.forEach(el => elsSelected.push(el.isSelected()));
2645
- const values = await Promise.all(elsSelected);
2646
- const selected = values.reduce((prev, cur) => prev || cur);
2647
- return truth(`checkable ${option}`, 'to be checked')[assertType](selected);
2648
- }
2649
-
2650
- async function findClickable(matcher, locator) {
2651
- locator = new Locator(locator);
2652
- if (!locator.isFuzzy()) {
2653
- const els = await this._locate(locator, true);
2654
- assertElementExists(els, locator.value);
2655
- return els[0];
2656
- }
2657
- const literal = xpathLocator.literal(locator.value);
2658
- const narrowLocator = Locator.clickable.narrow(literal);
2659
- let els = await matcher.findElements(global.by.xpath(narrowLocator));
2660
- if (els.length) {
2661
- return els[0];
2662
- }
2663
-
2664
- els = await matcher.findElements(global.by.xpath(Locator.clickable.wide(literal)));
2665
- if (els.length) {
2666
- return els[0];
2667
- }
2668
- return matcher.findElement(global.by.css(locator.value));
2669
- }
2670
-
2671
- function guessLocator(locator) {
2672
- const l = new Locator(locator);
2673
- if (l.isFuzzy()) return false;
2674
- if (l.type) return global.by[l.type](l.value);
2675
- return false;
2676
- }
2677
-
2678
- function assertElementExists(res, locator, prefix, suffix) {
2679
- if (!res.length) {
2680
- throw new ElementNotFound(locator, prefix, suffix);
2681
- }
2682
- }
2683
-
2684
- function isFrameLocator(locator) {
2685
- locator = new Locator(locator);
2686
- if (locator.isFrame()) return locator.value;
2687
- return false;
2688
- }
2689
-
2690
- function isWithin() {
2691
- return Object.keys(withinStore).length !== 0;
2692
- }
2693
-
2694
- function loadGlobals(browser) {
2695
- global.browser = browser;
2696
- global.$ = browser.$;
2697
- global.$$ = browser.$$;
2698
- global.element = browser.element;
2699
- global.by = global.By = new ProtractorBy();
2700
- global.ExpectedConditions = EC = new ProtractorExpectedConditions(browser);
2701
- }