codeceptjs 4.0.0-beta.5 → 4.0.0-beta.7.esm-aria

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