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