codeceptjs 4.0.0-beta.2 → 4.0.0-beta.20

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 (209) hide show
  1. package/README.md +133 -120
  2. package/bin/codecept.js +107 -96
  3. package/bin/test-server.js +64 -0
  4. package/docs/webapi/clearCookie.mustache +1 -1
  5. package/docs/webapi/click.mustache +5 -1
  6. package/lib/actor.js +71 -103
  7. package/lib/ai.js +159 -188
  8. package/lib/assert/empty.js +22 -24
  9. package/lib/assert/equal.js +30 -37
  10. package/lib/assert/error.js +14 -14
  11. package/lib/assert/include.js +43 -48
  12. package/lib/assert/throws.js +11 -11
  13. package/lib/assert/truth.js +22 -22
  14. package/lib/assert.js +20 -18
  15. package/lib/codecept.js +262 -162
  16. package/lib/colorUtils.js +50 -52
  17. package/lib/command/check.js +206 -0
  18. package/lib/command/configMigrate.js +56 -51
  19. package/lib/command/definitions.js +96 -109
  20. package/lib/command/dryRun.js +77 -79
  21. package/lib/command/generate.js +234 -194
  22. package/lib/command/gherkin/init.js +42 -33
  23. package/lib/command/gherkin/snippets.js +76 -74
  24. package/lib/command/gherkin/steps.js +20 -17
  25. package/lib/command/info.js +74 -38
  26. package/lib/command/init.js +301 -290
  27. package/lib/command/interactive.js +41 -32
  28. package/lib/command/list.js +28 -27
  29. package/lib/command/run-multiple/chunk.js +51 -48
  30. package/lib/command/run-multiple/collection.js +5 -5
  31. package/lib/command/run-multiple/run.js +5 -1
  32. package/lib/command/run-multiple.js +97 -97
  33. package/lib/command/run-rerun.js +19 -25
  34. package/lib/command/run-workers.js +68 -92
  35. package/lib/command/run.js +39 -27
  36. package/lib/command/utils.js +80 -64
  37. package/lib/command/workers/runTests.js +388 -226
  38. package/lib/config.js +109 -50
  39. package/lib/container.js +641 -261
  40. package/lib/data/context.js +60 -61
  41. package/lib/data/dataScenarioConfig.js +47 -47
  42. package/lib/data/dataTableArgument.js +32 -32
  43. package/lib/data/table.js +22 -22
  44. package/lib/effects.js +307 -0
  45. package/lib/element/WebElement.js +327 -0
  46. package/lib/els.js +160 -0
  47. package/lib/event.js +173 -163
  48. package/lib/globals.js +141 -0
  49. package/lib/heal.js +89 -85
  50. package/lib/helper/AI.js +131 -41
  51. package/lib/helper/ApiDataFactory.js +107 -75
  52. package/lib/helper/Appium.js +542 -404
  53. package/lib/helper/FileSystem.js +100 -79
  54. package/lib/helper/GraphQL.js +44 -43
  55. package/lib/helper/GraphQLDataFactory.js +52 -52
  56. package/lib/helper/JSONResponse.js +126 -88
  57. package/lib/helper/Mochawesome.js +54 -29
  58. package/lib/helper/Playwright.js +2547 -1316
  59. package/lib/helper/Puppeteer.js +1578 -1181
  60. package/lib/helper/REST.js +209 -68
  61. package/lib/helper/WebDriver.js +1482 -1342
  62. package/lib/helper/errors/ConnectionRefused.js +6 -6
  63. package/lib/helper/errors/ElementAssertion.js +11 -16
  64. package/lib/helper/errors/ElementNotFound.js +5 -9
  65. package/lib/helper/errors/RemoteBrowserConnectionRefused.js +5 -5
  66. package/lib/helper/extras/Console.js +11 -11
  67. package/lib/helper/extras/PlaywrightLocator.js +110 -0
  68. package/lib/helper/extras/PlaywrightPropEngine.js +18 -18
  69. package/lib/helper/extras/PlaywrightReactVueLocator.js +17 -8
  70. package/lib/helper/extras/PlaywrightRestartOpts.js +25 -11
  71. package/lib/helper/extras/Popup.js +22 -22
  72. package/lib/helper/extras/React.js +27 -28
  73. package/lib/helper/network/actions.js +36 -42
  74. package/lib/helper/network/utils.js +78 -84
  75. package/lib/helper/scripts/blurElement.js +5 -5
  76. package/lib/helper/scripts/focusElement.js +5 -5
  77. package/lib/helper/scripts/highlightElement.js +8 -8
  78. package/lib/helper/scripts/isElementClickable.js +34 -34
  79. package/lib/helper.js +2 -3
  80. package/lib/history.js +23 -19
  81. package/lib/hooks.js +8 -8
  82. package/lib/html.js +94 -104
  83. package/lib/index.js +38 -27
  84. package/lib/listener/config.js +30 -23
  85. package/lib/listener/emptyRun.js +54 -0
  86. package/lib/listener/enhancedGlobalRetry.js +110 -0
  87. package/lib/listener/exit.js +16 -18
  88. package/lib/listener/globalRetry.js +70 -0
  89. package/lib/listener/globalTimeout.js +181 -0
  90. package/lib/listener/helpers.js +76 -51
  91. package/lib/listener/mocha.js +10 -11
  92. package/lib/listener/result.js +11 -0
  93. package/lib/listener/retryEnhancer.js +85 -0
  94. package/lib/listener/steps.js +71 -59
  95. package/lib/listener/store.js +20 -0
  96. package/lib/locator.js +214 -197
  97. package/lib/mocha/asyncWrapper.js +274 -0
  98. package/lib/mocha/bdd.js +167 -0
  99. package/lib/mocha/cli.js +341 -0
  100. package/lib/mocha/factory.js +163 -0
  101. package/lib/mocha/featureConfig.js +89 -0
  102. package/lib/mocha/gherkin.js +231 -0
  103. package/lib/mocha/hooks.js +121 -0
  104. package/lib/mocha/index.js +21 -0
  105. package/lib/mocha/inject.js +46 -0
  106. package/lib/{interfaces → mocha}/scenarioConfig.js +58 -34
  107. package/lib/mocha/suite.js +89 -0
  108. package/lib/mocha/test.js +184 -0
  109. package/lib/mocha/types.d.ts +42 -0
  110. package/lib/mocha/ui.js +242 -0
  111. package/lib/output.js +141 -71
  112. package/lib/parser.js +47 -44
  113. package/lib/pause.js +173 -145
  114. package/lib/plugin/analyze.js +403 -0
  115. package/lib/plugin/{autoLogin.js → auth.js} +178 -79
  116. package/lib/plugin/autoDelay.js +36 -40
  117. package/lib/plugin/coverage.js +131 -78
  118. package/lib/plugin/customLocator.js +22 -21
  119. package/lib/plugin/customReporter.js +53 -0
  120. package/lib/plugin/enhancedRetryFailedStep.js +99 -0
  121. package/lib/plugin/heal.js +101 -110
  122. package/lib/plugin/htmlReporter.js +3648 -0
  123. package/lib/plugin/pageInfo.js +140 -0
  124. package/lib/plugin/pauseOnFail.js +12 -11
  125. package/lib/plugin/retryFailedStep.js +82 -47
  126. package/lib/plugin/screenshotOnFail.js +111 -92
  127. package/lib/plugin/stepByStepReport.js +159 -101
  128. package/lib/plugin/stepTimeout.js +20 -25
  129. package/lib/plugin/subtitles.js +38 -38
  130. package/lib/recorder.js +193 -130
  131. package/lib/rerun.js +94 -49
  132. package/lib/result.js +238 -0
  133. package/lib/retryCoordinator.js +207 -0
  134. package/lib/secret.js +20 -18
  135. package/lib/session.js +95 -89
  136. package/lib/step/base.js +239 -0
  137. package/lib/step/comment.js +10 -0
  138. package/lib/step/config.js +50 -0
  139. package/lib/step/func.js +46 -0
  140. package/lib/step/helper.js +50 -0
  141. package/lib/step/meta.js +99 -0
  142. package/lib/step/record.js +74 -0
  143. package/lib/step/retry.js +11 -0
  144. package/lib/step/section.js +55 -0
  145. package/lib/step.js +18 -329
  146. package/lib/steps.js +54 -0
  147. package/lib/store.js +38 -7
  148. package/lib/template/heal.js +3 -12
  149. package/lib/template/prompts/generatePageObject.js +31 -0
  150. package/lib/template/prompts/healStep.js +13 -0
  151. package/lib/template/prompts/writeStep.js +9 -0
  152. package/lib/test-server.js +334 -0
  153. package/lib/timeout.js +60 -0
  154. package/lib/transform.js +8 -8
  155. package/lib/translation.js +34 -21
  156. package/lib/utils/loaderCheck.js +124 -0
  157. package/lib/utils/mask_data.js +47 -0
  158. package/lib/utils/typescript.js +237 -0
  159. package/lib/utils.js +411 -228
  160. package/lib/workerStorage.js +37 -34
  161. package/lib/workers.js +532 -296
  162. package/package.json +124 -95
  163. package/translations/de-DE.js +5 -3
  164. package/translations/fr-FR.js +5 -4
  165. package/translations/index.js +22 -12
  166. package/translations/it-IT.js +4 -3
  167. package/translations/ja-JP.js +4 -3
  168. package/translations/nl-NL.js +76 -0
  169. package/translations/pl-PL.js +4 -3
  170. package/translations/pt-BR.js +4 -3
  171. package/translations/ru-RU.js +4 -3
  172. package/translations/utils.js +10 -0
  173. package/translations/zh-CN.js +4 -3
  174. package/translations/zh-TW.js +4 -3
  175. package/typings/index.d.ts +546 -185
  176. package/typings/promiseBasedTypes.d.ts +150 -875
  177. package/typings/types.d.ts +547 -992
  178. package/lib/cli.js +0 -249
  179. package/lib/dirname.js +0 -5
  180. package/lib/helper/Expect.js +0 -425
  181. package/lib/helper/ExpectHelper.js +0 -399
  182. package/lib/helper/MockServer.js +0 -223
  183. package/lib/helper/Nightmare.js +0 -1411
  184. package/lib/helper/Protractor.js +0 -1835
  185. package/lib/helper/SoftExpectHelper.js +0 -381
  186. package/lib/helper/TestCafe.js +0 -1410
  187. package/lib/helper/clientscripts/nightmare.js +0 -213
  188. package/lib/helper/testcafe/testControllerHolder.js +0 -42
  189. package/lib/helper/testcafe/testcafe-utils.js +0 -63
  190. package/lib/interfaces/bdd.js +0 -98
  191. package/lib/interfaces/featureConfig.js +0 -69
  192. package/lib/interfaces/gherkin.js +0 -195
  193. package/lib/listener/artifacts.js +0 -19
  194. package/lib/listener/retry.js +0 -68
  195. package/lib/listener/timeout.js +0 -109
  196. package/lib/mochaFactory.js +0 -110
  197. package/lib/plugin/allure.js +0 -15
  198. package/lib/plugin/commentStep.js +0 -136
  199. package/lib/plugin/debugErrors.js +0 -67
  200. package/lib/plugin/eachElement.js +0 -127
  201. package/lib/plugin/fakerTransform.js +0 -49
  202. package/lib/plugin/retryTo.js +0 -121
  203. package/lib/plugin/selenoid.js +0 -371
  204. package/lib/plugin/standardActingHelpers.js +0 -9
  205. package/lib/plugin/tryTo.js +0 -105
  206. package/lib/plugin/wdio.js +0 -246
  207. package/lib/scenario.js +0 -222
  208. package/lib/ui.js +0 -238
  209. package/lib/within.js +0 -70
@@ -1,1411 +0,0 @@
1
- import path from 'path';
2
-
3
- import { resolve as urlResolve } from 'url';
4
-
5
- import Helper from '@codeceptjs/helper';
6
- import { includes as stringIncludes } from '../assert/include.js';
7
- import { urlEquals, equals } from '../assert/equal.js';
8
- import empty from '../assert/empty.js';
9
- import { truth } from '../assert/truth';
10
- import Locator from '../locator.js';
11
- import ElementNotFound from './errors/ElementNotFound.js';
12
- import {
13
- xpathLocator, fileExists, screenshotOutputFolder, toCamelCase,
14
- } from '../utils.js';
15
-
16
- const specialKeys = {
17
- Backspace: '\u0008',
18
- Enter: '\u000d',
19
- Delete: '\u007f',
20
- };
21
-
22
- let withinStatus = false;
23
-
24
- /**
25
- * Nightmare helper wraps [Nightmare](https://github.com/segmentio/nightmare) library to provide
26
- * fastest headless testing using Electron engine. Unlike Selenium-based drivers this uses
27
- * Chromium-based browser with Electron with lots of client side scripts, thus should be less stable and
28
- * less trusted.
29
- *
30
- * Requires `nightmare` package to be installed.
31
- *
32
- * ## Configuration
33
- *
34
- * This helper should be configured in codecept.conf.ts or codecept.conf.js
35
- *
36
- * * `url` - base url of website to be tested
37
- * * `restart` (optional, default: true) - restart browser between tests.
38
- * * `disableScreenshots` (optional, default: false) - don't save screenshot on failure.
39
- * * `uniqueScreenshotNames` (optional, default: false) - option to prevent screenshot override if you have scenarios with the same name in different suites.
40
- * * `fullPageScreenshots` (optional, default: false) - make full page screenshots on failure.
41
- * * `keepBrowserState` (optional, default: false) - keep browser state between tests when `restart` set to false.
42
- * * `keepCookies` (optional, default: false) - keep cookies between tests when `restart` set to false.
43
- * * `waitForAction`: (optional) how long to wait after click, doubleClick or PressKey actions in ms. Default: 500.
44
- * * `waitForTimeout`: (optional) default wait* timeout in ms. Default: 1000.
45
- * * `windowSize`: (optional) default window size. Set a dimension like `640x480`.
46
- *
47
- * + options from [Nightmare configuration](https://github.com/segmentio/nightmare#api)
48
- *
49
- * ## Methods
50
- */
51
- class Nightmare extends Helper {
52
- constructor(config) {
53
- super(config);
54
-
55
- this.isRunning = false;
56
-
57
- // override defaults with config
58
- this._setConfig(config);
59
- }
60
-
61
- _validateConfig(config) {
62
- const defaults = {
63
- waitForAction: 500,
64
- waitForTimeout: 1000,
65
- fullPageScreenshots: false,
66
- disableScreenshots: false,
67
- uniqueScreenshotNames: false,
68
- rootElement: 'body',
69
- restart: true,
70
- keepBrowserState: false,
71
- keepCookies: false,
72
- js_errors: null,
73
- enableHAR: false,
74
- };
75
-
76
- return Object.assign(defaults, config);
77
- }
78
-
79
- static _config() {
80
- return [
81
- { name: 'url', message: 'Base url of site to be tested', default: 'http://localhost' },
82
- {
83
- name: 'show', message: 'Show browser window', default: true, type: 'confirm',
84
- },
85
- ];
86
- }
87
-
88
- static _checkRequirements() {
89
- try {
90
- require('nightmare');
91
- } catch (e) {
92
- return ['nightmare'];
93
- }
94
- }
95
-
96
- async _init() {
97
- this.Nightmare = require('nightmare');
98
-
99
- if (this.options.enableHAR) {
100
- require('nightmare-har-plugin').install(this.Nightmare);
101
- }
102
-
103
- this.Nightmare.action('findElements', function (locator, contextEl, done) {
104
- if (!done) {
105
- done = contextEl;
106
- contextEl = null;
107
- }
108
-
109
- const by = Object.keys(locator)[0];
110
- const value = locator[by];
111
-
112
- this.evaluate_now((by, locator, contextEl) => window.codeceptjs.findAndStoreElements(by, locator, contextEl), done, by, value, contextEl);
113
- });
114
-
115
- this.Nightmare.action('findElement', function (locator, contextEl, done) {
116
- if (!done) {
117
- done = contextEl;
118
- contextEl = null;
119
- }
120
-
121
- const by = Object.keys(locator)[0];
122
- const value = locator[by];
123
-
124
- this.evaluate_now((by, locator, contextEl) => {
125
- const res = window.codeceptjs.findAndStoreElement(by, locator, contextEl);
126
- if (res === null) {
127
- throw new Error(`Element ${(new Locator(locator))} couldn't be located by ${by}`);
128
- }
129
- return res;
130
- }, done, by, value, contextEl);
131
- });
132
-
133
- this.Nightmare.action('asyncScript', function () {
134
- let args = Array.prototype.slice.call(arguments);
135
- const done = args.pop();
136
- args = args.splice(1, 0, done);
137
- this.evaluate_now.apply(this, args);
138
- });
139
-
140
- this.Nightmare.action('enterText', function (el, text, clean, done) {
141
- const child = this.child;
142
- const typeFn = () => child.call('type', text, done);
143
-
144
- this.evaluate_now((el, clean) => {
145
- const element = window.codeceptjs.fetchElement(el);
146
- if (clean) element.value = '';
147
- element.focus();
148
- }, () => {
149
- if (clean) return typeFn();
150
- child.call('pressKey', 'End', typeFn); // type End before
151
- }, el, clean);
152
- });
153
-
154
- this.Nightmare.action('pressKey', (ns, options, parent, win, renderer, done) => {
155
- parent.respondTo('pressKey', (ch, done) => {
156
- win.webContents.sendInputEvent({
157
- type: 'keyDown',
158
- keyCode: ch,
159
- });
160
-
161
- win.webContents.sendInputEvent({
162
- type: 'char',
163
- keyCode: ch,
164
- });
165
-
166
- win.webContents.sendInputEvent({
167
- type: 'keyUp',
168
- keyCode: ch,
169
- });
170
- done();
171
- });
172
- done();
173
- }, function (key, done) {
174
- this.child.call('pressKey', key, done);
175
- });
176
-
177
- this.Nightmare.action('triggerMouseEvent', (ns, options, parent, win, renderer, done) => {
178
- parent.respondTo('triggerMouseEvent', (evt, done) => {
179
- win.webContents.sendInputEvent(evt);
180
- done();
181
- });
182
- done();
183
- }, function (event, done) {
184
- this.child.call('triggerMouseEvent', event, done);
185
- });
186
-
187
- this.Nightmare.action(
188
- 'upload',
189
- (ns, options, parent, win, renderer, done) => {
190
- parent.respondTo('upload', (selector, pathsToUpload, done) => {
191
- parent.emit('log', 'paths', pathsToUpload);
192
- try {
193
- // attach the debugger
194
- // NOTE: this will fail if devtools is open
195
- win.webContents.debugger.attach('1.1');
196
- } catch (e) {
197
- parent.emit('log', 'problem attaching', e);
198
- return done(e);
199
- }
200
-
201
- win.webContents.debugger.sendCommand('DOM.getDocument', {}, (err, domDocument) => {
202
- win.webContents.debugger.sendCommand('DOM.querySelector', {
203
- nodeId: domDocument.root.nodeId,
204
- selector,
205
- }, (err, queryResult) => {
206
- // HACK: chromium errors appear to be unpopulated objects?
207
- if (Object.keys(err)
208
- .length > 0) {
209
- parent.emit('log', 'problem selecting', err);
210
- return done(err);
211
- }
212
- win.webContents.debugger.sendCommand('DOM.setFileInputFiles', {
213
- nodeId: queryResult.nodeId,
214
- files: pathsToUpload,
215
- }, (err) => {
216
- if (Object.keys(err)
217
- .length > 0) {
218
- parent.emit('log', 'problem setting input', err);
219
- return done(err);
220
- }
221
- win.webContents.debugger.detach();
222
- done(null, pathsToUpload);
223
- });
224
- });
225
- });
226
- });
227
- done();
228
- },
229
- function (selector, pathsToUpload, done) {
230
- if (!Array.isArray(pathsToUpload)) {
231
- pathsToUpload = [pathsToUpload];
232
- }
233
- this.child.call('upload', selector, pathsToUpload, (err, stuff) => {
234
- done(err, stuff);
235
- });
236
- },
237
- );
238
-
239
- return Promise.resolve();
240
- }
241
-
242
- async _beforeSuite() {
243
- if (!this.options.restart && !this.isRunning) {
244
- this.debugSection('Session', 'Starting singleton browser session');
245
- return this._startBrowser();
246
- }
247
- }
248
-
249
- async _before() {
250
- if (this.options.restart) return this._startBrowser();
251
- if (!this.isRunning) return this._startBrowser();
252
- return this.browser;
253
- }
254
-
255
- async _after() {
256
- if (!this.isRunning) return;
257
- if (this.options.restart) {
258
- this.isRunning = false;
259
- return this._stopBrowser();
260
- }
261
- if (this.options.enableHAR) {
262
- await this.browser.resetHAR();
263
- }
264
- if (this.options.keepBrowserState) return;
265
- if (this.options.keepCookies) {
266
- await this.browser.cookies.clearAll();
267
- }
268
- this.debugSection('Session', 'cleaning up');
269
- return this.executeScript(() => localStorage.clear());
270
- }
271
-
272
- _afterSuite() {
273
- }
274
-
275
- _finishTest() {
276
- if (!this.options.restart && this.isRunning) {
277
- this._stopBrowser();
278
- }
279
- }
280
-
281
- async _startBrowser() {
282
- this.context = this.options.rootElement;
283
- if (this.options.enableHAR) {
284
- this.browser = this.Nightmare(Object.assign(require('nightmare-har-plugin').getDevtoolsOptions(), this.options));
285
- await this.browser;
286
- await this.browser.waitForDevtools();
287
- } else {
288
- this.browser = this.Nightmare(this.options);
289
- await this.browser;
290
- }
291
- await this.browser.goto('about:blank'); // Load a blank page so .saveScreenshot (/evaluate) will work
292
- this.isRunning = true;
293
- this.browser.on('dom-ready', () => this._injectClientScripts());
294
- this.browser.on('did-start-loading', () => this._injectClientScripts());
295
- this.browser.on('will-navigate', () => this._injectClientScripts());
296
- this.browser.on('console', (type, message) => {
297
- this.debug(`${type}: ${message}`);
298
- });
299
-
300
- if (this.options.windowSize) {
301
- const size = this.options.windowSize.split('x');
302
- return this.browser.viewport(parseInt(size[0], 10), parseInt(size[1], 10));
303
- }
304
- }
305
-
306
- /**
307
- * Get HAR
308
- *
309
- * ```js
310
- * let har = await I.grabHAR();
311
- * fs.writeFileSync('sample.har', JSON.stringify({log: har}));
312
- * ```
313
- */
314
- async grabHAR() {
315
- return this.browser.getHAR();
316
- }
317
-
318
- async saveHAR(fileName) {
319
- const outputFile = path.join(global.output_dir, fileName);
320
- this.debug(`HAR is saving to ${outputFile}`);
321
-
322
- await this.browser.getHAR().then((har) => {
323
- require('fs').writeFileSync(outputFile, JSON.stringify({ log: har }));
324
- });
325
- }
326
-
327
- async resetHAR() {
328
- await this.browser.resetHAR();
329
- }
330
-
331
- async _stopBrowser() {
332
- return this.browser.end().catch((error) => {
333
- this.debugSection('Error on End', error);
334
- });
335
- }
336
-
337
- async _withinBegin(locator) {
338
- this.context = locator;
339
- locator = new Locator(locator, 'css');
340
- withinStatus = true;
341
- return this.browser.evaluate((by, locator) => {
342
- const el = window.codeceptjs.findElement(by, locator);
343
- if (!el) throw new Error(`Element by ${by}: ${locator} not found`);
344
- window.codeceptjs.within = el;
345
- }, locator.type, locator.value);
346
- }
347
-
348
- _withinEnd() {
349
- this.context = this.options.rootElement;
350
- withinStatus = false;
351
- return this.browser.evaluate(() => {
352
- window.codeceptjs.within = null;
353
- });
354
- }
355
-
356
- /**
357
- * Locate elements by different locator types, including strict locator.
358
- * Should be used in custom helpers.
359
- *
360
- * This method return promise with array of IDs of found elements.
361
- * Actual elements can be accessed inside `evaluate` by using `codeceptjs.fetchElement()`
362
- * client-side function:
363
- *
364
- * ```js
365
- * // get an inner text of an element
366
- *
367
- * let browser = this.helpers['Nightmare'].browser;
368
- * let value = this.helpers['Nightmare']._locate({name: 'password'}).then(function(els) {
369
- * return browser.evaluate(function(el) {
370
- * return codeceptjs.fetchElement(el).value;
371
- * }, els[0]);
372
- * });
373
- * ```
374
- */
375
- _locate(locator) {
376
- locator = new Locator(locator, 'css');
377
- return this.browser.evaluate((by, locator) => {
378
- return window.codeceptjs.findAndStoreElements(by, locator);
379
- }, locator.type, locator.value);
380
- }
381
-
382
- /**
383
- * Add a header override for all HTTP requests. If header is undefined, the header overrides will be reset.
384
- *
385
- * ```js
386
- * I.haveHeader('x-my-custom-header', 'some value');
387
- * I.haveHeader(); // clear headers
388
- * ```
389
- */
390
- haveHeader(header, value) {
391
- return this.browser.header(header, value);
392
- }
393
-
394
- /**
395
- * {{> amOnPage }}
396
- * @param {?object} headers list of request headers can be passed
397
- *
398
- */
399
- async amOnPage(url, headers = null) {
400
- if (!(/^\w+\:\/\//.test(url))) {
401
- url = urlResolve(this.options.url, url);
402
- }
403
- const currentUrl = await this.browser.url();
404
- if (url === currentUrl) {
405
- // navigating to the same url will cause an error in nightmare, so don't do it
406
- return;
407
- }
408
- return this.browser.goto(url, headers).then((res) => {
409
- this.debugSection('URL', res.url);
410
- this.debugSection('Code', res.code);
411
- this.debugSection('Headers', JSON.stringify(res.headers));
412
- });
413
- }
414
-
415
- /**
416
- * {{> seeInTitle }}
417
- */
418
- async seeInTitle(text) {
419
- const title = await this.browser.title();
420
- stringIncludes('web page title').assert(text, title);
421
- }
422
-
423
- /**
424
- * {{> dontSeeInTitle }}
425
- */
426
- async dontSeeInTitle(text) {
427
- const title = await this.browser.title();
428
- stringIncludes('web page title').negate(text, title);
429
- }
430
-
431
- /**
432
- * {{> grabTitle }}
433
- */
434
- async grabTitle() {
435
- return this.browser.title();
436
- }
437
-
438
- /**
439
- * {{> grabCurrentUrl }}
440
- */
441
- async grabCurrentUrl() {
442
- return this.browser.url();
443
- }
444
-
445
- /**
446
- * {{> seeInCurrentUrl }}
447
- */
448
- async seeInCurrentUrl(url) {
449
- const currentUrl = await this.browser.url();
450
- stringIncludes('url').assert(url, currentUrl);
451
- }
452
-
453
- /**
454
- * {{> dontSeeInCurrentUrl }}
455
- */
456
- async dontSeeInCurrentUrl(url) {
457
- const currentUrl = await this.browser.url();
458
- stringIncludes('url').negate(url, currentUrl);
459
- }
460
-
461
- /**
462
- * {{> seeCurrentUrlEquals }}
463
- */
464
- async seeCurrentUrlEquals(url) {
465
- const currentUrl = await this.browser.url();
466
- urlEquals(this.options.url).assert(url, currentUrl);
467
- }
468
-
469
- /**
470
- * {{> dontSeeCurrentUrlEquals }}
471
- */
472
- async dontSeeCurrentUrlEquals(url) {
473
- const currentUrl = await this.browser.url();
474
- urlEquals(this.options.url).negate(url, currentUrl);
475
- }
476
-
477
- /**
478
- * {{> see }}
479
- */
480
- async see(text, context = null) {
481
- return proceedSee.call(this, 'assert', text, context);
482
- }
483
-
484
- /**
485
- * {{> dontSee }}
486
- */
487
- dontSee(text, context = null) {
488
- return proceedSee.call(this, 'negate', text, context);
489
- }
490
-
491
- /**
492
- * {{> seeElement }}
493
- */
494
- async seeElement(locator) {
495
- locator = new Locator(locator, 'css');
496
- const num = await this.browser.evaluate((by, locator) => {
497
- return window.codeceptjs.findElements(by, locator).filter(e => e.offsetWidth > 0 && e.offsetHeight > 0).length;
498
- }, locator.type, locator.value);
499
- equals('number of elements on a page').negate(0, num);
500
- }
501
-
502
- /**
503
- * {{> dontSeeElement }}
504
- */
505
- async dontSeeElement(locator) {
506
- locator = new Locator(locator, 'css');
507
- locator = new Locator(locator, 'css');
508
- const num = await this.browser.evaluate((by, locator) => {
509
- return window.codeceptjs.findElements(by, locator).filter(e => e.offsetWidth > 0 && e.offsetHeight > 0).length;
510
- }, locator.type, locator.value);
511
- equals('number of elements on a page').assert(0, num);
512
- }
513
-
514
- /**
515
- * {{> seeElementInDOM }}
516
- */
517
- async seeElementInDOM(locator) {
518
- locator = new Locator(locator, 'css');
519
- const els = await this.browser.findElements(locator.toStrict());
520
- empty('elements').negate(els.fill('ELEMENT'));
521
- }
522
-
523
- /**
524
- * {{> dontSeeElementInDOM }}
525
- */
526
- async dontSeeElementInDOM(locator) {
527
- locator = new Locator(locator, 'css');
528
- const els = await this.browser.findElements(locator.toStrict());
529
- empty('elements').assert(els.fill('ELEMENT'));
530
- }
531
-
532
- /**
533
- * {{> seeInSource }}
534
- */
535
- async seeInSource(text) {
536
- const source = await this.browser.evaluate(() => document.documentElement.outerHTML);
537
- stringIncludes('HTML source of a page').assert(text, source);
538
- }
539
-
540
- /**
541
- * {{> dontSeeInSource }}
542
- */
543
- async dontSeeInSource(text) {
544
- const source = await this.browser.evaluate(() => document.documentElement.outerHTML);
545
- stringIncludes('HTML source of a page').negate(text, source);
546
- }
547
-
548
- /**
549
- * {{> seeNumberOfElements }}
550
- */
551
- async seeNumberOfElements(locator, num) {
552
- const elements = await this._locate(locator);
553
- return equals(`expected number of elements (${(new Locator(locator))}) is ${num}, but found ${elements.length}`).assert(elements.length, num);
554
- }
555
-
556
- /**
557
- * {{> seeNumberOfVisibleElements }}
558
- */
559
- async seeNumberOfVisibleElements(locator, num) {
560
- const res = await this.grabNumberOfVisibleElements(locator);
561
- return equals(`expected number of visible elements (${(new Locator(locator))}) is ${num}, but found ${res}`).assert(res, num);
562
- }
563
-
564
- /**
565
- * {{> grabNumberOfVisibleElements }}
566
- */
567
- async grabNumberOfVisibleElements(locator) {
568
- locator = new Locator(locator, 'css');
569
-
570
- const num = await this.browser.evaluate((by, locator) => {
571
- return window.codeceptjs.findElements(by, locator)
572
- .filter(e => e.offsetWidth > 0 && e.offsetHeight > 0).length;
573
- }, locator.type, locator.value);
574
-
575
- return num;
576
- }
577
-
578
- /**
579
- * {{> click }}
580
- */
581
- async click(locator, context = null) {
582
- const el = await findClickable.call(this, locator, context);
583
- assertElementExists(el, locator, 'Clickable');
584
- return this.browser.evaluate(el => window.codeceptjs.clickEl(el), el)
585
- .wait(this.options.waitForAction);
586
- }
587
-
588
- /**
589
- * {{> doubleClick }}
590
- */
591
- async doubleClick(locator, context = null) {
592
- const el = await findClickable.call(this, locator, context);
593
- assertElementExists(el, locator, 'Clickable');
594
- return this.browser.evaluate(el => window.codeceptjs.doubleClickEl(el), el)
595
- .wait(this.options.waitForAction);
596
- }
597
-
598
- /**
599
- * {{> rightClick }}
600
- */
601
- async rightClick(locator, context = null) {
602
- const el = await findClickable.call(this, locator, context);
603
- assertElementExists(el, locator, 'Clickable');
604
- return this.browser.evaluate(el => window.codeceptjs.rightClickEl(el), el)
605
- .wait(this.options.waitForAction);
606
- }
607
-
608
- /**
609
- * {{> moveCursorTo }}
610
- */
611
- async moveCursorTo(locator, offsetX = 0, offsetY = 0) {
612
- locator = new Locator(locator, 'css');
613
- const el = await this.browser.findElement(locator.toStrict());
614
- assertElementExists(el, locator);
615
- return this.browser.evaluate((el, x, y) => window.codeceptjs.hoverEl(el, x, y), el, offsetX, offsetY)
616
- .wait(this.options.waitForAction); // wait for hover event to happen
617
- }
618
-
619
- /**
620
- * {{> executeScript }}
621
- *
622
- * Wrapper for synchronous [evaluate](https://github.com/segmentio/nightmare#evaluatefn-arg1-arg2)
623
- */
624
- async executeScript(...args) {
625
- return this.browser.evaluate.apply(this.browser, args)
626
- .catch(err => err); // Nightmare's first argument is error :(
627
- }
628
-
629
- /**
630
- * {{> executeAsyncScript }}
631
- *
632
- * Wrapper for asynchronous [evaluate](https://github.com/segmentio/nightmare#evaluatefn-arg1-arg2).
633
- * Unlike NightmareJS implementation calling `done` will return its first argument.
634
- */
635
- async executeAsyncScript(...args) {
636
- return this.browser.evaluate.apply(this.browser, args)
637
- .catch(err => err); // Nightmare's first argument is error :(
638
- }
639
-
640
- /**
641
- * {{> resizeWindow }}
642
- */
643
- async resizeWindow(width, height) {
644
- if (width === 'maximize') {
645
- throw new Error('Nightmare doesn\'t support resizeWindow to maximum!');
646
- }
647
- return this.browser.viewport(width, height).wait(this.options.waitForAction);
648
- }
649
-
650
- /**
651
- * {{> checkOption }}
652
- */
653
- async checkOption(field, context = null) {
654
- const els = await findCheckable.call(this, field, context);
655
- assertElementExists(els[0], field, 'Checkbox or radio');
656
- return this.browser.evaluate(els => window.codeceptjs.checkEl(els[0]), els)
657
- .wait(this.options.waitForAction);
658
- }
659
-
660
- /**
661
- * {{> uncheckOption }}
662
- */
663
- async uncheckOption(field, context = null) {
664
- const els = await findCheckable.call(this, field, context);
665
- assertElementExists(els[0], field, 'Checkbox or radio');
666
- return this.browser.evaluate(els => window.codeceptjs.unCheckEl(els[0]), els)
667
- .wait(this.options.waitForAction);
668
- }
669
-
670
- /**
671
- * {{> fillField }}
672
- */
673
- async fillField(field, value) {
674
- const el = await findField.call(this, field);
675
- assertElementExists(el, field, 'Field');
676
- return this.browser.enterText(el, value.toString(), true)
677
- .wait(this.options.waitForAction);
678
- }
679
-
680
- /**
681
- * {{> clearField }}
682
- */
683
- async clearField(field) {
684
- return this.fillField(field, '');
685
- }
686
-
687
- /**
688
- * {{> appendField }}
689
- */
690
- async appendField(field, value) {
691
- const el = await findField.call(this, field);
692
- assertElementExists(el, field, 'Field');
693
- return this.browser.enterText(el, value.toString(), false)
694
- .wait(this.options.waitForAction);
695
- }
696
-
697
- /**
698
- * {{> seeInField }}
699
- */
700
- async seeInField(field, value) {
701
- const _value = (typeof value === 'boolean') ? value : value.toString();
702
- return proceedSeeInField.call(this, 'assert', field, _value);
703
- }
704
-
705
- /**
706
- * {{> dontSeeInField }}
707
- */
708
- async dontSeeInField(field, value) {
709
- const _value = (typeof value === 'boolean') ? value : value.toString();
710
- return proceedSeeInField.call(this, 'negate', field, _value);
711
- }
712
-
713
- /**
714
- * Sends [input event](http://electron.atom.io/docs/api/web-contents/#webcontentssendinputeventevent) on a page.
715
- * Can submit special keys like 'Enter', 'Backspace', etc
716
- */
717
- async pressKey(key) {
718
- if (Array.isArray(key)) {
719
- key = key.join('+'); // should work with accelerators...
720
- }
721
- if (Object.keys(specialKeys).indexOf(key) >= 0) {
722
- key = specialKeys[key];
723
- }
724
- return this.browser.pressKey(key).wait(this.options.waitForAction);
725
- }
726
-
727
- /**
728
- * Sends [input event](http://electron.atom.io/docs/api/web-contents/#contentssendinputeventevent) on a page.
729
- * Should be a mouse event like:
730
- * {
731
- type: 'mouseDown',
732
- x: args.x,
733
- y: args.y,
734
- button: "left"
735
- }
736
- */
737
- async triggerMouseEvent(event) {
738
- return this.browser.triggerMouseEvent(event).wait(this.options.waitForAction);
739
- }
740
-
741
- /**
742
- * {{> seeCheckboxIsChecked }}
743
- */
744
- async seeCheckboxIsChecked(field) {
745
- return proceedIsChecked.call(this, 'assert', field);
746
- }
747
-
748
- /**
749
- * {{> dontSeeCheckboxIsChecked }}
750
- */
751
- async dontSeeCheckboxIsChecked(field) {
752
- return proceedIsChecked.call(this, 'negate', field);
753
- }
754
-
755
- /**
756
- * {{> attachFile }}
757
- *
758
- * 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))
759
- */
760
- async attachFile(locator, pathToFile) {
761
- const file = path.join(global.codecept_dir, pathToFile);
762
-
763
- locator = new Locator(locator, 'css');
764
- if (!locator.isCSS()) {
765
- throw new Error('Only CSS locator allowed for attachFile in Nightmare helper');
766
- }
767
-
768
- if (!fileExists(file)) {
769
- throw new Error(`File at ${file} can not be found on local system`);
770
- }
771
- return this.browser.upload(locator.value, file);
772
- }
773
-
774
- /**
775
- * {{> grabTextFromAll }}
776
- */
777
- async grabTextFromAll(locator) {
778
- locator = new Locator(locator, 'css');
779
- const els = await this.browser.findElements(locator.toStrict());
780
- const texts = [];
781
- const getText = el => window.codeceptjs.fetchElement(el).innerText;
782
- for (const el of els) {
783
- texts.push(await this.browser.evaluate(getText, el));
784
- }
785
- return texts;
786
- }
787
-
788
- /**
789
- * {{> grabTextFrom }}
790
- */
791
- async grabTextFrom(locator) {
792
- locator = new Locator(locator, 'css');
793
- const els = await this.browser.findElement(locator.toStrict());
794
- assertElementExists(els, locator);
795
- const texts = await this.grabTextFromAll(locator);
796
- if (texts.length > 1) {
797
- this.debugSection('GrabText', `Using first element out of ${texts.length}`);
798
- }
799
-
800
- return texts[0];
801
- }
802
-
803
- /**
804
- * {{> grabValueFromAll }}
805
- */
806
- async grabValueFromAll(locator) {
807
- locator = new Locator(locator, 'css');
808
- const els = await this.browser.findElements(locator.toStrict());
809
- const values = [];
810
- const getValues = el => window.codeceptjs.fetchElement(el).value;
811
- for (const el of els) {
812
- values.push(await this.browser.evaluate(getValues, el));
813
- }
814
-
815
- return values;
816
- }
817
-
818
- /**
819
- * {{> grabValueFrom }}
820
- */
821
- async grabValueFrom(locator) {
822
- const el = await findField.call(this, locator);
823
- assertElementExists(el, locator, 'Field');
824
- const values = await this.grabValueFromAll(locator);
825
- if (values.length > 1) {
826
- this.debugSection('GrabValue', `Using first element out of ${values.length}`);
827
- }
828
-
829
- return values[0];
830
- }
831
-
832
- /**
833
- * {{> grabAttributeFromAll }}
834
- */
835
- async grabAttributeFromAll(locator, attr) {
836
- locator = new Locator(locator, 'css');
837
- const els = await this.browser.findElements(locator.toStrict());
838
- const array = [];
839
-
840
- for (let index = 0; index < els.length; index++) {
841
- const el = els[index];
842
- array.push(await this.browser.evaluate((el, attr) => window.codeceptjs.fetchElement(el).getAttribute(attr), el, attr));
843
- }
844
-
845
- return array;
846
- }
847
-
848
- /**
849
- * {{> grabAttributeFrom }}
850
- */
851
- async grabAttributeFrom(locator, attr) {
852
- locator = new Locator(locator, 'css');
853
- const els = await this.browser.findElement(locator.toStrict());
854
- assertElementExists(els, locator);
855
-
856
- const attrs = await this.grabAttributeFromAll(locator, attr);
857
- if (attrs.length > 1) {
858
- this.debugSection('GrabAttribute', `Using first element out of ${attrs.length}`);
859
- }
860
-
861
- return attrs[0];
862
- }
863
-
864
- /**
865
- * {{> grabHTMLFromAll }}
866
- */
867
- async grabHTMLFromAll(locator) {
868
- locator = new Locator(locator, 'css');
869
- const els = await this.browser.findElements(locator.toStrict());
870
- const array = [];
871
-
872
- for (let index = 0; index < els.length; index++) {
873
- const el = els[index];
874
- array.push(await this.browser.evaluate(el => window.codeceptjs.fetchElement(el).innerHTML, el));
875
- }
876
- this.debugSection('GrabHTML', array);
877
-
878
- return array;
879
- }
880
-
881
- /**
882
- * {{> grabHTMLFrom }}
883
- */
884
- async grabHTMLFrom(locator) {
885
- locator = new Locator(locator, 'css');
886
- const els = await this.browser.findElement(locator.toStrict());
887
- assertElementExists(els, locator);
888
- const html = await this.grabHTMLFromAll(locator);
889
- if (html.length > 1) {
890
- this.debugSection('GrabHTML', `Using first element out of ${html.length}`);
891
- }
892
-
893
- return html[0];
894
- }
895
-
896
- /**
897
- * {{> grabCssPropertyFrom }}
898
- */
899
- async grabCssPropertyFrom(locator, cssProperty) {
900
- locator = new Locator(locator, 'css');
901
- const els = await this.browser.findElements(locator.toStrict());
902
- const array = [];
903
-
904
- const getCssPropForElement = async (el, prop) => {
905
- return (await this.browser.evaluate((el) => {
906
- return window.getComputedStyle(window.codeceptjs.fetchElement(el));
907
- }, el))[toCamelCase(prop)];
908
- };
909
-
910
- for (const el of els) {
911
- assertElementExists(el, locator);
912
- const cssValue = await getCssPropForElement(el, cssProperty);
913
- array.push(cssValue);
914
- }
915
- this.debugSection('HTML', array);
916
-
917
- return array.length > 1 ? array : array[0];
918
- }
919
-
920
- _injectClientScripts() {
921
- return this.browser.inject('js', path.join(__dirname, 'clientscripts', 'nightmare.js'));
922
- }
923
-
924
- /**
925
- * {{> selectOption }}
926
- */
927
- async selectOption(select, option) {
928
- const fetchAndCheckOption = function (el, locator) {
929
- el = window.codeceptjs.fetchElement(el);
930
- const found = document.evaluate(locator, el, null, 5, null);
931
- let current = null;
932
- const items = [];
933
- while (current = found.iterateNext()) {
934
- items.push(current);
935
- }
936
- for (let i = 0; i < items.length; i++) {
937
- current = items[i];
938
- if (current instanceof HTMLOptionElement) {
939
- current.selected = true;
940
- if (!el.multiple) el.value = current.value;
941
- }
942
- const event = document.createEvent('HTMLEvents');
943
- event.initEvent('change', true, true);
944
- el.dispatchEvent(event);
945
- }
946
- return !!current;
947
- };
948
-
949
- const el = await findField.call(this, select);
950
- assertElementExists(el, select, 'Selectable field');
951
- if (!Array.isArray(option)) {
952
- option = [option];
953
- }
954
-
955
- for (const key in option) {
956
- const opt = xpathLocator.literal(option[key]);
957
- const checked = await this.browser.evaluate(fetchAndCheckOption, el, Locator.select.byVisibleText(opt));
958
-
959
- if (!checked) {
960
- await this.browser.evaluate(fetchAndCheckOption, el, Locator.select.byValue(opt));
961
- }
962
- }
963
- return this.browser.wait(this.options.waitForAction);
964
- }
965
-
966
- /**
967
- * {{> setCookie }}
968
- *
969
- * Wrapper for `.cookies.set(cookie)`.
970
- * [See more](https://github.com/segmentio/nightmare/blob/master/Readme.md#cookiessetcookie)
971
- */
972
- async setCookie(cookie) {
973
- return this.browser.cookies.set(cookie);
974
- }
975
-
976
- /**
977
- * {{> seeCookie }}
978
- *
979
- */
980
- async seeCookie(name) {
981
- const res = await this.browser.cookies.get(name);
982
- truth(`cookie ${name}`, 'to be set').assert(res);
983
- }
984
-
985
- /**
986
- * {{> dontSeeCookie }}
987
- */
988
- async dontSeeCookie(name) {
989
- const res = await this.browser.cookies.get(name);
990
- truth(`cookie ${name}`, 'to be set').negate(res);
991
- }
992
-
993
- /**
994
- * {{> grabCookie }}
995
- *
996
- * Cookie in JSON format. If name not passed returns all cookies for this domain.
997
- *
998
- * 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 }).`
999
- */
1000
- async grabCookie(name) {
1001
- return this.browser.cookies.get(name);
1002
- }
1003
-
1004
- /**
1005
- * {{> clearCookie }}
1006
- */
1007
- async clearCookie(cookie) {
1008
- if (!cookie) {
1009
- return this.browser.cookies.clearAll();
1010
- }
1011
- return this.browser.cookies.clear(cookie);
1012
- }
1013
-
1014
- /**
1015
- * {{> waitForFunction }}
1016
- */
1017
- async waitForFunction(fn, argsOrSec = null, sec = null) {
1018
- let args = [];
1019
- if (argsOrSec) {
1020
- if (Array.isArray(argsOrSec)) {
1021
- args = argsOrSec;
1022
- } else if (typeof argsOrSec === 'number') {
1023
- sec = argsOrSec;
1024
- }
1025
- }
1026
- this.browser.options.waitTimeout = sec ? sec * 1000 : this.options.waitForTimeout;
1027
- return this.browser.wait(fn, ...args);
1028
- }
1029
-
1030
- /**
1031
- * {{> wait }}
1032
- */
1033
- async wait(sec) {
1034
- return new Promise(((done) => {
1035
- setTimeout(done, sec * 1000);
1036
- }));
1037
- }
1038
-
1039
- /**
1040
- * {{> waitForText }}
1041
- */
1042
- async waitForText(text, sec, context = null) {
1043
- if (!context) {
1044
- context = this.context;
1045
- }
1046
- const locator = new Locator(context, 'css');
1047
- this.browser.options.waitTimeout = sec ? sec * 1000 : this.options.waitForTimeout;
1048
- return this.browser.wait((by, locator, text) => {
1049
- return window.codeceptjs.findElement(by, locator).innerText.indexOf(text) > -1;
1050
- }, locator.type, locator.value, text).catch((err) => {
1051
- if (err.message.indexOf('Cannot read property') > -1) {
1052
- throw new Error(`element (${JSON.stringify(context)}) is not in DOM. Unable to wait text.`);
1053
- } else if (err.message && err.message.indexOf('.wait() timed out after') > -1) {
1054
- throw new Error(`there is no element(${JSON.stringify(context)}) with text "${text}" after ${sec} sec`);
1055
- } else throw err;
1056
- });
1057
- }
1058
-
1059
- /**
1060
- * {{> waitForVisible }}
1061
- */
1062
- waitForVisible(locator, sec) {
1063
- this.browser.options.waitTimeout = sec ? sec * 1000 : this.options.waitForTimeout;
1064
- locator = new Locator(locator, 'css');
1065
-
1066
- return this.browser.wait((by, locator) => {
1067
- const el = window.codeceptjs.findElement(by, locator);
1068
- if (!el) return false;
1069
- return el.offsetWidth > 0 && el.offsetHeight > 0;
1070
- }, locator.type, locator.value).catch((err) => {
1071
- if (err.message && err.message.indexOf('.wait() timed out after') > -1) {
1072
- throw new Error(`element (${JSON.stringify(locator)}) still not visible on page after ${sec} sec`);
1073
- } else throw err;
1074
- });
1075
- }
1076
-
1077
- /**
1078
- * {{> waitToHide }}
1079
- */
1080
- async waitToHide(locator, sec = null) {
1081
- return this.waitForInvisible(locator, sec);
1082
- }
1083
-
1084
- /**
1085
- * {{> waitForInvisible }}
1086
- */
1087
- waitForInvisible(locator, sec) {
1088
- this.browser.options.waitTimeout = sec ? sec * 1000 : this.options.waitForTimeout;
1089
- locator = new Locator(locator, 'css');
1090
-
1091
- return this.browser.wait((by, locator) => {
1092
- const el = window.codeceptjs.findElement(by, locator);
1093
- if (!el) return true;
1094
- return !(el.offsetWidth > 0 && el.offsetHeight > 0);
1095
- }, locator.type, locator.value).catch((err) => {
1096
- if (err.message && err.message.indexOf('.wait() timed out after') > -1) {
1097
- throw new Error(`element (${JSON.stringify(locator)}) still visible after ${sec} sec`);
1098
- } else throw err;
1099
- });
1100
- }
1101
-
1102
- /**
1103
- * {{> waitForElement }}
1104
- */
1105
- async waitForElement(locator, sec) {
1106
- this.browser.options.waitTimeout = sec ? sec * 1000 : this.options.waitForTimeout;
1107
- locator = new Locator(locator, 'css');
1108
-
1109
- return this.browser.wait((by, locator) => window.codeceptjs.findElement(by, locator) !== null, locator.type, locator.value).catch((err) => {
1110
- if (err.message && err.message.indexOf('.wait() timed out after') > -1) {
1111
- throw new Error(`element (${JSON.stringify(locator)}) still not present on page after ${sec} sec`);
1112
- } else throw err;
1113
- });
1114
- }
1115
-
1116
- async waitUntilExists(locator, sec) {
1117
- console.log(`waitUntilExists deprecated:
1118
- * use 'waitForElement' to wait for element to be attached
1119
- * use 'waitForDetached to wait for element to be removed'`);
1120
- return this.waitForDetached(locator, sec);
1121
- }
1122
-
1123
- /**
1124
- * {{> waitForDetached }}
1125
- */
1126
- async waitForDetached(locator, sec) {
1127
- this.browser.options.waitTimeout = sec ? sec * 1000 : this.options.waitForTimeout;
1128
- sec = this.browser.options.waitForTimeout / 1000;
1129
- locator = new Locator(locator, 'css');
1130
-
1131
- return this.browser.wait((by, locator) => window.codeceptjs.findElement(by, locator) === null, locator.type, locator.value).catch((err) => {
1132
- if (err.message && err.message.indexOf('.wait() timed out after') > -1) {
1133
- throw new Error(`element (${JSON.stringify(locator)}) still on page after ${sec} sec`);
1134
- } else throw err;
1135
- });
1136
- }
1137
-
1138
- /**
1139
- * {{> refreshPage }}
1140
- */
1141
- async refreshPage() {
1142
- return this.browser.refresh();
1143
- }
1144
-
1145
- /**
1146
- * Reload the page
1147
- */
1148
- refresh() {
1149
- console.log('Deprecated in favor of refreshPage');
1150
- return this.browser.refresh();
1151
- }
1152
-
1153
- /**
1154
- * {{> saveElementScreenshot }}
1155
- *
1156
- */
1157
- async saveElementScreenshot(locator, fileName) {
1158
- const outputFile = screenshotOutputFolder(fileName);
1159
-
1160
- const rect = await this.grabElementBoundingRect(locator);
1161
-
1162
- const button_clip = {
1163
- x: Math.floor(rect.x),
1164
- y: Math.floor(rect.y),
1165
- width: Math.floor(rect.width),
1166
- height: Math.floor(rect.height),
1167
- };
1168
-
1169
- this.debug(`Screenshot of ${(new Locator(locator))} element has been saved to ${outputFile}`);
1170
- // take the screenshot
1171
- await this.browser.screenshot(outputFile, button_clip);
1172
- }
1173
-
1174
- /**
1175
- * {{> grabElementBoundingRect }}
1176
- */
1177
- async grabElementBoundingRect(locator, prop) {
1178
- locator = new Locator(locator, 'css');
1179
-
1180
- const rect = await this.browser.evaluate(async (by, locator) => {
1181
- // store the button in a variable
1182
-
1183
- const build_cluster_btn = await window.codeceptjs.findElement(by, locator);
1184
-
1185
- // use the getClientRects() function on the button to determine
1186
- // the size and location
1187
- const rect = build_cluster_btn.getBoundingClientRect();
1188
-
1189
- // convert the rectangle to a clip object and return it
1190
- return {
1191
- x: rect.left,
1192
- y: rect.top,
1193
- width: rect.width,
1194
- height: rect.height,
1195
- };
1196
- }, locator.type, locator.value);
1197
-
1198
- if (prop) return rect[prop];
1199
- return rect;
1200
- }
1201
-
1202
- /**
1203
- * {{> saveScreenshot }}
1204
- */
1205
- async saveScreenshot(fileName, fullPage = this.options.fullPageScreenshots) {
1206
- const outputFile = screenshotOutputFolder(fileName);
1207
-
1208
- this.debug(`Screenshot is saving to ${outputFile}`);
1209
-
1210
- if (!fullPage) {
1211
- return this.browser.screenshot(outputFile);
1212
- }
1213
- const { height, width } = await this.browser.evaluate(() => {
1214
- return { height: document.body.scrollHeight, width: document.body.scrollWidth };
1215
- });
1216
- await this.browser.viewport(width, height);
1217
- return this.browser.screenshot(outputFile);
1218
- }
1219
-
1220
- async _failed() {
1221
- if (withinStatus !== false) await this._withinEnd();
1222
- }
1223
-
1224
- /**
1225
- * {{> scrollTo }}
1226
- */
1227
- async scrollTo(locator, offsetX = 0, offsetY = 0) {
1228
- if (typeof locator === 'number' && typeof offsetX === 'number') {
1229
- offsetY = offsetX;
1230
- offsetX = locator;
1231
- locator = null;
1232
- }
1233
- if (locator) {
1234
- locator = new Locator(locator, 'css');
1235
- return this.browser.evaluate((by, locator, offsetX, offsetY) => {
1236
- const el = window.codeceptjs.findElement(by, locator);
1237
- if (!el) throw new Error(`Element not found ${by}: ${locator}`);
1238
- const rect = el.getBoundingClientRect();
1239
- window.scrollTo(rect.left + offsetX, rect.top + offsetY);
1240
- }, locator.type, locator.value, offsetX, offsetY);
1241
- }
1242
- // eslint-disable-next-line prefer-arrow-callback
1243
- return this.executeScript(function (x, y) { return window.scrollTo(x, y); }, offsetX, offsetY);
1244
- }
1245
-
1246
- /**
1247
- * {{> scrollPageToTop }}
1248
- */
1249
- async scrollPageToTop() {
1250
- return this.executeScript(() => window.scrollTo(0, 0));
1251
- }
1252
-
1253
- /**
1254
- * {{> scrollPageToBottom }}
1255
- */
1256
- async scrollPageToBottom() {
1257
- /* eslint-disable prefer-arrow-callback, comma-dangle */
1258
- return this.executeScript(function () {
1259
- const body = document.body;
1260
- const html = document.documentElement;
1261
- window.scrollTo(0, Math.max(
1262
- body.scrollHeight,
1263
- body.offsetHeight,
1264
- html.clientHeight,
1265
- html.scrollHeight,
1266
- html.offsetHeight
1267
- ));
1268
- });
1269
- /* eslint-enable */
1270
- }
1271
-
1272
- /**
1273
- * {{> grabPageScrollPosition }}
1274
- */
1275
- async grabPageScrollPosition() {
1276
- /* eslint-disable comma-dangle */
1277
- function getScrollPosition() {
1278
- return {
1279
- x: window.pageXOffset,
1280
- y: window.pageYOffset
1281
- };
1282
- }
1283
- /* eslint-enable comma-dangle */
1284
- return this.executeScript(getScrollPosition);
1285
- }
1286
- }
1287
-
1288
- export default Nightmare;
1289
-
1290
- async function proceedSee(assertType, text, context) {
1291
- let description;
1292
- let locator;
1293
- if (!context) {
1294
- if (this.context === this.options.rootElement) {
1295
- locator = new Locator(this.context, 'css');
1296
- description = 'web application';
1297
- } else {
1298
- description = `current context ${this.context}`;
1299
- locator = new Locator({ xpath: './/*' });
1300
- }
1301
- } else {
1302
- locator = new Locator(context, 'css');
1303
- description = `element ${locator.toString()}`;
1304
- }
1305
-
1306
- const texts = await this.browser.evaluate((by, locator) => {
1307
- return window.codeceptjs.findElements(by, locator).map(el => el.innerText);
1308
- }, locator.type, locator.value);
1309
- const allText = texts.join(' | ');
1310
- return stringIncludes(description)[assertType](text, allText);
1311
- }
1312
-
1313
- async function proceedSeeInField(assertType, field, value) {
1314
- const el = await findField.call(this, field);
1315
- assertElementExists(el, field, 'Field');
1316
- const tag = await this.browser.evaluate(el => window.codeceptjs.fetchElement(el).tagName, el);
1317
- const fieldVal = await this.browser.evaluate(el => window.codeceptjs.fetchElement(el).value, el);
1318
- if (tag === 'select') {
1319
- // locate option by values and check them
1320
- const text = await this.browser.evaluate((el, val) => {
1321
- return el.querySelector(`option[value="${val}"]`).innerText;
1322
- }, el, xpathLocator.literal(fieldVal));
1323
- return equals(`select option by ${field}`)[assertType](value, text);
1324
- }
1325
- return stringIncludes(`field by ${field}`)[assertType](value, fieldVal);
1326
- }
1327
-
1328
- async function proceedIsChecked(assertType, option) {
1329
- const els = await findCheckable.call(this, option);
1330
- assertElementExists(els, option, 'Checkable');
1331
- const selected = await this.browser.evaluate((els) => {
1332
- return els.map(el => window.codeceptjs.fetchElement(el).checked).reduce((prev, cur) => prev || cur);
1333
- }, els);
1334
- return truth(`checkable ${option}`, 'to be checked')[assertType](selected);
1335
- }
1336
-
1337
- async function findCheckable(locator, context) {
1338
- let contextEl = null;
1339
- if (context) {
1340
- contextEl = await this.browser.findElement((new Locator(context, 'css')).toStrict());
1341
- }
1342
-
1343
- const matchedLocator = new Locator(locator);
1344
- if (!matchedLocator.isFuzzy()) {
1345
- return this.browser.findElements(matchedLocator.toStrict(), contextEl);
1346
- }
1347
-
1348
- const literal = xpathLocator.literal(locator);
1349
- let els = await this.browser.findElements({ xpath: Locator.checkable.byText(literal) }, contextEl);
1350
- if (els.length) {
1351
- return els;
1352
- }
1353
- els = await this.browser.findElements({ xpath: Locator.checkable.byName(literal) }, contextEl);
1354
- if (els.length) {
1355
- return els;
1356
- }
1357
- return this.browser.findElements({ css: locator }, contextEl);
1358
- }
1359
-
1360
- async function findClickable(locator, context) {
1361
- let contextEl = null;
1362
- if (context) {
1363
- contextEl = await this.browser.findElement((new Locator(context, 'css')).toStrict());
1364
- }
1365
-
1366
- const matchedLocator = new Locator(locator);
1367
- if (!matchedLocator.isFuzzy()) {
1368
- return this.browser.findElement(matchedLocator.toStrict(), contextEl);
1369
- }
1370
-
1371
- const literal = xpathLocator.literal(locator);
1372
-
1373
- let els = await this.browser.findElements({ xpath: Locator.clickable.narrow(literal) }, contextEl);
1374
- if (els.length) {
1375
- return els[0];
1376
- }
1377
-
1378
- els = await this.browser.findElements({ xpath: Locator.clickable.wide(literal) }, contextEl);
1379
- if (els.length) {
1380
- return els[0];
1381
- }
1382
-
1383
- return this.browser.findElement({ css: locator }, contextEl);
1384
- }
1385
-
1386
- async function findField(locator) {
1387
- const matchedLocator = new Locator(locator);
1388
- if (!matchedLocator.isFuzzy()) {
1389
- return this.browser.findElements(matchedLocator.toStrict());
1390
- }
1391
- const literal = xpathLocator.literal(locator);
1392
-
1393
- let els = await this.browser.findElements({ xpath: Locator.field.labelEquals(literal) });
1394
- if (els.length) {
1395
- return els[0];
1396
- }
1397
-
1398
- els = await this.browser.findElements({ xpath: Locator.field.labelContains(literal) });
1399
- if (els.length) {
1400
- return els[0];
1401
- }
1402
- els = await this.browser.findElements({ xpath: Locator.field.byName(literal) });
1403
- if (els.length) {
1404
- return els[0];
1405
- }
1406
- return this.browser.findElement({ css: locator });
1407
- }
1408
-
1409
- function assertElementExists(el, locator, prefix, suffix) {
1410
- if (el === null) throw new ElementNotFound(locator, prefix, suffix);
1411
- }