codeceptjs 3.4.1 → 3.5.1-2.beta.7

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (281) hide show
  1. package/README.md +31 -30
  2. package/bin/codecept.js +1 -1
  3. package/lib/actor.js +6 -3
  4. package/lib/ai.js +180 -0
  5. package/lib/cli.js +13 -3
  6. package/lib/codecept.js +8 -0
  7. package/lib/colorUtils.js +10 -0
  8. package/lib/command/definitions.js +2 -7
  9. package/lib/command/dryRun.js +11 -2
  10. package/lib/command/generate.js +46 -3
  11. package/lib/command/info.js +24 -0
  12. package/lib/command/init.js +64 -6
  13. package/lib/command/interactive.js +15 -1
  14. package/lib/command/run-multiple/collection.js +17 -5
  15. package/lib/command/run-multiple.js +4 -2
  16. package/lib/command/run-workers.js +68 -5
  17. package/lib/command/run.js +7 -0
  18. package/lib/command/workers/runTests.js +39 -0
  19. package/lib/container.js +13 -3
  20. package/lib/data/context.js +14 -6
  21. package/lib/event.js +4 -0
  22. package/lib/helper/ApiDataFactory.js +2 -1
  23. package/lib/helper/Appium.js +116 -29
  24. package/lib/helper/Expect.js +422 -0
  25. package/lib/helper/FileSystem.js +1 -1
  26. package/lib/helper/GraphQL.js +25 -0
  27. package/lib/helper/JSONResponse.js +4 -4
  28. package/lib/helper/Nightmare.js +10 -5
  29. package/lib/helper/OpenAI.js +126 -0
  30. package/lib/helper/Playwright.js +1298 -229
  31. package/lib/helper/Protractor.js +12 -7
  32. package/lib/helper/Puppeteer.js +204 -64
  33. package/lib/helper/REST.js +15 -5
  34. package/lib/helper/TestCafe.js +45 -10
  35. package/lib/helper/WebDriver.js +252 -83
  36. package/lib/helper/errors/ElementNotFound.js +2 -1
  37. package/lib/helper/extras/PlaywrightReactVueLocator.js +38 -0
  38. package/lib/helper/scripts/blurElement.js +17 -0
  39. package/lib/helper/scripts/focusElement.js +17 -0
  40. package/lib/helper/scripts/highlightElement.js +20 -0
  41. package/lib/html.js +258 -0
  42. package/lib/interfaces/bdd.js +1 -1
  43. package/lib/interfaces/gherkin.js +37 -3
  44. package/lib/interfaces/scenarioConfig.js +1 -0
  45. package/lib/listener/retry.js +2 -1
  46. package/lib/locator.js +17 -4
  47. package/lib/mochaFactory.js +2 -1
  48. package/lib/output.js +1 -1
  49. package/lib/pause.js +78 -19
  50. package/lib/plugin/autoLogin.js +45 -10
  51. package/lib/plugin/debugErrors.js +67 -0
  52. package/lib/plugin/fakerTransform.js +4 -6
  53. package/lib/plugin/heal.js +209 -0
  54. package/lib/plugin/retryFailedStep.js +10 -1
  55. package/lib/plugin/retryTo.js +2 -4
  56. package/lib/plugin/screenshotOnFail.js +11 -2
  57. package/lib/plugin/selenoid.js +6 -1
  58. package/lib/plugin/standardActingHelpers.js +0 -2
  59. package/lib/plugin/stepByStepReport.js +2 -2
  60. package/lib/plugin/tryTo.js +5 -7
  61. package/lib/plugin/wdio.js +0 -1
  62. package/lib/recorder.js +22 -11
  63. package/lib/secret.js +5 -4
  64. package/lib/session.js +1 -1
  65. package/lib/step.js +36 -12
  66. package/lib/ui.js +5 -3
  67. package/lib/utils.js +22 -1
  68. package/lib/workers.js +83 -10
  69. package/package.json +117 -95
  70. package/translations/de-DE.js +5 -0
  71. package/translations/fr-FR.js +14 -1
  72. package/translations/it-IT.js +1 -0
  73. package/translations/ja-JP.js +14 -9
  74. package/translations/pl-PL.js +5 -0
  75. package/translations/pt-BR.js +1 -0
  76. package/translations/ru-RU.js +1 -0
  77. package/translations/zh-CN.js +5 -0
  78. package/translations/zh-TW.js +5 -0
  79. package/typings/index.d.ts +51 -15
  80. package/typings/promiseBasedTypes.d.ts +864 -802
  81. package/typings/types.d.ts +1339 -744
  82. package/CHANGELOG.md +0 -2427
  83. package/docs/advanced.md +0 -351
  84. package/docs/api.md +0 -323
  85. package/docs/basics.md +0 -980
  86. package/docs/bdd.md +0 -535
  87. package/docs/best.md +0 -237
  88. package/docs/books.md +0 -37
  89. package/docs/bootstrap.md +0 -135
  90. package/docs/build/ApiDataFactory.js +0 -409
  91. package/docs/build/Appium.js +0 -1938
  92. package/docs/build/FileSystem.js +0 -228
  93. package/docs/build/GraphQL.js +0 -204
  94. package/docs/build/GraphQLDataFactory.js +0 -309
  95. package/docs/build/JSONResponse.js +0 -338
  96. package/docs/build/Mochawesome.js +0 -71
  97. package/docs/build/Nightmare.js +0 -2145
  98. package/docs/build/Playwright.js +0 -3986
  99. package/docs/build/Polly.js +0 -42
  100. package/docs/build/Protractor.js +0 -2699
  101. package/docs/build/Puppeteer.js +0 -3710
  102. package/docs/build/REST.js +0 -334
  103. package/docs/build/SeleniumWebdriver.js +0 -76
  104. package/docs/build/TestCafe.js +0 -2057
  105. package/docs/build/WebDriver.js +0 -4017
  106. package/docs/changelog.md +0 -2436
  107. package/docs/commands.md +0 -254
  108. package/docs/community-helpers.md +0 -58
  109. package/docs/configuration.md +0 -157
  110. package/docs/continuous-integration.md +0 -22
  111. package/docs/custom-helpers.md +0 -306
  112. package/docs/data.md +0 -375
  113. package/docs/detox.md +0 -235
  114. package/docs/docker.md +0 -137
  115. package/docs/email.md +0 -183
  116. package/docs/examples.md +0 -149
  117. package/docs/helpers/ApiDataFactory.md +0 -266
  118. package/docs/helpers/Appium.md +0 -1312
  119. package/docs/helpers/Detox.md +0 -586
  120. package/docs/helpers/FileSystem.md +0 -152
  121. package/docs/helpers/GraphQL.md +0 -130
  122. package/docs/helpers/GraphQLDataFactory.md +0 -226
  123. package/docs/helpers/JSONResponse.md +0 -254
  124. package/docs/helpers/Mochawesome.md +0 -8
  125. package/docs/helpers/MockRequest.md +0 -377
  126. package/docs/helpers/Nightmare.md +0 -1256
  127. package/docs/helpers/Playwright.md +0 -2208
  128. package/docs/helpers/Polly.md +0 -44
  129. package/docs/helpers/Puppeteer-firefox.md +0 -86
  130. package/docs/helpers/Puppeteer.md +0 -2141
  131. package/docs/helpers/REST.md +0 -217
  132. package/docs/helpers/TestCafe.md +0 -1222
  133. package/docs/helpers/WebDriver.md +0 -2319
  134. package/docs/hooks.md +0 -340
  135. package/docs/index.md +0 -111
  136. package/docs/installation.md +0 -75
  137. package/docs/internal-api.md +0 -265
  138. package/docs/locators.md +0 -331
  139. package/docs/mobile-react-native-locators.md +0 -67
  140. package/docs/mobile.md +0 -297
  141. package/docs/nightmare.md +0 -223
  142. package/docs/pageobjects.md +0 -291
  143. package/docs/parallel.md +0 -232
  144. package/docs/playwright.md +0 -609
  145. package/docs/plugins.md +0 -1171
  146. package/docs/puppeteer.md +0 -316
  147. package/docs/quickstart.md +0 -163
  148. package/docs/react.md +0 -69
  149. package/docs/reports.md +0 -392
  150. package/docs/secrets.md +0 -30
  151. package/docs/shadow.md +0 -68
  152. package/docs/shared/keys.mustache +0 -31
  153. package/docs/shared/react.mustache +0 -1
  154. package/docs/testcafe.md +0 -174
  155. package/docs/translation.md +0 -247
  156. package/docs/tutorial.md +0 -271
  157. package/docs/typescript.md +0 -180
  158. package/docs/ui.md +0 -59
  159. package/docs/videos.md +0 -28
  160. package/docs/visual.md +0 -202
  161. package/docs/vue.md +0 -121
  162. package/docs/webapi/amOnPage.mustache +0 -11
  163. package/docs/webapi/appendField.mustache +0 -9
  164. package/docs/webapi/attachFile.mustache +0 -12
  165. package/docs/webapi/checkOption.mustache +0 -13
  166. package/docs/webapi/clearCookie.mustache +0 -10
  167. package/docs/webapi/clearField.mustache +0 -9
  168. package/docs/webapi/click.mustache +0 -25
  169. package/docs/webapi/clickLink.mustache +0 -8
  170. package/docs/webapi/closeCurrentTab.mustache +0 -7
  171. package/docs/webapi/closeOtherTabs.mustache +0 -8
  172. package/docs/webapi/dontSee.mustache +0 -11
  173. package/docs/webapi/dontSeeCheckboxIsChecked.mustache +0 -10
  174. package/docs/webapi/dontSeeCookie.mustache +0 -8
  175. package/docs/webapi/dontSeeCurrentUrlEquals.mustache +0 -10
  176. package/docs/webapi/dontSeeElement.mustache +0 -8
  177. package/docs/webapi/dontSeeElementInDOM.mustache +0 -8
  178. package/docs/webapi/dontSeeInCurrentUrl.mustache +0 -4
  179. package/docs/webapi/dontSeeInField.mustache +0 -11
  180. package/docs/webapi/dontSeeInSource.mustache +0 -8
  181. package/docs/webapi/dontSeeInTitle.mustache +0 -8
  182. package/docs/webapi/doubleClick.mustache +0 -13
  183. package/docs/webapi/downloadFile.mustache +0 -12
  184. package/docs/webapi/dragAndDrop.mustache +0 -9
  185. package/docs/webapi/dragSlider.mustache +0 -11
  186. package/docs/webapi/executeAsyncScript.mustache +0 -24
  187. package/docs/webapi/executeScript.mustache +0 -26
  188. package/docs/webapi/fillField.mustache +0 -16
  189. package/docs/webapi/forceClick.mustache +0 -28
  190. package/docs/webapi/forceRightClick.mustache +0 -18
  191. package/docs/webapi/grabAllWindowHandles.mustache +0 -7
  192. package/docs/webapi/grabAttributeFrom.mustache +0 -10
  193. package/docs/webapi/grabAttributeFromAll.mustache +0 -9
  194. package/docs/webapi/grabBrowserLogs.mustache +0 -9
  195. package/docs/webapi/grabCookie.mustache +0 -11
  196. package/docs/webapi/grabCssPropertyFrom.mustache +0 -11
  197. package/docs/webapi/grabCssPropertyFromAll.mustache +0 -10
  198. package/docs/webapi/grabCurrentUrl.mustache +0 -9
  199. package/docs/webapi/grabCurrentWindowHandle.mustache +0 -6
  200. package/docs/webapi/grabDataFromPerformanceTiming.mustache +0 -20
  201. package/docs/webapi/grabElementBoundingRect.mustache +0 -20
  202. package/docs/webapi/grabGeoLocation.mustache +0 -8
  203. package/docs/webapi/grabHTMLFrom.mustache +0 -10
  204. package/docs/webapi/grabHTMLFromAll.mustache +0 -9
  205. package/docs/webapi/grabNumberOfOpenTabs.mustache +0 -8
  206. package/docs/webapi/grabNumberOfVisibleElements.mustache +0 -9
  207. package/docs/webapi/grabPageScrollPosition.mustache +0 -8
  208. package/docs/webapi/grabPopupText.mustache +0 -5
  209. package/docs/webapi/grabSource.mustache +0 -8
  210. package/docs/webapi/grabTextFrom.mustache +0 -10
  211. package/docs/webapi/grabTextFromAll.mustache +0 -9
  212. package/docs/webapi/grabTitle.mustache +0 -8
  213. package/docs/webapi/grabValueFrom.mustache +0 -9
  214. package/docs/webapi/grabValueFromAll.mustache +0 -8
  215. package/docs/webapi/moveCursorTo.mustache +0 -12
  216. package/docs/webapi/openNewTab.mustache +0 -7
  217. package/docs/webapi/pressKey.mustache +0 -12
  218. package/docs/webapi/pressKeyDown.mustache +0 -12
  219. package/docs/webapi/pressKeyUp.mustache +0 -12
  220. package/docs/webapi/pressKeyWithKeyNormalization.mustache +0 -60
  221. package/docs/webapi/refreshPage.mustache +0 -6
  222. package/docs/webapi/resizeWindow.mustache +0 -6
  223. package/docs/webapi/rightClick.mustache +0 -14
  224. package/docs/webapi/saveElementScreenshot.mustache +0 -10
  225. package/docs/webapi/saveScreenshot.mustache +0 -12
  226. package/docs/webapi/say.mustache +0 -10
  227. package/docs/webapi/scrollIntoView.mustache +0 -11
  228. package/docs/webapi/scrollPageToBottom.mustache +0 -6
  229. package/docs/webapi/scrollPageToTop.mustache +0 -6
  230. package/docs/webapi/scrollTo.mustache +0 -12
  231. package/docs/webapi/see.mustache +0 -11
  232. package/docs/webapi/seeAttributesOnElements.mustache +0 -9
  233. package/docs/webapi/seeCheckboxIsChecked.mustache +0 -10
  234. package/docs/webapi/seeCookie.mustache +0 -8
  235. package/docs/webapi/seeCssPropertiesOnElements.mustache +0 -9
  236. package/docs/webapi/seeCurrentUrlEquals.mustache +0 -11
  237. package/docs/webapi/seeElement.mustache +0 -8
  238. package/docs/webapi/seeElementInDOM.mustache +0 -8
  239. package/docs/webapi/seeInCurrentUrl.mustache +0 -8
  240. package/docs/webapi/seeInField.mustache +0 -12
  241. package/docs/webapi/seeInPopup.mustache +0 -8
  242. package/docs/webapi/seeInSource.mustache +0 -7
  243. package/docs/webapi/seeInTitle.mustache +0 -8
  244. package/docs/webapi/seeNumberOfElements.mustache +0 -11
  245. package/docs/webapi/seeNumberOfVisibleElements.mustache +0 -10
  246. package/docs/webapi/seeTextEquals.mustache +0 -9
  247. package/docs/webapi/seeTitleEquals.mustache +0 -8
  248. package/docs/webapi/selectOption.mustache +0 -21
  249. package/docs/webapi/setCookie.mustache +0 -16
  250. package/docs/webapi/setGeoLocation.mustache +0 -12
  251. package/docs/webapi/switchTo.mustache +0 -9
  252. package/docs/webapi/switchToNextTab.mustache +0 -10
  253. package/docs/webapi/switchToPreviousTab.mustache +0 -10
  254. package/docs/webapi/type.mustache +0 -18
  255. package/docs/webapi/uncheckOption.mustache +0 -13
  256. package/docs/webapi/wait.mustache +0 -8
  257. package/docs/webapi/waitForClickable.mustache +0 -11
  258. package/docs/webapi/waitForDetached.mustache +0 -10
  259. package/docs/webapi/waitForElement.mustache +0 -11
  260. package/docs/webapi/waitForEnabled.mustache +0 -6
  261. package/docs/webapi/waitForFunction.mustache +0 -17
  262. package/docs/webapi/waitForInvisible.mustache +0 -10
  263. package/docs/webapi/waitForText.mustache +0 -13
  264. package/docs/webapi/waitForValue.mustache +0 -10
  265. package/docs/webapi/waitForVisible.mustache +0 -10
  266. package/docs/webapi/waitInUrl.mustache +0 -9
  267. package/docs/webapi/waitNumberOfVisibleElements.mustache +0 -10
  268. package/docs/webapi/waitToHide.mustache +0 -10
  269. package/docs/webapi/waitUrlEquals.mustache +0 -10
  270. package/docs/webdriver.md +0 -657
  271. package/docs/wiki/Books-&-Posts.md +0 -27
  272. package/docs/wiki/Community-Helpers-&-Plugins.md +0 -49
  273. package/docs/wiki/Converting-Playwright-to-Istanbul-Coverage.md +0 -29
  274. package/docs/wiki/Examples.md +0 -139
  275. package/docs/wiki/Google-Summer-of-Code-(GSoC)-2020.md +0 -68
  276. package/docs/wiki/Home.md +0 -16
  277. package/docs/wiki/Release-Process.md +0 -24
  278. package/docs/wiki/Roadmap.md +0 -23
  279. package/docs/wiki/Tests.md +0 -1393
  280. package/docs/wiki/Upgrading-to-CodeceptJS-3.md +0 -153
  281. package/docs/wiki/Videos.md +0 -19
@@ -1,2145 +0,0 @@
1
- const path = require('path');
2
-
3
- const urlResolve = require('url').resolve;
4
-
5
- const Helper = require('@codeceptjs/helper');
6
- const { includes: stringIncludes } = require('../assert/include');
7
- const { urlEquals } = require('../assert/equal');
8
- const { equals } = require('../assert/equal');
9
- const { empty } = require('../assert/empty');
10
- const { truth } = require('../assert/truth');
11
- const Locator = require('../locator');
12
- const ElementNotFound = require('./errors/ElementNotFound');
13
- const {
14
- xpathLocator,
15
- fileExists,
16
- screenshotOutputFolder,
17
- toCamelCase,
18
- } = require('../utils');
19
-
20
- const specialKeys = {
21
- Backspace: '\u0008',
22
- Enter: '\u000d',
23
- Delete: '\u007f',
24
- };
25
-
26
- let withinStatus = false;
27
-
28
- /**
29
- * Nightmare helper wraps [Nightmare](https://github.com/segmentio/nightmare) library to provide
30
- * fastest headless testing using Electron engine. Unlike Selenium-based drivers this uses
31
- * Chromium-based browser with Electron with lots of client side scripts, thus should be less stable and
32
- * less trusted.
33
- *
34
- * Requires `nightmare` package to be installed.
35
- *
36
- * ## Configuration
37
- *
38
- * This helper should be configured in codecept.conf.ts or codecept.conf.js
39
- *
40
- * * `url` - base url of website to be tested
41
- * * `restart` (optional, default: true) - restart browser between tests.
42
- * * `disableScreenshots` (optional, default: false) - don't save screenshot on failure.
43
- * * `uniqueScreenshotNames` (optional, default: false) - option to prevent screenshot override if you have scenarios with the same name in different suites.
44
- * * `fullPageScreenshots` (optional, default: false) - make full page screenshots on failure.
45
- * * `keepBrowserState` (optional, default: false) - keep browser state between tests when `restart` set to false.
46
- * * `keepCookies` (optional, default: false) - keep cookies between tests when `restart` set to false.
47
- * * `waitForAction`: (optional) how long to wait after click, doubleClick or PressKey actions in ms. Default: 500.
48
- * * `waitForTimeout`: (optional) default wait* timeout in ms. Default: 1000.
49
- * * `windowSize`: (optional) default window size. Set a dimension like `640x480`.
50
- *
51
- * + options from [Nightmare configuration](https://github.com/segmentio/nightmare#api)
52
- *
53
- * ## Methods
54
- */
55
- class Nightmare extends Helper {
56
- constructor(config) {
57
- super(config);
58
-
59
- this.isRunning = false;
60
-
61
- // override defaults with config
62
- this._setConfig(config);
63
- }
64
-
65
- _validateConfig(config) {
66
- const defaults = {
67
- waitForAction: 500,
68
- waitForTimeout: 1000,
69
- fullPageScreenshots: false,
70
- disableScreenshots: false,
71
- uniqueScreenshotNames: false,
72
- rootElement: 'body',
73
- restart: true,
74
- keepBrowserState: false,
75
- keepCookies: false,
76
- js_errors: null,
77
- enableHAR: false,
78
- };
79
-
80
- return Object.assign(defaults, config);
81
- }
82
-
83
- static _config() {
84
- return [
85
- { name: 'url', message: 'Base url of site to be tested', default: 'http://localhost' },
86
- {
87
- name: 'show', message: 'Show browser window', default: true, type: 'confirm',
88
- },
89
- ];
90
- }
91
-
92
- static _checkRequirements() {
93
- try {
94
- require('nightmare');
95
- } catch (e) {
96
- return ['nightmare'];
97
- }
98
- }
99
-
100
- async _init() {
101
- this.Nightmare = require('nightmare');
102
-
103
- if (this.options.enableHAR) {
104
- require('nightmare-har-plugin').install(this.Nightmare);
105
- }
106
-
107
- this.Nightmare.action('findElements', function (locator, contextEl, done) {
108
- if (!done) {
109
- done = contextEl;
110
- contextEl = null;
111
- }
112
-
113
- const by = Object.keys(locator)[0];
114
- const value = locator[by];
115
-
116
- this.evaluate_now((by, locator, contextEl) => window.codeceptjs.findAndStoreElements(by, locator, contextEl), done, by, value, contextEl);
117
- });
118
-
119
- this.Nightmare.action('findElement', function (locator, contextEl, done) {
120
- if (!done) {
121
- done = contextEl;
122
- contextEl = null;
123
- }
124
-
125
- const by = Object.keys(locator)[0];
126
- const value = locator[by];
127
-
128
- this.evaluate_now((by, locator, contextEl) => {
129
- const res = window.codeceptjs.findAndStoreElement(by, locator, contextEl);
130
- if (res === null) {
131
- throw new Error(`Element ${(new Locator(locator))} couldn't be located by ${by}`);
132
- }
133
- return res;
134
- }, done, by, value, contextEl);
135
- });
136
-
137
- this.Nightmare.action('asyncScript', function () {
138
- let args = Array.prototype.slice.call(arguments);
139
- const done = args.pop();
140
- args = args.splice(1, 0, done);
141
- this.evaluate_now.apply(this, args);
142
- });
143
-
144
- this.Nightmare.action('enterText', function (el, text, clean, done) {
145
- const child = this.child;
146
- const typeFn = () => child.call('type', text, done);
147
-
148
- this.evaluate_now((el, clean) => {
149
- const element = window.codeceptjs.fetchElement(el);
150
- if (clean) element.value = '';
151
- element.focus();
152
- }, () => {
153
- if (clean) return typeFn();
154
- child.call('pressKey', 'End', typeFn); // type End before
155
- }, el, clean);
156
- });
157
-
158
- this.Nightmare.action('pressKey', (ns, options, parent, win, renderer, done) => {
159
- parent.respondTo('pressKey', (ch, done) => {
160
- win.webContents.sendInputEvent({
161
- type: 'keyDown',
162
- keyCode: ch,
163
- });
164
-
165
- win.webContents.sendInputEvent({
166
- type: 'char',
167
- keyCode: ch,
168
- });
169
-
170
- win.webContents.sendInputEvent({
171
- type: 'keyUp',
172
- keyCode: ch,
173
- });
174
- done();
175
- });
176
- done();
177
- }, function (key, done) {
178
- this.child.call('pressKey', key, done);
179
- });
180
-
181
- this.Nightmare.action('triggerMouseEvent', (ns, options, parent, win, renderer, done) => {
182
- parent.respondTo('triggerMouseEvent', (evt, done) => {
183
- win.webContents.sendInputEvent(evt);
184
- done();
185
- });
186
- done();
187
- }, function (event, done) {
188
- this.child.call('triggerMouseEvent', event, done);
189
- });
190
-
191
- this.Nightmare.action(
192
- 'upload',
193
- (ns, options, parent, win, renderer, done) => {
194
- parent.respondTo('upload', (selector, pathsToUpload, done) => {
195
- parent.emit('log', 'paths', pathsToUpload);
196
- try {
197
- // attach the debugger
198
- // NOTE: this will fail if devtools is open
199
- win.webContents.debugger.attach('1.1');
200
- } catch (e) {
201
- parent.emit('log', 'problem attaching', e);
202
- return done(e);
203
- }
204
-
205
- win.webContents.debugger.sendCommand('DOM.getDocument', {}, (err, domDocument) => {
206
- win.webContents.debugger.sendCommand('DOM.querySelector', {
207
- nodeId: domDocument.root.nodeId,
208
- selector,
209
- }, (err, queryResult) => {
210
- // HACK: chromium errors appear to be unpopulated objects?
211
- if (Object.keys(err)
212
- .length > 0) {
213
- parent.emit('log', 'problem selecting', err);
214
- return done(err);
215
- }
216
- win.webContents.debugger.sendCommand('DOM.setFileInputFiles', {
217
- nodeId: queryResult.nodeId,
218
- files: pathsToUpload,
219
- }, (err) => {
220
- if (Object.keys(err)
221
- .length > 0) {
222
- parent.emit('log', 'problem setting input', err);
223
- return done(err);
224
- }
225
- win.webContents.debugger.detach();
226
- done(null, pathsToUpload);
227
- });
228
- });
229
- });
230
- });
231
- done();
232
- },
233
- function (selector, pathsToUpload, done) {
234
- if (!Array.isArray(pathsToUpload)) {
235
- pathsToUpload = [pathsToUpload];
236
- }
237
- this.child.call('upload', selector, pathsToUpload, (err, stuff) => {
238
- done(err, stuff);
239
- });
240
- },
241
- );
242
-
243
- return Promise.resolve();
244
- }
245
-
246
- async _beforeSuite() {
247
- if (!this.options.restart && !this.isRunning) {
248
- this.debugSection('Session', 'Starting singleton browser session');
249
- return this._startBrowser();
250
- }
251
- }
252
-
253
- async _before() {
254
- if (this.options.restart) return this._startBrowser();
255
- if (!this.isRunning) return this._startBrowser();
256
- return this.browser;
257
- }
258
-
259
- async _after() {
260
- if (!this.isRunning) return;
261
- if (this.options.restart) {
262
- this.isRunning = false;
263
- return this._stopBrowser();
264
- }
265
- if (this.options.enableHAR) {
266
- await this.browser.resetHAR();
267
- }
268
- if (this.options.keepBrowserState) return;
269
- if (this.options.keepCookies) {
270
- await this.browser.cookies.clearAll();
271
- }
272
- this.debugSection('Session', 'cleaning up');
273
- return this.executeScript(() => localStorage.clear());
274
- }
275
-
276
- _afterSuite() {
277
- }
278
-
279
- _finishTest() {
280
- if (!this.options.restart && this.isRunning) {
281
- this._stopBrowser();
282
- }
283
- }
284
-
285
- async _startBrowser() {
286
- this.context = this.options.rootElement;
287
- if (this.options.enableHAR) {
288
- this.browser = this.Nightmare(Object.assign(require('nightmare-har-plugin').getDevtoolsOptions(), this.options));
289
- await this.browser;
290
- await this.browser.waitForDevtools();
291
- } else {
292
- this.browser = this.Nightmare(this.options);
293
- await this.browser;
294
- }
295
- await this.browser.goto('about:blank'); // Load a blank page so .saveScreenshot (/evaluate) will work
296
- this.isRunning = true;
297
- this.browser.on('dom-ready', () => this._injectClientScripts());
298
- this.browser.on('did-start-loading', () => this._injectClientScripts());
299
- this.browser.on('will-navigate', () => this._injectClientScripts());
300
- this.browser.on('console', (type, message) => {
301
- this.debug(`${type}: ${message}`);
302
- });
303
-
304
- if (this.options.windowSize) {
305
- const size = this.options.windowSize.split('x');
306
- return this.browser.viewport(parseInt(size[0], 10), parseInt(size[1], 10));
307
- }
308
- }
309
-
310
- /**
311
- * Get HAR
312
- *
313
- * ```js
314
- * let har = await I.grabHAR();
315
- * fs.writeFileSync('sample.har', JSON.stringify({log: har}));
316
- * ```
317
- */
318
- async grabHAR() {
319
- return this.browser.getHAR();
320
- }
321
-
322
- async saveHAR(fileName) {
323
- const outputFile = path.join(global.output_dir, fileName);
324
- this.debug(`HAR is saving to ${outputFile}`);
325
-
326
- await this.browser.getHAR().then((har) => {
327
- require('fs').writeFileSync(outputFile, JSON.stringify({ log: har }));
328
- });
329
- }
330
-
331
- async resetHAR() {
332
- await this.browser.resetHAR();
333
- }
334
-
335
- async _stopBrowser() {
336
- return this.browser.end().catch((error) => {
337
- this.debugSection('Error on End', error);
338
- });
339
- }
340
-
341
- async _withinBegin(locator) {
342
- this.context = locator;
343
- locator = new Locator(locator, 'css');
344
- withinStatus = true;
345
- return this.browser.evaluate((by, locator) => {
346
- const el = window.codeceptjs.findElement(by, locator);
347
- if (!el) throw new Error(`Element by ${by}: ${locator} not found`);
348
- window.codeceptjs.within = el;
349
- }, locator.type, locator.value);
350
- }
351
-
352
- _withinEnd() {
353
- this.context = this.options.rootElement;
354
- withinStatus = false;
355
- return this.browser.evaluate(() => {
356
- window.codeceptjs.within = null;
357
- });
358
- }
359
-
360
- /**
361
- * Locate elements by different locator types, including strict locator.
362
- * Should be used in custom helpers.
363
- *
364
- * This method return promise with array of IDs of found elements.
365
- * Actual elements can be accessed inside `evaluate` by using `codeceptjs.fetchElement()`
366
- * client-side function:
367
- *
368
- * ```js
369
- * // get an inner text of an element
370
- *
371
- * let browser = this.helpers['Nightmare'].browser;
372
- * let value = this.helpers['Nightmare']._locate({name: 'password'}).then(function(els) {
373
- * return browser.evaluate(function(el) {
374
- * return codeceptjs.fetchElement(el).value;
375
- * }, els[0]);
376
- * });
377
- * ```
378
- */
379
- _locate(locator) {
380
- locator = new Locator(locator, 'css');
381
- return this.browser.evaluate((by, locator) => {
382
- return window.codeceptjs.findAndStoreElements(by, locator);
383
- }, locator.type, locator.value);
384
- }
385
-
386
- /**
387
- * Add a header override for all HTTP requests. If header is undefined, the header overrides will be reset.
388
- *
389
- * ```js
390
- * I.haveHeader('x-my-custom-header', 'some value');
391
- * I.haveHeader(); // clear headers
392
- * ```
393
- */
394
- haveHeader(header, value) {
395
- return this.browser.header(header, value);
396
- }
397
-
398
- /**
399
- * Opens a web page in a browser. Requires relative or absolute url.
400
- * If url starts with `/`, opens a web page of a site defined in `url` config parameter.
401
- *
402
- * ```js
403
- * I.amOnPage('/'); // opens main page of website
404
- * I.amOnPage('https://github.com'); // opens github
405
- * I.amOnPage('/login'); // opens a login page
406
- * ```
407
- *
408
- * @param {string} url url path or global url.
409
- * @return {void} automatically synchronized promise with recorder #!
410
- * @param {?object} headers list of request headers can be passed
411
- *
412
- */
413
- async amOnPage(url, headers = null) {
414
- if (!(/^\w+\:\/\//.test(url))) {
415
- url = urlResolve(this.options.url, url);
416
- }
417
- const currentUrl = await this.browser.url();
418
- if (url === currentUrl) {
419
- // navigating to the same url will cause an error in nightmare, so don't do it
420
- return;
421
- }
422
- return this.browser.goto(url, headers).then((res) => {
423
- this.debugSection('URL', res.url);
424
- this.debugSection('Code', res.code);
425
- this.debugSection('Headers', JSON.stringify(res.headers));
426
- });
427
- }
428
-
429
- /**
430
- * Checks that title contains text.
431
- *
432
- * ```js
433
- * I.seeInTitle('Home Page');
434
- * ```
435
- *
436
- * @param {string} text text value to check.
437
- * ⚠️ returns a _promise_ which is synchronized internally by recorder
438
- *
439
- */
440
- async seeInTitle(text) {
441
- const title = await this.browser.title();
442
- stringIncludes('web page title').assert(text, title);
443
- }
444
-
445
- /**
446
- * Checks that title does not contain text.
447
- *
448
- * ```js
449
- * I.dontSeeInTitle('Error');
450
- * ```
451
- *
452
- * @param {string} text value to check.
453
- * ⚠️ returns a _promise_ which is synchronized internally by recorder
454
- *
455
- */
456
- async dontSeeInTitle(text) {
457
- const title = await this.browser.title();
458
- stringIncludes('web page title').negate(text, title);
459
- }
460
-
461
- /**
462
- * Retrieves a page title and returns it to test.
463
- * Resumes test execution, so **should be used inside async with `await`** operator.
464
- *
465
- * ```js
466
- * let title = await I.grabTitle();
467
- * ```
468
- *
469
- * @returns {Promise<string>} title
470
- */
471
- async grabTitle() {
472
- return this.browser.title();
473
- }
474
-
475
- /**
476
- * Get current URL from browser.
477
- * Resumes test execution, so should be used inside an async function.
478
- *
479
- * ```js
480
- * let url = await I.grabCurrentUrl();
481
- * console.log(`Current URL is [${url}]`);
482
- * ```
483
- *
484
- * @returns {Promise<string>} current URL
485
- */
486
- async grabCurrentUrl() {
487
- return this.browser.url();
488
- }
489
-
490
- /**
491
- * Checks that current url contains a provided fragment.
492
- *
493
- * ```js
494
- * I.seeInCurrentUrl('/register'); // we are on registration page
495
- * ```
496
- *
497
- * @param {string} url a fragment to check
498
- * ⚠️ returns a _promise_ which is synchronized internally by recorder
499
- *
500
- */
501
- async seeInCurrentUrl(url) {
502
- const currentUrl = await this.browser.url();
503
- stringIncludes('url').assert(url, currentUrl);
504
- }
505
-
506
- /**
507
- * Checks that current url does not contain a provided fragment.
508
- *
509
- * @param {string} url value to check.
510
- * ⚠️ returns a _promise_ which is synchronized internally by recorder
511
- *
512
- */
513
- async dontSeeInCurrentUrl(url) {
514
- const currentUrl = await this.browser.url();
515
- stringIncludes('url').negate(url, currentUrl);
516
- }
517
-
518
- /**
519
- * Checks that current url is equal to provided one.
520
- * If a relative url provided, a configured url will be prepended to it.
521
- * So both examples will work:
522
- *
523
- * ```js
524
- * I.seeCurrentUrlEquals('/register');
525
- * I.seeCurrentUrlEquals('http://my.site.com/register');
526
- * ```
527
- *
528
- * @param {string} url value to check.
529
- * ⚠️ returns a _promise_ which is synchronized internally by recorder
530
- *
531
- */
532
- async seeCurrentUrlEquals(url) {
533
- const currentUrl = await this.browser.url();
534
- urlEquals(this.options.url).assert(url, currentUrl);
535
- }
536
-
537
- /**
538
- * Checks that current url is not equal to provided one.
539
- * If a relative url provided, a configured url will be prepended to it.
540
- *
541
- * ```js
542
- * I.dontSeeCurrentUrlEquals('/login'); // relative url are ok
543
- * I.dontSeeCurrentUrlEquals('http://mysite.com/login'); // absolute urls are also ok
544
- * ```
545
- *
546
- * @param {string} url value to check.
547
- * ⚠️ returns a _promise_ which is synchronized internally by recorder
548
- *
549
- */
550
- async dontSeeCurrentUrlEquals(url) {
551
- const currentUrl = await this.browser.url();
552
- urlEquals(this.options.url).negate(url, currentUrl);
553
- }
554
-
555
- /**
556
- * Checks that a page contains a visible text.
557
- * Use context parameter to narrow down the search.
558
- *
559
- * ```js
560
- * I.see('Welcome'); // text welcome on a page
561
- * I.see('Welcome', '.content'); // text inside .content div
562
- * I.see('Register', {css: 'form.register'}); // use strict locator
563
- * ```
564
- * @param {string} text expected on page.
565
- * @param {?CodeceptJS.LocatorOrString} [context=null] (optional, `null` by default) element located by CSS|Xpath|strict locator in which to search for text.
566
- * ⚠️ returns a _promise_ which is synchronized internally by recorder
567
- *
568
- */
569
- async see(text, context = null) {
570
- return proceedSee.call(this, 'assert', text, context);
571
- }
572
-
573
- /**
574
- * Opposite to `see`. Checks that a text is not present on a page.
575
- * Use context parameter to narrow down the search.
576
- *
577
- * ```js
578
- * I.dontSee('Login'); // assume we are already logged in.
579
- * I.dontSee('Login', '.nav'); // no login inside .nav element
580
- * ```
581
- *
582
- * @param {string} text which is not present.
583
- * @param {CodeceptJS.LocatorOrString} [context] (optional) element located by CSS|XPath|strict locator in which to perfrom search.
584
- * ⚠️ returns a _promise_ which is synchronized internally by recorder
585
- *
586
- */
587
- dontSee(text, context = null) {
588
- return proceedSee.call(this, 'negate', text, context);
589
- }
590
-
591
- /**
592
- * Checks that a given Element is visible
593
- * Element is located by CSS or XPath.
594
- *
595
- * ```js
596
- * I.seeElement('#modal');
597
- * ```
598
- * @param {CodeceptJS.LocatorOrString} locator located by CSS|XPath|strict locator.
599
- * ⚠️ returns a _promise_ which is synchronized internally by recorder
600
- *
601
- */
602
- async seeElement(locator) {
603
- locator = new Locator(locator, 'css');
604
- const num = await this.browser.evaluate((by, locator) => {
605
- return window.codeceptjs.findElements(by, locator).filter(e => e.offsetWidth > 0 && e.offsetHeight > 0).length;
606
- }, locator.type, locator.value);
607
- equals('number of elements on a page').negate(0, num);
608
- }
609
-
610
- /**
611
- * Opposite to `seeElement`. Checks that element is not visible (or in DOM)
612
- *
613
- * ```js
614
- * I.dontSeeElement('.modal'); // modal is not shown
615
- * ```
616
- *
617
- * @param {CodeceptJS.LocatorOrString} locator located by CSS|XPath|Strict locator.
618
- * ⚠️ returns a _promise_ which is synchronized internally by recorder
619
- *
620
- */
621
- async dontSeeElement(locator) {
622
- locator = new Locator(locator, 'css');
623
- locator = new Locator(locator, 'css');
624
- const num = await this.browser.evaluate((by, locator) => {
625
- return window.codeceptjs.findElements(by, locator).filter(e => e.offsetWidth > 0 && e.offsetHeight > 0).length;
626
- }, locator.type, locator.value);
627
- equals('number of elements on a page').assert(0, num);
628
- }
629
-
630
- /**
631
- * Checks that a given Element is present in the DOM
632
- * Element is located by CSS or XPath.
633
- *
634
- * ```js
635
- * I.seeElementInDOM('#modal');
636
- * ```
637
- * @param {CodeceptJS.LocatorOrString} locator element located by CSS|XPath|strict locator.
638
- * ⚠️ returns a _promise_ which is synchronized internally by recorder
639
- *
640
- */
641
- async seeElementInDOM(locator) {
642
- locator = new Locator(locator, 'css');
643
- const els = await this.browser.findElements(locator.toStrict());
644
- empty('elements').negate(els.fill('ELEMENT'));
645
- }
646
-
647
- /**
648
- * Opposite to `seeElementInDOM`. Checks that element is not on page.
649
- *
650
- * ```js
651
- * I.dontSeeElementInDOM('.nav'); // checks that element is not on page visible or not
652
- * ```
653
- *
654
- * @param {CodeceptJS.LocatorOrString} locator located by CSS|XPath|Strict locator.
655
- * ⚠️ returns a _promise_ which is synchronized internally by recorder
656
- *
657
- */
658
- async dontSeeElementInDOM(locator) {
659
- locator = new Locator(locator, 'css');
660
- const els = await this.browser.findElements(locator.toStrict());
661
- empty('elements').assert(els.fill('ELEMENT'));
662
- }
663
-
664
- /**
665
- * Checks that the current page contains the given string in its raw source code.
666
- *
667
- * ```js
668
- * I.seeInSource('<h1>Green eggs &amp; ham</h1>');
669
- * ```
670
- * @param {string} text value to check.
671
- * ⚠️ returns a _promise_ which is synchronized internally by recorder
672
- *
673
- */
674
- async seeInSource(text) {
675
- const source = await this.browser.evaluate(() => document.documentElement.outerHTML);
676
- stringIncludes('HTML source of a page').assert(text, source);
677
- }
678
-
679
- /**
680
- * Checks that the current page does not contains the given string in its raw source code.
681
- *
682
- * ```js
683
- * I.dontSeeInSource('<!--'); // no comments in source
684
- * ```
685
- *
686
- * @param {string} value to check.
687
- * ⚠️ returns a _promise_ which is synchronized internally by recorder
688
- *
689
- */
690
- async dontSeeInSource(text) {
691
- const source = await this.browser.evaluate(() => document.documentElement.outerHTML);
692
- stringIncludes('HTML source of a page').negate(text, source);
693
- }
694
-
695
- /**
696
- * Asserts that an element appears a given number of times in the DOM.
697
- * Element is located by label or name or CSS or XPath.
698
- *
699
- *
700
- * ```js
701
- * I.seeNumberOfElements('#submitBtn', 1);
702
- * ```
703
- *
704
- * @param {CodeceptJS.LocatorOrString} locator element located by CSS|XPath|strict locator.
705
- * @param {number} num number of elements.
706
- * ⚠️ returns a _promise_ which is synchronized internally by recorder
707
- *
708
- */
709
- async seeNumberOfElements(locator, num) {
710
- const elements = await this._locate(locator);
711
- return equals(`expected number of elements (${(new Locator(locator))}) is ${num}, but found ${elements.length}`).assert(elements.length, num);
712
- }
713
-
714
- /**
715
- * Asserts that an element is visible a given number of times.
716
- * Element is located by CSS or XPath.
717
- *
718
- * ```js
719
- * I.seeNumberOfVisibleElements('.buttons', 3);
720
- * ```
721
- *
722
- * @param {CodeceptJS.LocatorOrString} locator element located by CSS|XPath|strict locator.
723
- * @param {number} num number of elements.
724
- * ⚠️ returns a _promise_ which is synchronized internally by recorder
725
- *
726
- */
727
- async seeNumberOfVisibleElements(locator, num) {
728
- const res = await this.grabNumberOfVisibleElements(locator);
729
- return equals(`expected number of visible elements (${(new Locator(locator))}) is ${num}, but found ${res}`).assert(res, num);
730
- }
731
-
732
- /**
733
- * Grab number of visible elements by locator.
734
- * Resumes test execution, so **should be used inside async function with `await`** operator.
735
- *
736
- * ```js
737
- * let numOfElements = await I.grabNumberOfVisibleElements('p');
738
- * ```
739
- *
740
- * @param {CodeceptJS.LocatorOrString} locator located by CSS|XPath|strict locator.
741
- * @returns {Promise<number>} number of visible elements
742
- */
743
- async grabNumberOfVisibleElements(locator) {
744
- locator = new Locator(locator, 'css');
745
-
746
- const num = await this.browser.evaluate((by, locator) => {
747
- return window.codeceptjs.findElements(by, locator)
748
- .filter(e => e.offsetWidth > 0 && e.offsetHeight > 0).length;
749
- }, locator.type, locator.value);
750
-
751
- return num;
752
- }
753
-
754
- /**
755
- * Perform a click on a link or a button, given by a locator.
756
- * If a fuzzy locator is given, the page will be searched for a button, link, or image matching the locator string.
757
- * For buttons, the "value" attribute, "name" attribute, and inner text are searched. For links, the link text is searched.
758
- * For images, the "alt" attribute and inner text of any parent links are searched.
759
- *
760
- * The second parameter is a context (CSS or XPath locator) to narrow the search.
761
- *
762
- * ```js
763
- * // simple link
764
- * I.click('Logout');
765
- * // button of form
766
- * I.click('Submit');
767
- * // CSS button
768
- * I.click('#form input[type=submit]');
769
- * // XPath
770
- * I.click('//form/*[@type=submit]');
771
- * // link in context
772
- * I.click('Logout', '#nav');
773
- * // using strict locator
774
- * I.click({css: 'nav a.login'});
775
- * ```
776
- *
777
- * @param {CodeceptJS.LocatorOrString} locator clickable link or button located by text, or any element located by CSS|XPath|strict locator.
778
- * @param {?CodeceptJS.LocatorOrString | null} [context=null] (optional, `null` by default) element to search in CSS|XPath|Strict locator.
779
- * ⚠️ returns a _promise_ which is synchronized internally by recorder
780
- *
781
- */
782
- async click(locator, context = null) {
783
- const el = await findClickable.call(this, locator, context);
784
- assertElementExists(el, locator, 'Clickable');
785
- return this.browser.evaluate(el => window.codeceptjs.clickEl(el), el)
786
- .wait(this.options.waitForAction);
787
- }
788
-
789
- /**
790
- * Performs a double-click on an element matched by link|button|label|CSS or XPath.
791
- * Context can be specified as second parameter to narrow search.
792
- *
793
- * ```js
794
- * I.doubleClick('Edit');
795
- * I.doubleClick('Edit', '.actions');
796
- * I.doubleClick({css: 'button.accept'});
797
- * I.doubleClick('.btn.edit');
798
- * ```
799
- *
800
- * @param {CodeceptJS.LocatorOrString} locator clickable link or button located by text, or any element located by CSS|XPath|strict locator.
801
- * @param {?CodeceptJS.LocatorOrString} [context=null] (optional, `null` by default) element to search in CSS|XPath|Strict locator.
802
- * ⚠️ returns a _promise_ which is synchronized internally by recorder
803
- *
804
- */
805
- async doubleClick(locator, context = null) {
806
- const el = await findClickable.call(this, locator, context);
807
- assertElementExists(el, locator, 'Clickable');
808
- return this.browser.evaluate(el => window.codeceptjs.doubleClickEl(el), el)
809
- .wait(this.options.waitForAction);
810
- }
811
-
812
- /**
813
- * Performs right click on a clickable element matched by semantic locator, CSS or XPath.
814
- *
815
- * ```js
816
- * // right click element with id el
817
- * I.rightClick('#el');
818
- * // right click link or button with text "Click me"
819
- * I.rightClick('Click me');
820
- * // right click button with text "Click me" inside .context
821
- * I.rightClick('Click me', '.context');
822
- * ```
823
- *
824
- * @param {CodeceptJS.LocatorOrString} locator clickable element located by CSS|XPath|strict locator.
825
- * @param {?CodeceptJS.LocatorOrString} [context=null] (optional, `null` by default) element located by CSS|XPath|strict locator.
826
- * ⚠️ returns a _promise_ which is synchronized internally by recorder
827
- *
828
- */
829
- async rightClick(locator, context = null) {
830
- const el = await findClickable.call(this, locator, context);
831
- assertElementExists(el, locator, 'Clickable');
832
- return this.browser.evaluate(el => window.codeceptjs.rightClickEl(el), el)
833
- .wait(this.options.waitForAction);
834
- }
835
-
836
- /**
837
- * Moves cursor to element matched by locator.
838
- * Extra shift can be set with offsetX and offsetY options.
839
- *
840
- * ```js
841
- * I.moveCursorTo('.tooltip');
842
- * I.moveCursorTo('#submit', 5,5);
843
- * ```
844
- *
845
- * @param {CodeceptJS.LocatorOrString} locator located by CSS|XPath|strict locator.
846
- * @param {number} [offsetX=0] (optional, `0` by default) X-axis offset.
847
- * @param {number} [offsetY=0] (optional, `0` by default) Y-axis offset.
848
- * ⚠️ returns a _promise_ which is synchronized internally by recorder
849
- *
850
- */
851
- async moveCursorTo(locator, offsetX = 0, offsetY = 0) {
852
- locator = new Locator(locator, 'css');
853
- const el = await this.browser.findElement(locator.toStrict());
854
- assertElementExists(el, locator);
855
- return this.browser.evaluate((el, x, y) => window.codeceptjs.hoverEl(el, x, y), el, offsetX, offsetY)
856
- .wait(this.options.waitForAction); // wait for hover event to happen
857
- }
858
-
859
- /**
860
- * Executes sync script on a page.
861
- * Pass arguments to function as additional parameters.
862
- * Will return execution result to a test.
863
- * In this case you should use async function and await to receive results.
864
- *
865
- * Example with jQuery DatePicker:
866
- *
867
- * ```js
868
- * // change date of jQuery DatePicker
869
- * I.executeScript(function() {
870
- * // now we are inside browser context
871
- * $('date').datetimepicker('setDate', new Date());
872
- * });
873
- * ```
874
- * Can return values. Don't forget to use `await` to get them.
875
- *
876
- * ```js
877
- * let date = await I.executeScript(function(el) {
878
- * // only basic types can be returned
879
- * return $(el).datetimepicker('getDate').toString();
880
- * }, '#date'); // passing jquery selector
881
- * ```
882
- *
883
- * @param {string|function} fn function to be executed in browser context.
884
- * @param {...any} args to be passed to function.
885
- * ⚠️ returns a _promise_ which is synchronized internally by recorder
886
- *
887
- *
888
- * Wrapper for synchronous [evaluate](https://github.com/segmentio/nightmare#evaluatefn-arg1-arg2)
889
- */
890
- async executeScript(...args) {
891
- return this.browser.evaluate.apply(this.browser, args)
892
- .catch(err => err); // Nightmare's first argument is error :(
893
- }
894
-
895
- /**
896
- * Executes async script on page.
897
- * Provided function should execute a passed callback (as first argument) to signal it is finished.
898
- *
899
- * Example: In Vue.js to make components completely rendered we are waiting for [nextTick](https://vuejs.org/v2/api/#Vue-nextTick).
900
- *
901
- * ```js
902
- * I.executeAsyncScript(function(done) {
903
- * Vue.nextTick(done); // waiting for next tick
904
- * });
905
- * ```
906
- *
907
- * By passing value to `done()` function you can return values.
908
- * Additional arguments can be passed as well, while `done` function is always last parameter in arguments list.
909
- *
910
- * ```js
911
- * let val = await I.executeAsyncScript(function(url, done) {
912
- * // in browser context
913
- * $.ajax(url, { success: (data) => done(data); }
914
- * }, 'http://ajax.callback.url/');
915
- * ```
916
- *
917
- * @param {string|function} fn function to be executed in browser context.
918
- * @param {...any} args to be passed to function.
919
- * ⚠️ returns a _promise_ which is synchronized internally by recorder
920
- *
921
- *
922
- * Wrapper for asynchronous [evaluate](https://github.com/segmentio/nightmare#evaluatefn-arg1-arg2).
923
- * Unlike NightmareJS implementation calling `done` will return its first argument.
924
- */
925
- async executeAsyncScript(...args) {
926
- return this.browser.evaluate.apply(this.browser, args)
927
- .catch(err => err); // Nightmare's first argument is error :(
928
- }
929
-
930
- /**
931
- * Resize the current window to provided width and height.
932
- * First parameter can be set to `maximize`.
933
- *
934
- * @param {number} width width in pixels or `maximize`.
935
- * @param {number} height height in pixels.
936
- * ⚠️ returns a _promise_ which is synchronized internally by recorder
937
- *
938
- */
939
- async resizeWindow(width, height) {
940
- if (width === 'maximize') {
941
- throw new Error('Nightmare doesn\'t support resizeWindow to maximum!');
942
- }
943
- return this.browser.viewport(width, height).wait(this.options.waitForAction);
944
- }
945
-
946
- /**
947
- * Selects a checkbox or radio button.
948
- * Element is located by label or name or CSS or XPath.
949
- *
950
- * The second parameter is a context (CSS or XPath locator) to narrow the search.
951
- *
952
- * ```js
953
- * I.checkOption('#agree');
954
- * I.checkOption('I Agree to Terms and Conditions');
955
- * I.checkOption('agree', '//form');
956
- * ```
957
- * @param {CodeceptJS.LocatorOrString} field checkbox located by label | name | CSS | XPath | strict locator.
958
- * @param {?CodeceptJS.LocatorOrString} [context=null] (optional, `null` by default) element located by CSS | XPath | strict locator.
959
- * ⚠️ returns a _promise_ which is synchronized internally by recorder
960
- *
961
- */
962
- async checkOption(field, context = null) {
963
- const els = await findCheckable.call(this, field, context);
964
- assertElementExists(els[0], field, 'Checkbox or radio');
965
- return this.browser.evaluate(els => window.codeceptjs.checkEl(els[0]), els)
966
- .wait(this.options.waitForAction);
967
- }
968
-
969
- /**
970
- * Unselects a checkbox or radio button.
971
- * Element is located by label or name or CSS or XPath.
972
- *
973
- * The second parameter is a context (CSS or XPath locator) to narrow the search.
974
- *
975
- * ```js
976
- * I.uncheckOption('#agree');
977
- * I.uncheckOption('I Agree to Terms and Conditions');
978
- * I.uncheckOption('agree', '//form');
979
- * ```
980
- * @param {CodeceptJS.LocatorOrString} field checkbox located by label | name | CSS | XPath | strict locator.
981
- * @param {?CodeceptJS.LocatorOrString} [context=null] (optional, `null` by default) element located by CSS | XPath | strict locator.
982
- * ⚠️ returns a _promise_ which is synchronized internally by recorder
983
- *
984
- */
985
- async uncheckOption(field, context = null) {
986
- const els = await findCheckable.call(this, field, context);
987
- assertElementExists(els[0], field, 'Checkbox or radio');
988
- return this.browser.evaluate(els => window.codeceptjs.unCheckEl(els[0]), els)
989
- .wait(this.options.waitForAction);
990
- }
991
-
992
- /**
993
- * Fills a text field or textarea, after clearing its value, with the given string.
994
- * Field is located by name, label, CSS, or XPath.
995
- *
996
- * ```js
997
- * // by label
998
- * I.fillField('Email', 'hello@world.com');
999
- * // by name
1000
- * I.fillField('password', secret('123456'));
1001
- * // by CSS
1002
- * I.fillField('form#login input[name=username]', 'John');
1003
- * // or by strict locator
1004
- * I.fillField({css: 'form#login input[name=username]'}, 'John');
1005
- * ```
1006
- * @param {CodeceptJS.LocatorOrString} field located by label|name|CSS|XPath|strict locator.
1007
- * @param {CodeceptJS.StringOrSecret} value text value to fill.
1008
- * ⚠️ returns a _promise_ which is synchronized internally by recorder
1009
- *
1010
- */
1011
- async fillField(field, value) {
1012
- const el = await findField.call(this, field);
1013
- assertElementExists(el, field, 'Field');
1014
- return this.browser.enterText(el, value.toString(), true)
1015
- .wait(this.options.waitForAction);
1016
- }
1017
-
1018
- /**
1019
- * Clears a `<textarea>` or text `<input>` element's value.
1020
- *
1021
- * ```js
1022
- * I.clearField('Email');
1023
- * I.clearField('user[email]');
1024
- * I.clearField('#email');
1025
- * ```
1026
- * @param {LocatorOrString} editable field located by label|name|CSS|XPath|strict locator.
1027
- * ⚠️ returns a _promise_ which is synchronized internally by recorder.
1028
- *
1029
- */
1030
- async clearField(field) {
1031
- return this.fillField(field, '');
1032
- }
1033
-
1034
- /**
1035
- * Appends text to a input field or textarea.
1036
- * Field is located by name, label, CSS or XPath
1037
- *
1038
- * ```js
1039
- * I.appendField('#myTextField', 'appended');
1040
- * ```
1041
- * @param {CodeceptJS.LocatorOrString} field located by label|name|CSS|XPath|strict locator
1042
- * @param {string} value text value to append.
1043
- * ⚠️ returns a _promise_ which is synchronized internally by recorder
1044
- *
1045
- */
1046
- async appendField(field, value) {
1047
- const el = await findField.call(this, field);
1048
- assertElementExists(el, field, 'Field');
1049
- return this.browser.enterText(el, value, false)
1050
- .wait(this.options.waitForAction);
1051
- }
1052
-
1053
- /**
1054
- * Checks that the given input field or textarea equals to given value.
1055
- * For fuzzy locators, fields are matched by label text, the "name" attribute, CSS, and XPath.
1056
- *
1057
- * ```js
1058
- * I.seeInField('Username', 'davert');
1059
- * I.seeInField({css: 'form textarea'},'Type your comment here');
1060
- * I.seeInField('form input[type=hidden]','hidden_value');
1061
- * I.seeInField('#searchform input','Search');
1062
- * ```
1063
- * @param {CodeceptJS.LocatorOrString} field located by label|name|CSS|XPath|strict locator.
1064
- * @param {string} value value to check.
1065
- * ⚠️ returns a _promise_ which is synchronized internally by recorder
1066
- *
1067
- */
1068
- async seeInField(field, value) {
1069
- return proceedSeeInField.call(this, 'assert', field, value);
1070
- }
1071
-
1072
- /**
1073
- * Checks that value of input field or textarea doesn't equal to given value
1074
- * Opposite to `seeInField`.
1075
- *
1076
- * ```js
1077
- * I.dontSeeInField('email', 'user@user.com'); // field by name
1078
- * I.dontSeeInField({ css: 'form input.email' }, 'user@user.com'); // field by CSS
1079
- * ```
1080
- *
1081
- * @param {CodeceptJS.LocatorOrString} field located by label|name|CSS|XPath|strict locator.
1082
- * @param {string} value value to check.
1083
- * ⚠️ returns a _promise_ which is synchronized internally by recorder
1084
- *
1085
- */
1086
- async dontSeeInField(field, value) {
1087
- return proceedSeeInField.call(this, 'negate', field, value);
1088
- }
1089
-
1090
- /**
1091
- * Sends [input event](http://electron.atom.io/docs/api/web-contents/#webcontentssendinputeventevent) on a page.
1092
- * Can submit special keys like 'Enter', 'Backspace', etc
1093
- */
1094
- async pressKey(key) {
1095
- if (Array.isArray(key)) {
1096
- key = key.join('+'); // should work with accelerators...
1097
- }
1098
- if (Object.keys(specialKeys).indexOf(key) >= 0) {
1099
- key = specialKeys[key];
1100
- }
1101
- return this.browser.pressKey(key).wait(this.options.waitForAction);
1102
- }
1103
-
1104
- /**
1105
- * Sends [input event](http://electron.atom.io/docs/api/web-contents/#contentssendinputeventevent) on a page.
1106
- * Should be a mouse event like:
1107
- * {
1108
- type: 'mouseDown',
1109
- x: args.x,
1110
- y: args.y,
1111
- button: "left"
1112
- }
1113
- */
1114
- async triggerMouseEvent(event) {
1115
- return this.browser.triggerMouseEvent(event).wait(this.options.waitForAction);
1116
- }
1117
-
1118
- /**
1119
- * Verifies that the specified checkbox is checked.
1120
- *
1121
- * ```js
1122
- * I.seeCheckboxIsChecked('Agree');
1123
- * I.seeCheckboxIsChecked('#agree'); // I suppose user agreed to terms
1124
- * I.seeCheckboxIsChecked({css: '#signup_form input[type=checkbox]'});
1125
- * ```
1126
- *
1127
- * @param {CodeceptJS.LocatorOrString} field located by label|name|CSS|XPath|strict locator.
1128
- * ⚠️ returns a _promise_ which is synchronized internally by recorder
1129
- *
1130
- */
1131
- async seeCheckboxIsChecked(field) {
1132
- return proceedIsChecked.call(this, 'assert', field);
1133
- }
1134
-
1135
- /**
1136
- * Verifies that the specified checkbox is not checked.
1137
- *
1138
- * ```js
1139
- * I.dontSeeCheckboxIsChecked('#agree'); // located by ID
1140
- * I.dontSeeCheckboxIsChecked('I agree to terms'); // located by label
1141
- * I.dontSeeCheckboxIsChecked('agree'); // located by name
1142
- * ```
1143
- *
1144
- * @param {CodeceptJS.LocatorOrString} field located by label|name|CSS|XPath|strict locator.
1145
- * ⚠️ returns a _promise_ which is synchronized internally by recorder
1146
- *
1147
- */
1148
- async dontSeeCheckboxIsChecked(field) {
1149
- return proceedIsChecked.call(this, 'negate', field);
1150
- }
1151
-
1152
- /**
1153
- * Attaches a file to element located by label, name, CSS or XPath
1154
- * Path to file is relative current codecept directory (where codecept.conf.ts or codecept.conf.js is located).
1155
- * File will be uploaded to remote system (if tests are running remotely).
1156
- *
1157
- * ```js
1158
- * I.attachFile('Avatar', 'data/avatar.jpg');
1159
- * I.attachFile('form input[name=avatar]', 'data/avatar.jpg');
1160
- * ```
1161
- *
1162
- * @param {CodeceptJS.LocatorOrString} locator field located by label|name|CSS|XPath|strict locator.
1163
- * @param {string} pathToFile local file path relative to codecept.conf.ts or codecept.conf.js config file.
1164
- * ⚠️ returns a _promise_ which is synchronized internally by recorder
1165
- *
1166
- *
1167
- * Doesn't work if the Chromium DevTools panel is open (as Chromium allows only one attachment to the debugger at a time. [See more](https://github.com/rosshinkley/nightmare-upload#important-note-about-setting-file-upload-inputs))
1168
- */
1169
- async attachFile(locator, pathToFile) {
1170
- const file = path.join(global.codecept_dir, pathToFile);
1171
-
1172
- locator = new Locator(locator, 'css');
1173
- if (!locator.isCSS()) {
1174
- throw new Error('Only CSS locator allowed for attachFile in Nightmare helper');
1175
- }
1176
-
1177
- if (!fileExists(file)) {
1178
- throw new Error(`File at ${file} can not be found on local system`);
1179
- }
1180
- return this.browser.upload(locator.value, file);
1181
- }
1182
-
1183
- /**
1184
- * Retrieves all texts from an element located by CSS or XPath and returns it to test.
1185
- * Resumes test execution, so **should be used inside async with `await`** operator.
1186
- *
1187
- * ```js
1188
- * let pins = await I.grabTextFromAll('#pin li');
1189
- * ```
1190
- *
1191
- * @param {CodeceptJS.LocatorOrString} locator element located by CSS|XPath|strict locator.
1192
- * @returns {Promise<string[]>} attribute value
1193
- *
1194
- */
1195
- async grabTextFromAll(locator) {
1196
- locator = new Locator(locator, 'css');
1197
- const els = await this.browser.findElements(locator.toStrict());
1198
- const texts = [];
1199
- const getText = el => window.codeceptjs.fetchElement(el).innerText;
1200
- for (const el of els) {
1201
- texts.push(await this.browser.evaluate(getText, el));
1202
- }
1203
- return texts;
1204
- }
1205
-
1206
- /**
1207
- * Retrieves a text from an element located by CSS or XPath and returns it to test.
1208
- * Resumes test execution, so **should be used inside async with `await`** operator.
1209
- *
1210
- * ```js
1211
- * let pin = await I.grabTextFrom('#pin');
1212
- * ```
1213
- * If multiple elements found returns first element.
1214
- *
1215
- * @param {CodeceptJS.LocatorOrString} locator element located by CSS|XPath|strict locator.
1216
- * @returns {Promise<string>} attribute value
1217
- *
1218
- */
1219
- async grabTextFrom(locator) {
1220
- locator = new Locator(locator, 'css');
1221
- const els = await this.browser.findElement(locator.toStrict());
1222
- assertElementExists(els, locator);
1223
- const texts = await this.grabTextFromAll(locator);
1224
- if (texts.length > 1) {
1225
- this.debugSection('GrabText', `Using first element out of ${texts.length}`);
1226
- }
1227
-
1228
- return texts[0];
1229
- }
1230
-
1231
- /**
1232
- * Retrieves an array of value from a form located by CSS or XPath and returns it to test.
1233
- * Resumes test execution, so **should be used inside async function with `await`** operator.
1234
- *
1235
- * ```js
1236
- * let inputs = await I.grabValueFromAll('//form/input');
1237
- * ```
1238
- * @param {CodeceptJS.LocatorOrString} locator field located by label|name|CSS|XPath|strict locator.
1239
- * @returns {Promise<string[]>} attribute value
1240
- *
1241
- */
1242
- async grabValueFromAll(locator) {
1243
- locator = new Locator(locator, 'css');
1244
- const els = await this.browser.findElements(locator.toStrict());
1245
- const values = [];
1246
- const getValues = el => window.codeceptjs.fetchElement(el).value;
1247
- for (const el of els) {
1248
- values.push(await this.browser.evaluate(getValues, el));
1249
- }
1250
-
1251
- return values;
1252
- }
1253
-
1254
- /**
1255
- * Retrieves a value from a form element located by CSS or XPath and returns it to test.
1256
- * Resumes test execution, so **should be used inside async function with `await`** operator.
1257
- * If more than one element is found - value of first element is returned.
1258
- *
1259
- * ```js
1260
- * let email = await I.grabValueFrom('input[name=email]');
1261
- * ```
1262
- * @param {CodeceptJS.LocatorOrString} locator field located by label|name|CSS|XPath|strict locator.
1263
- * @returns {Promise<string>} attribute value
1264
- *
1265
- */
1266
- async grabValueFrom(locator) {
1267
- const el = await findField.call(this, locator);
1268
- assertElementExists(el, locator, 'Field');
1269
- const values = await this.grabValueFromAll(locator);
1270
- if (values.length > 1) {
1271
- this.debugSection('GrabValue', `Using first element out of ${values.length}`);
1272
- }
1273
-
1274
- return values[0];
1275
- }
1276
-
1277
- /**
1278
- * Retrieves an array of attributes from elements located by CSS or XPath and returns it to test.
1279
- * Resumes test execution, so **should be used inside async with `await`** operator.
1280
- *
1281
- * ```js
1282
- * let hints = await I.grabAttributeFromAll('.tooltip', 'title');
1283
- * ```
1284
- * @param {CodeceptJS.LocatorOrString} locator element located by CSS|XPath|strict locator.
1285
- * @param {string} attr attribute name.
1286
- * @returns {Promise<string[]>} attribute value
1287
- *
1288
- */
1289
- async grabAttributeFromAll(locator, attr) {
1290
- locator = new Locator(locator, 'css');
1291
- const els = await this.browser.findElements(locator.toStrict());
1292
- const array = [];
1293
-
1294
- for (let index = 0; index < els.length; index++) {
1295
- const el = els[index];
1296
- array.push(await this.browser.evaluate((el, attr) => window.codeceptjs.fetchElement(el).getAttribute(attr), el, attr));
1297
- }
1298
-
1299
- return array;
1300
- }
1301
-
1302
- /**
1303
- * Retrieves an attribute from an element located by CSS or XPath and returns it to test.
1304
- * Resumes test execution, so **should be used inside async with `await`** operator.
1305
- * If more than one element is found - attribute of first element is returned.
1306
- *
1307
- * ```js
1308
- * let hint = await I.grabAttributeFrom('#tooltip', 'title');
1309
- * ```
1310
- * @param {CodeceptJS.LocatorOrString} locator element located by CSS|XPath|strict locator.
1311
- * @param {string} attr attribute name.
1312
- * @returns {Promise<string>} attribute value
1313
- *
1314
- */
1315
- async grabAttributeFrom(locator, attr) {
1316
- locator = new Locator(locator, 'css');
1317
- const els = await this.browser.findElement(locator.toStrict());
1318
- assertElementExists(els, locator);
1319
-
1320
- const attrs = await this.grabAttributeFromAll(locator, attr);
1321
- if (attrs.length > 1) {
1322
- this.debugSection('GrabAttribute', `Using first element out of ${attrs.length}`);
1323
- }
1324
-
1325
- return attrs[0];
1326
- }
1327
-
1328
- /**
1329
- * Retrieves all the innerHTML from elements located by CSS or XPath and returns it to test.
1330
- * Resumes test execution, so **should be used inside async function with `await`** operator.
1331
- *
1332
- * ```js
1333
- * let postHTMLs = await I.grabHTMLFromAll('.post');
1334
- * ```
1335
- *
1336
- * @param {CodeceptJS.LocatorOrString} element located by CSS|XPath|strict locator.
1337
- * @returns {Promise<string[]>} HTML code for an element
1338
- *
1339
- */
1340
- async grabHTMLFromAll(locator) {
1341
- locator = new Locator(locator, 'css');
1342
- const els = await this.browser.findElements(locator.toStrict());
1343
- const array = [];
1344
-
1345
- for (let index = 0; index < els.length; index++) {
1346
- const el = els[index];
1347
- array.push(await this.browser.evaluate(el => window.codeceptjs.fetchElement(el).innerHTML, el));
1348
- }
1349
- this.debugSection('GrabHTML', array);
1350
-
1351
- return array;
1352
- }
1353
-
1354
- /**
1355
- * Retrieves the innerHTML from an element located by CSS or XPath and returns it to test.
1356
- * Resumes test execution, so **should be used inside async function with `await`** operator.
1357
- * If more than one element is found - HTML of first element is returned.
1358
- *
1359
- * ```js
1360
- * let postHTML = await I.grabHTMLFrom('#post');
1361
- * ```
1362
- *
1363
- * @param {CodeceptJS.LocatorOrString} element located by CSS|XPath|strict locator.
1364
- * @returns {Promise<string>} HTML code for an element
1365
- *
1366
- */
1367
- async grabHTMLFrom(locator) {
1368
- locator = new Locator(locator, 'css');
1369
- const els = await this.browser.findElement(locator.toStrict());
1370
- assertElementExists(els, locator);
1371
- const html = await this.grabHTMLFromAll(locator);
1372
- if (html.length > 1) {
1373
- this.debugSection('GrabHTML', `Using first element out of ${html.length}`);
1374
- }
1375
-
1376
- return html[0];
1377
- }
1378
-
1379
- /**
1380
- * Grab CSS property for given locator
1381
- * Resumes test execution, so **should be used inside an async function with `await`** operator.
1382
- * If more than one element is found - value of first element is returned.
1383
- *
1384
- * ```js
1385
- * const value = await I.grabCssPropertyFrom('h3', 'font-weight');
1386
- * ```
1387
- *
1388
- * @param {CodeceptJS.LocatorOrString} locator element located by CSS|XPath|strict locator.
1389
- * @param {string} cssProperty CSS property name.
1390
- * @returns {Promise<string>} CSS value
1391
- *
1392
- */
1393
- async grabCssPropertyFrom(locator, cssProperty) {
1394
- locator = new Locator(locator, 'css');
1395
- const els = await this.browser.findElements(locator.toStrict());
1396
- const array = [];
1397
-
1398
- const getCssPropForElement = async (el, prop) => {
1399
- return (await this.browser.evaluate((el) => {
1400
- return window.getComputedStyle(window.codeceptjs.fetchElement(el));
1401
- }, el))[toCamelCase(prop)];
1402
- };
1403
-
1404
- for (const el of els) {
1405
- assertElementExists(el, locator);
1406
- const cssValue = await getCssPropForElement(el, cssProperty);
1407
- array.push(cssValue);
1408
- }
1409
- this.debugSection('HTML', array);
1410
-
1411
- return array.length > 1 ? array : array[0];
1412
- }
1413
-
1414
- _injectClientScripts() {
1415
- return this.browser.inject('js', path.join(__dirname, 'clientscripts', 'nightmare.js'));
1416
- }
1417
-
1418
- /**
1419
- * Selects an option in a drop-down select.
1420
- * Field is searched by label | name | CSS | XPath.
1421
- * Option is selected by visible text or by value.
1422
- *
1423
- * ```js
1424
- * I.selectOption('Choose Plan', 'Monthly'); // select by label
1425
- * I.selectOption('subscription', 'Monthly'); // match option by text
1426
- * I.selectOption('subscription', '0'); // or by value
1427
- * I.selectOption('//form/select[@name=account]','Premium');
1428
- * I.selectOption('form select[name=account]', 'Premium');
1429
- * I.selectOption({css: 'form select[name=account]'}, 'Premium');
1430
- * ```
1431
- *
1432
- * Provide an array for the second argument to select multiple options.
1433
- *
1434
- * ```js
1435
- * I.selectOption('Which OS do you use?', ['Android', 'iOS']);
1436
- * ```
1437
- * @param {LocatorOrString} select field located by label|name|CSS|XPath|strict locator.
1438
- * @param {string|Array<*>} option visible text or value of option.
1439
- * ⚠️ returns a _promise_ which is synchronized internally by recorder
1440
- *
1441
- */
1442
- async selectOption(select, option) {
1443
- const fetchAndCheckOption = function (el, locator) {
1444
- el = window.codeceptjs.fetchElement(el);
1445
- const found = document.evaluate(locator, el, null, 5, null);
1446
- let current = null;
1447
- const items = [];
1448
- while (current = found.iterateNext()) {
1449
- items.push(current);
1450
- }
1451
- for (let i = 0; i < items.length; i++) {
1452
- current = items[i];
1453
- if (current instanceof HTMLOptionElement) {
1454
- current.selected = true;
1455
- if (!el.multiple) el.value = current.value;
1456
- }
1457
- const event = document.createEvent('HTMLEvents');
1458
- event.initEvent('change', true, true);
1459
- el.dispatchEvent(event);
1460
- }
1461
- return !!current;
1462
- };
1463
-
1464
- const el = await findField.call(this, select);
1465
- assertElementExists(el, select, 'Selectable field');
1466
- if (!Array.isArray(option)) {
1467
- option = [option];
1468
- }
1469
-
1470
- for (const key in option) {
1471
- const opt = xpathLocator.literal(option[key]);
1472
- const checked = await this.browser.evaluate(fetchAndCheckOption, el, Locator.select.byVisibleText(opt));
1473
-
1474
- if (!checked) {
1475
- await this.browser.evaluate(fetchAndCheckOption, el, Locator.select.byValue(opt));
1476
- }
1477
- }
1478
- return this.browser.wait(this.options.waitForAction);
1479
- }
1480
-
1481
- /**
1482
- * Sets cookie(s).
1483
- *
1484
- * Can be a single cookie object or an array of cookies:
1485
- *
1486
- * ```js
1487
- * I.setCookie({name: 'auth', value: true});
1488
- *
1489
- * // as array
1490
- * I.setCookie([
1491
- * {name: 'auth', value: true},
1492
- * {name: 'agree', value: true}
1493
- * ]);
1494
- * ```
1495
- *
1496
- * @param {Cookie|Array<Cookie>} cookie a cookie object or array of cookie objects.
1497
- * ⚠️ returns a _promise_ which is synchronized internally by recorder
1498
- *
1499
- *
1500
- * Wrapper for `.cookies.set(cookie)`.
1501
- * [See more](https://github.com/segmentio/nightmare/blob/master/Readme.md#cookiessetcookie)
1502
- */
1503
- async setCookie(cookie) {
1504
- return this.browser.cookies.set(cookie);
1505
- }
1506
-
1507
- /**
1508
- * Checks that cookie with given name exists.
1509
- *
1510
- * ```js
1511
- * I.seeCookie('Auth');
1512
- * ```
1513
- *
1514
- * @param {string} name cookie name.
1515
- * ⚠️ returns a _promise_ which is synchronized internally by recorder
1516
- *
1517
- *
1518
- */
1519
- async seeCookie(name) {
1520
- const res = await this.browser.cookies.get(name);
1521
- truth(`cookie ${name}`, 'to be set').assert(res);
1522
- }
1523
-
1524
- /**
1525
- * Checks that cookie with given name does not exist.
1526
- *
1527
- * ```js
1528
- * I.dontSeeCookie('auth'); // no auth cookie
1529
- * ```
1530
- *
1531
- * @param {string} name cookie name.
1532
- * ⚠️ returns a _promise_ which is synchronized internally by recorder
1533
- *
1534
- */
1535
- async dontSeeCookie(name) {
1536
- const res = await this.browser.cookies.get(name);
1537
- truth(`cookie ${name}`, 'to be set').negate(res);
1538
- }
1539
-
1540
- /**
1541
- * Gets a cookie object by name.
1542
- * If none provided gets all cookies.
1543
- * Resumes test execution, so **should be used inside async function with `await`** operator.
1544
- *
1545
- * ```js
1546
- * let cookie = await I.grabCookie('auth');
1547
- * assert(cookie.value, '123456');
1548
- * ```
1549
- *
1550
- * @param {?string} [name=null] cookie name.
1551
- * @returns {Promise<string>|Promise<string[]>} attribute value
1552
- *
1553
- *
1554
- * Cookie in JSON format. If name not passed returns all cookies for this domain.
1555
- *
1556
- * Multiple cookies can be received by passing query object `I.grabCookie({ secure: true});`. If you'd like get all cookies for all urls, use: `.grabCookie({ url: null }).`
1557
- */
1558
- async grabCookie(name) {
1559
- return this.browser.cookies.get(name);
1560
- }
1561
-
1562
- /**
1563
- * Clears a cookie by name,
1564
- * if none provided clears all cookies.
1565
- *
1566
- * ```js
1567
- * I.clearCookie();
1568
- * I.clearCookie('test');
1569
- * ```
1570
- *
1571
- * @param {?string} [cookie=null] (optional, `null` by default) cookie name
1572
- * ⚠️ returns a _promise_ which is synchronized internally by recorder
1573
- *
1574
- */
1575
- async clearCookie(cookie) {
1576
- if (!cookie) {
1577
- return this.browser.cookies.clearAll();
1578
- }
1579
- return this.browser.cookies.clear(cookie);
1580
- }
1581
-
1582
- /**
1583
- * Waits for a function to return true (waits for 1 sec by default).
1584
- * Running in browser context.
1585
- *
1586
- * ```js
1587
- * I.waitForFunction(fn[, [args[, timeout]])
1588
- * ```
1589
- *
1590
- * ```js
1591
- * I.waitForFunction(() => window.requests == 0);
1592
- * I.waitForFunction(() => window.requests == 0, 5); // waits for 5 sec
1593
- * I.waitForFunction((count) => window.requests == count, [3], 5) // pass args and wait for 5 sec
1594
- * ```
1595
- *
1596
- * @param {string|function} fn to be executed in browser context.
1597
- * @param {any[]|number} [argsOrSec] (optional, `1` by default) arguments for function or seconds.
1598
- * @param {number} [sec] (optional, `1` by default) time in seconds to wait
1599
- * ⚠️ returns a _promise_ which is synchronized internally by recorder
1600
- *
1601
- */
1602
- async waitForFunction(fn, argsOrSec = null, sec = null) {
1603
- let args = [];
1604
- if (argsOrSec) {
1605
- if (Array.isArray(argsOrSec)) {
1606
- args = argsOrSec;
1607
- } else if (typeof argsOrSec === 'number') {
1608
- sec = argsOrSec;
1609
- }
1610
- }
1611
- this.browser.options.waitTimeout = sec ? sec * 1000 : this.options.waitForTimeout;
1612
- return this.browser.wait(fn, ...args);
1613
- }
1614
-
1615
- /**
1616
- * Pauses execution for a number of seconds.
1617
- *
1618
- * ```js
1619
- * I.wait(2); // wait 2 secs
1620
- * ```
1621
- *
1622
- * @param {number} sec number of second to wait.
1623
- * ⚠️ returns a _promise_ which is synchronized internally by recorder
1624
- *
1625
- */
1626
- async wait(sec) {
1627
- return new Promise(((done) => {
1628
- setTimeout(done, sec * 1000);
1629
- }));
1630
- }
1631
-
1632
- /**
1633
- * Waits for a text to appear (by default waits for 1sec).
1634
- * Element can be located by CSS or XPath.
1635
- * Narrow down search results by providing context.
1636
- *
1637
- * ```js
1638
- * I.waitForText('Thank you, form has been submitted');
1639
- * I.waitForText('Thank you, form has been submitted', 5, '#modal');
1640
- * ```
1641
- *
1642
- * @param {string }text to wait for.
1643
- * @param {number} [sec=1] (optional, `1` by default) time in seconds to wait
1644
- * @param {CodeceptJS.LocatorOrString} [context] (optional) element located by CSS|XPath|strict locator.
1645
- * ⚠️ returns a _promise_ which is synchronized internally by recorder
1646
- *
1647
- */
1648
- async waitForText(text, sec, context = null) {
1649
- if (!context) {
1650
- context = this.context;
1651
- }
1652
- const locator = new Locator(context, 'css');
1653
- this.browser.options.waitTimeout = sec ? sec * 1000 : this.options.waitForTimeout;
1654
- return this.browser.wait((by, locator, text) => {
1655
- return window.codeceptjs.findElement(by, locator).innerText.indexOf(text) > -1;
1656
- }, locator.type, locator.value, text).catch((err) => {
1657
- if (err.message.indexOf('Cannot read property') > -1) {
1658
- throw new Error(`element (${JSON.stringify(context)}) is not in DOM. Unable to wait text.`);
1659
- } else if (err.message && err.message.indexOf('.wait() timed out after') > -1) {
1660
- throw new Error(`there is no element(${JSON.stringify(context)}) with text "${text}" after ${sec} sec`);
1661
- } else throw err;
1662
- });
1663
- }
1664
-
1665
- /**
1666
- * Waits for an element to become visible on a page (by default waits for 1sec).
1667
- * Element can be located by CSS or XPath.
1668
- *
1669
- * ```js
1670
- * I.waitForVisible('#popup');
1671
- * ```
1672
- *
1673
- * @param {CodeceptJS.LocatorOrString} locator element located by CSS|XPath|strict locator.
1674
- * @param {number} [sec=1] (optional, `1` by default) time in seconds to wait
1675
- * ⚠️ returns a _promise_ which is synchronized internally by recorder
1676
- *
1677
- */
1678
- waitForVisible(locator, sec) {
1679
- this.browser.options.waitTimeout = sec ? sec * 1000 : this.options.waitForTimeout;
1680
- locator = new Locator(locator, 'css');
1681
-
1682
- return this.browser.wait((by, locator) => {
1683
- const el = window.codeceptjs.findElement(by, locator);
1684
- if (!el) return false;
1685
- return el.offsetWidth > 0 && el.offsetHeight > 0;
1686
- }, locator.type, locator.value).catch((err) => {
1687
- if (err.message && err.message.indexOf('.wait() timed out after') > -1) {
1688
- throw new Error(`element (${JSON.stringify(locator)}) still not visible on page after ${sec} sec`);
1689
- } else throw err;
1690
- });
1691
- }
1692
-
1693
- /**
1694
- * Waits for an element to hide (by default waits for 1sec).
1695
- * Element can be located by CSS or XPath.
1696
- *
1697
- * ```js
1698
- * I.waitToHide('#popup');
1699
- * ```
1700
- *
1701
- * @param {CodeceptJS.LocatorOrString} locator element located by CSS|XPath|strict locator.
1702
- * @param {number} [sec=1] (optional, `1` by default) time in seconds to wait
1703
- * ⚠️ returns a _promise_ which is synchronized internally by recorder
1704
- *
1705
- */
1706
- async waitToHide(locator, sec = null) {
1707
- return this.waitForInvisible(locator, sec);
1708
- }
1709
-
1710
- /**
1711
- * Waits for an element to be removed or become invisible on a page (by default waits for 1sec).
1712
- * Element can be located by CSS or XPath.
1713
- *
1714
- * ```js
1715
- * I.waitForInvisible('#popup');
1716
- * ```
1717
- *
1718
- * @param {CodeceptJS.LocatorOrString} locator element located by CSS|XPath|strict locator.
1719
- * @param {number} [sec=1] (optional, `1` by default) time in seconds to wait
1720
- * ⚠️ returns a _promise_ which is synchronized internally by recorder
1721
- *
1722
- */
1723
- waitForInvisible(locator, sec) {
1724
- this.browser.options.waitTimeout = sec ? sec * 1000 : this.options.waitForTimeout;
1725
- locator = new Locator(locator, 'css');
1726
-
1727
- return this.browser.wait((by, locator) => {
1728
- const el = window.codeceptjs.findElement(by, locator);
1729
- if (!el) return true;
1730
- return !(el.offsetWidth > 0 && el.offsetHeight > 0);
1731
- }, locator.type, locator.value).catch((err) => {
1732
- if (err.message && err.message.indexOf('.wait() timed out after') > -1) {
1733
- throw new Error(`element (${JSON.stringify(locator)}) still visible after ${sec} sec`);
1734
- } else throw err;
1735
- });
1736
- }
1737
-
1738
- /**
1739
- * Waits for element to be present on page (by default waits for 1sec).
1740
- * Element can be located by CSS or XPath.
1741
- *
1742
- * ```js
1743
- * I.waitForElement('.btn.continue');
1744
- * I.waitForElement('.btn.continue', 5); // wait for 5 secs
1745
- * ```
1746
- *
1747
- * @param {CodeceptJS.LocatorOrString} locator element located by CSS|XPath|strict locator.
1748
- * @param {number} [sec] (optional, `1` by default) time in seconds to wait
1749
- * ⚠️ returns a _promise_ which is synchronized internally by recorder
1750
- *
1751
- */
1752
- async waitForElement(locator, sec) {
1753
- this.browser.options.waitTimeout = sec ? sec * 1000 : this.options.waitForTimeout;
1754
- locator = new Locator(locator, 'css');
1755
-
1756
- return this.browser.wait((by, locator) => window.codeceptjs.findElement(by, locator) !== null, locator.type, locator.value).catch((err) => {
1757
- if (err.message && err.message.indexOf('.wait() timed out after') > -1) {
1758
- throw new Error(`element (${JSON.stringify(locator)}) still not present on page after ${sec} sec`);
1759
- } else throw err;
1760
- });
1761
- }
1762
-
1763
- async waitUntilExists(locator, sec) {
1764
- console.log(`waitUntilExists deprecated:
1765
- * use 'waitForElement' to wait for element to be attached
1766
- * use 'waitForDetached to wait for element to be removed'`);
1767
- return this.waitForDetached(locator, sec);
1768
- }
1769
-
1770
- /**
1771
- * Waits for an element to become not attached to the DOM on a page (by default waits for 1sec).
1772
- * Element can be located by CSS or XPath.
1773
- *
1774
- * ```js
1775
- * I.waitForDetached('#popup');
1776
- * ```
1777
- *
1778
- * @param {CodeceptJS.LocatorOrString} locator element located by CSS|XPath|strict locator.
1779
- * @param {number} [sec=1] (optional, `1` by default) time in seconds to wait
1780
- * ⚠️ returns a _promise_ which is synchronized internally by recorder
1781
- *
1782
- */
1783
- async waitForDetached(locator, sec) {
1784
- this.browser.options.waitTimeout = sec ? sec * 1000 : this.options.waitForTimeout;
1785
- sec = this.browser.options.waitForTimeout / 1000;
1786
- locator = new Locator(locator, 'css');
1787
-
1788
- return this.browser.wait((by, locator) => window.codeceptjs.findElement(by, locator) === null, locator.type, locator.value).catch((err) => {
1789
- if (err.message && err.message.indexOf('.wait() timed out after') > -1) {
1790
- throw new Error(`element (${JSON.stringify(locator)}) still on page after ${sec} sec`);
1791
- } else throw err;
1792
- });
1793
- }
1794
-
1795
- /**
1796
- * Reload the current page.
1797
- *
1798
- * ```js
1799
- * I.refreshPage();
1800
- * ```
1801
- * ⚠️ returns a _promise_ which is synchronized internally by recorder
1802
- *
1803
- */
1804
- async refreshPage() {
1805
- return this.browser.refresh();
1806
- }
1807
-
1808
- /**
1809
- * Reload the page
1810
- */
1811
- refresh() {
1812
- console.log('Deprecated in favor of refreshPage');
1813
- return this.browser.refresh();
1814
- }
1815
-
1816
- /**
1817
- * Saves screenshot of the specified locator to ouput folder (set in codecept.conf.ts or codecept.conf.js).
1818
- * Filename is relative to output folder.
1819
- *
1820
- * ```js
1821
- * I.saveElementScreenshot(`#submit`,'debug.png');
1822
- * ```
1823
- *
1824
- * @param {CodeceptJS.LocatorOrString} locator element located by CSS|XPath|strict locator.
1825
- * @param {string} fileName file name to save.
1826
- * ⚠️ returns a _promise_ which is synchronized internally by recorder
1827
- *
1828
- *
1829
- */
1830
- async saveElementScreenshot(locator, fileName) {
1831
- const outputFile = screenshotOutputFolder(fileName);
1832
-
1833
- const rect = await this.grabElementBoundingRect(locator);
1834
-
1835
- const button_clip = {
1836
- x: Math.floor(rect.x),
1837
- y: Math.floor(rect.y),
1838
- width: Math.floor(rect.width),
1839
- height: Math.floor(rect.height),
1840
- };
1841
-
1842
- this.debug(`Screenshot of ${(new Locator(locator))} element has been saved to ${outputFile}`);
1843
- // take the screenshot
1844
- await this.browser.screenshot(outputFile, button_clip);
1845
- }
1846
-
1847
- /**
1848
- * Grab the width, height, location of given locator.
1849
- * Provide `width` or `height`as second param to get your desired prop.
1850
- * Resumes test execution, so **should be used inside an async function with `await`** operator.
1851
- *
1852
- * Returns an object with `x`, `y`, `width`, `height` keys.
1853
- *
1854
- * ```js
1855
- * const value = await I.grabElementBoundingRect('h3');
1856
- * // value is like { x: 226.5, y: 89, width: 527, height: 220 }
1857
- * ```
1858
- *
1859
- * To get only one metric use second parameter:
1860
- *
1861
- * ```js
1862
- * const width = await I.grabElementBoundingRect('h3', 'width');
1863
- * // width == 527
1864
- * ```
1865
- * @param {LocatorOrString} locator element located by CSS|XPath|strict locator.
1866
- * @param {string=} elementSize x, y, width or height of the given element.
1867
- * @returns {Promise<DOMRect>|Promise<number>} Element bounding rectangle
1868
- *
1869
- */
1870
- async grabElementBoundingRect(locator, prop) {
1871
- locator = new Locator(locator, 'css');
1872
-
1873
- const rect = await this.browser.evaluate(async (by, locator) => {
1874
- // store the button in a variable
1875
-
1876
- const build_cluster_btn = await window.codeceptjs.findElement(by, locator);
1877
-
1878
- // use the getClientRects() function on the button to determine
1879
- // the size and location
1880
- const rect = build_cluster_btn.getBoundingClientRect();
1881
-
1882
- // convert the rectangle to a clip object and return it
1883
- return {
1884
- x: rect.left,
1885
- y: rect.top,
1886
- width: rect.width,
1887
- height: rect.height,
1888
- };
1889
- }, locator.type, locator.value);
1890
-
1891
- if (prop) return rect[prop];
1892
- return rect;
1893
- }
1894
-
1895
- /**
1896
- * Saves a screenshot to ouput folder (set in codecept.conf.ts or codecept.conf.js).
1897
- * Filename is relative to output folder.
1898
- * 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.
1899
- *
1900
- * ```js
1901
- * I.saveScreenshot('debug.png');
1902
- * I.saveScreenshot('debug.png', true) //resizes to available scrollHeight and scrollWidth before taking screenshot
1903
- * ```
1904
- *
1905
- * @param {string} fileName file name to save.
1906
- * @param {boolean} [fullPage=false] (optional, `false` by default) flag to enable fullscreen screenshot mode.
1907
- * ⚠️ returns a _promise_ which is synchronized internally by recorder
1908
- *
1909
- */
1910
- async saveScreenshot(fileName, fullPage = this.options.fullPageScreenshots) {
1911
- const outputFile = screenshotOutputFolder(fileName);
1912
-
1913
- this.debug(`Screenshot is saving to ${outputFile}`);
1914
-
1915
- if (!fullPage) {
1916
- return this.browser.screenshot(outputFile);
1917
- }
1918
- const { height, width } = await this.browser.evaluate(() => {
1919
- return { height: document.body.scrollHeight, width: document.body.scrollWidth };
1920
- });
1921
- await this.browser.viewport(width, height);
1922
- return this.browser.screenshot(outputFile);
1923
- }
1924
-
1925
- async _failed() {
1926
- if (withinStatus !== false) await this._withinEnd();
1927
- }
1928
-
1929
- /**
1930
- * Scrolls to element matched by locator.
1931
- * Extra shift can be set with offsetX and offsetY options.
1932
- *
1933
- * ```js
1934
- * I.scrollTo('footer');
1935
- * I.scrollTo('#submit', 5, 5);
1936
- * ```
1937
- *
1938
- * @param {CodeceptJS.LocatorOrString} locator located by CSS|XPath|strict locator.
1939
- * @param {number} [offsetX=0] (optional, `0` by default) X-axis offset.
1940
- * @param {number} [offsetY=0] (optional, `0` by default) Y-axis offset.
1941
- * ⚠️ returns a _promise_ which is synchronized internally by recorder
1942
- *
1943
- */
1944
- async scrollTo(locator, offsetX = 0, offsetY = 0) {
1945
- if (typeof locator === 'number' && typeof offsetX === 'number') {
1946
- offsetY = offsetX;
1947
- offsetX = locator;
1948
- locator = null;
1949
- }
1950
- if (locator) {
1951
- locator = new Locator(locator, 'css');
1952
- return this.browser.evaluate((by, locator, offsetX, offsetY) => {
1953
- const el = window.codeceptjs.findElement(by, locator);
1954
- if (!el) throw new Error(`Element not found ${by}: ${locator}`);
1955
- const rect = el.getBoundingClientRect();
1956
- window.scrollTo(rect.left + offsetX, rect.top + offsetY);
1957
- }, locator.type, locator.value, offsetX, offsetY);
1958
- }
1959
- // eslint-disable-next-line prefer-arrow-callback
1960
- return this.executeScript(function (x, y) { return window.scrollTo(x, y); }, offsetX, offsetY);
1961
- }
1962
-
1963
- /**
1964
- * Scroll page to the top.
1965
- *
1966
- * ```js
1967
- * I.scrollPageToTop();
1968
- * ```
1969
- * ⚠️ returns a _promise_ which is synchronized internally by recorder
1970
- *
1971
- */
1972
- async scrollPageToTop() {
1973
- return this.executeScript(() => window.scrollTo(0, 0));
1974
- }
1975
-
1976
- /**
1977
- * Scroll page to the bottom.
1978
- *
1979
- * ```js
1980
- * I.scrollPageToBottom();
1981
- * ```
1982
- * ⚠️ returns a _promise_ which is synchronized internally by recorder
1983
- *
1984
- */
1985
- async scrollPageToBottom() {
1986
- /* eslint-disable prefer-arrow-callback, comma-dangle */
1987
- return this.executeScript(function () {
1988
- const body = document.body;
1989
- const html = document.documentElement;
1990
- window.scrollTo(0, Math.max(
1991
- body.scrollHeight, body.offsetHeight,
1992
- html.clientHeight, html.scrollHeight, html.offsetHeight
1993
- ));
1994
- });
1995
- /* eslint-enable */
1996
- }
1997
-
1998
- /**
1999
- * Retrieves a page scroll position and returns it to test.
2000
- * Resumes test execution, so **should be used inside an async function with `await`** operator.
2001
- *
2002
- * ```js
2003
- * let { x, y } = await I.grabPageScrollPosition();
2004
- * ```
2005
- *
2006
- * @returns {Promise<PageScrollPosition>} scroll position
2007
- *
2008
- */
2009
- async grabPageScrollPosition() {
2010
- /* eslint-disable comma-dangle */
2011
- function getScrollPosition() {
2012
- return {
2013
- x: window.pageXOffset,
2014
- y: window.pageYOffset
2015
- };
2016
- }
2017
- /* eslint-enable comma-dangle */
2018
- return this.executeScript(getScrollPosition);
2019
- }
2020
- }
2021
-
2022
- module.exports = Nightmare;
2023
-
2024
- async function proceedSee(assertType, text, context) {
2025
- let description;
2026
- let locator;
2027
- if (!context) {
2028
- if (this.context === this.options.rootElement) {
2029
- locator = new Locator(this.context, 'css');
2030
- description = 'web application';
2031
- } else {
2032
- description = `current context ${this.context}`;
2033
- locator = new Locator({ xpath: './/*' });
2034
- }
2035
- } else {
2036
- locator = new Locator(context, 'css');
2037
- description = `element ${locator.toString()}`;
2038
- }
2039
-
2040
- const texts = await this.browser.evaluate((by, locator) => {
2041
- return window.codeceptjs.findElements(by, locator).map(el => el.innerText);
2042
- }, locator.type, locator.value);
2043
- const allText = texts.join(' | ');
2044
- return stringIncludes(description)[assertType](text, allText);
2045
- }
2046
-
2047
- async function proceedSeeInField(assertType, field, value) {
2048
- const el = await findField.call(this, field);
2049
- assertElementExists(el, field, 'Field');
2050
- const tag = await this.browser.evaluate(el => window.codeceptjs.fetchElement(el).tagName, el);
2051
- const fieldVal = await this.browser.evaluate(el => window.codeceptjs.fetchElement(el).value, el);
2052
- if (tag === 'select') {
2053
- // locate option by values and check them
2054
- const text = await this.browser.evaluate((el, val) => {
2055
- return el.querySelector(`option[value="${val}"]`).innerText;
2056
- }, el, xpathLocator.literal(fieldVal));
2057
- return equals(`select option by ${field}`)[assertType](value, text);
2058
- }
2059
- return stringIncludes(`field by ${field}`)[assertType](value, fieldVal);
2060
- }
2061
-
2062
- async function proceedIsChecked(assertType, option) {
2063
- const els = await findCheckable.call(this, option);
2064
- assertElementExists(els, option, 'Checkable');
2065
- const selected = await this.browser.evaluate((els) => {
2066
- return els.map(el => window.codeceptjs.fetchElement(el).checked).reduce((prev, cur) => prev || cur);
2067
- }, els);
2068
- return truth(`checkable ${option}`, 'to be checked')[assertType](selected);
2069
- }
2070
-
2071
- async function findCheckable(locator, context) {
2072
- let contextEl = null;
2073
- if (context) {
2074
- contextEl = await this.browser.findElement((new Locator(context, 'css')).toStrict());
2075
- }
2076
-
2077
- const matchedLocator = new Locator(locator);
2078
- if (!matchedLocator.isFuzzy()) {
2079
- return this.browser.findElements(matchedLocator.toStrict(), contextEl);
2080
- }
2081
-
2082
- const literal = xpathLocator.literal(locator);
2083
- let els = await this.browser.findElements({ xpath: Locator.checkable.byText(literal) }, contextEl);
2084
- if (els.length) {
2085
- return els;
2086
- }
2087
- els = await this.browser.findElements({ xpath: Locator.checkable.byName(literal) }, contextEl);
2088
- if (els.length) {
2089
- return els;
2090
- }
2091
- return this.browser.findElements({ css: locator }, contextEl);
2092
- }
2093
-
2094
- async function findClickable(locator, context) {
2095
- let contextEl = null;
2096
- if (context) {
2097
- contextEl = await this.browser.findElement((new Locator(context, 'css')).toStrict());
2098
- }
2099
-
2100
- const matchedLocator = new Locator(locator);
2101
- if (!matchedLocator.isFuzzy()) {
2102
- return this.browser.findElement(matchedLocator.toStrict(), contextEl);
2103
- }
2104
-
2105
- const literal = xpathLocator.literal(locator);
2106
-
2107
- let els = await this.browser.findElements({ xpath: Locator.clickable.narrow(literal) }, contextEl);
2108
- if (els.length) {
2109
- return els[0];
2110
- }
2111
-
2112
- els = await this.browser.findElements({ xpath: Locator.clickable.wide(literal) }, contextEl);
2113
- if (els.length) {
2114
- return els[0];
2115
- }
2116
-
2117
- return this.browser.findElement({ css: locator }, contextEl);
2118
- }
2119
-
2120
- async function findField(locator) {
2121
- const matchedLocator = new Locator(locator);
2122
- if (!matchedLocator.isFuzzy()) {
2123
- return this.browser.findElements(matchedLocator.toStrict());
2124
- }
2125
- const literal = xpathLocator.literal(locator);
2126
-
2127
- let els = await this.browser.findElements({ xpath: Locator.field.labelEquals(literal) });
2128
- if (els.length) {
2129
- return els[0];
2130
- }
2131
-
2132
- els = await this.browser.findElements({ xpath: Locator.field.labelContains(literal) });
2133
- if (els.length) {
2134
- return els[0];
2135
- }
2136
- els = await this.browser.findElements({ xpath: Locator.field.byName(literal) });
2137
- if (els.length) {
2138
- return els[0];
2139
- }
2140
- return this.browser.findElement({ css: locator });
2141
- }
2142
-
2143
- function assertElementExists(el, locator, prefix, suffix) {
2144
- if (el === null) throw new ElementNotFound(locator, prefix, suffix);
2145
- }