codeceptjs 3.5.12-beta.2 → 3.5.12-beta.3

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