codeceptjs 4.0.0-beta.5 → 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 (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 +191 -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 +63 -57
  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 +11 -2
  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,1391 +0,0 @@
1
- // @ts-nocheck
2
- const fs = require('fs')
3
- const assert = require('assert')
4
- const path = require('path')
5
- const qrcode = require('qrcode-terminal')
6
- const createTestCafe = require('testcafe')
7
- const { Selector, ClientFunction } = require('testcafe')
8
-
9
- const Helper = require('@codeceptjs/helper')
10
- const ElementNotFound = require('./errors/ElementNotFound')
11
- const testControllerHolder = require('./testcafe/testControllerHolder')
12
- const { mapError, createTestFile, createClientFunction } = require('./testcafe/testcafe-utils')
13
-
14
- const stringIncludes = require('../assert/include').includes
15
- const { urlEquals } = require('../assert/equal')
16
- const { empty } = require('../assert/empty')
17
- const { truth } = require('../assert/truth')
18
- const { xpathLocator, normalizeSpacesInString } = require('../utils')
19
- const Locator = require('../locator')
20
-
21
- /**
22
- * Client Functions
23
- */
24
- const getPageUrl = t => ClientFunction(() => document.location.href).with({ boundTestRun: t })
25
- const getHtmlSource = t => ClientFunction(() => document.getElementsByTagName('html')[0].innerHTML).with({ boundTestRun: t })
26
-
27
- /**
28
- * Uses [TestCafe](https://github.com/DevExpress/testcafe) library to run cross-browser tests.
29
- * The browser version you want to use in tests must be installed on your system.
30
- *
31
- * Requires `testcafe` package to be installed.
32
- *
33
- * ```
34
- * npm i testcafe --save-dev
35
- * ```
36
- *
37
- * ## Configuration
38
- *
39
- * This helper should be configured in codecept.conf.ts or codecept.conf.js
40
- *
41
- * * `url`: base url of website to be tested
42
- * * `show`: (optional, default: false) - show browser window.
43
- * * `windowSize`: (optional) - set browser window width and height
44
- * * `getPageTimeout` (optional, default: '30000') config option to set maximum navigation time in milliseconds.
45
- * * `waitForTimeout`: (optional) default wait* timeout in ms. Default: 5000.
46
- * * `browser`: (optional, default: chrome) - See https://devexpress.github.io/testcafe/documentation/using-testcafe/common-concepts/browsers/browser-support.html
47
- *
48
- *
49
- * #### Example #1: Show chrome browser window
50
- *
51
- * ```js
52
- * {
53
- * helpers: {
54
- * TestCafe : {
55
- * url: "http://localhost",
56
- * waitForTimeout: 15000,
57
- * show: true,
58
- * browser: "chrome"
59
- * }
60
- * }
61
- * }
62
- * ```
63
- *
64
- * To use remote device you can provide 'remote' as browser parameter this will display a link with QR Code
65
- * See https://devexpress.github.io/testcafe/documentation/recipes/test-on-remote-computers-and-mobile-devices.html
66
- * #### Example #2: Remote browser connection
67
- *
68
- * ```js
69
- * {
70
- * helpers: {
71
- * TestCafe : {
72
- * url: "http://localhost",
73
- * waitForTimeout: 15000,
74
- * browser: "remote"
75
- * }
76
- * }
77
- * }
78
- * ```
79
- *
80
- * ## Access From Helpers
81
- *
82
- * Call Testcafe methods directly using the testcafe controller.
83
- *
84
- * ```js
85
- * const testcafeTestController = this.helpers['TestCafe'].t;
86
- * const comboBox = Selector('.combo-box');
87
- * await testcafeTestController
88
- * .hover(comboBox) // hover over combo box
89
- * .click('#i-prefer-both') // click some other element
90
- * ```
91
- *
92
- * ## Methods
93
- */
94
- class TestCafe extends Helper {
95
- constructor(config) {
96
- super(config)
97
-
98
- this.testcafe = undefined // testcafe instance
99
- this.t = undefined // testcafe test controller
100
- this.dummyTestcafeFile // generated testcafe test file
101
-
102
- // context is used for within() function.
103
- // It requires to have _withinBeginand _withinEnd implemented.
104
- // Inside _withinBegin we should define that all next element calls should be started from a specific element (this.context).
105
- this.context = undefined // TODO Not sure if this applies to testcafe
106
-
107
- this.options = {
108
- url: 'http://localhost',
109
- show: false,
110
- browser: 'chrome',
111
- restart: true, // TODO Test if restart false works
112
- manualStart: false,
113
- keepBrowserState: false,
114
- waitForTimeout: 5000,
115
- getPageTimeout: 30000,
116
- fullPageScreenshots: false,
117
- disableScreenshots: false,
118
- windowSize: undefined,
119
- ...config,
120
- }
121
- }
122
-
123
- // TOOD Do a requirements check
124
- static _checkRequirements() {
125
- try {
126
- require('testcafe')
127
- } catch (e) {
128
- return ['testcafe@^1.1.0']
129
- }
130
- }
131
-
132
- static _config() {
133
- return [
134
- { name: 'url', message: 'Base url of site to be tested', default: 'http://localhost' },
135
- { name: 'browser', message: 'Browser to be used', default: 'chrome' },
136
- {
137
- name: 'show',
138
- message: 'Show browser window',
139
- default: true,
140
- type: 'confirm',
141
- },
142
- ]
143
- }
144
-
145
- async _configureAndStartBrowser() {
146
- this.dummyTestcafeFile = createTestFile(global.output_dir) // create a dummy test file to get hold of the test controller
147
-
148
- this.iteration += 2 // Use different ports for each test run
149
- // @ts-ignore
150
- this.testcafe = await createTestCafe('', null, null)
151
-
152
- this.debugSection('_before', 'Starting testcafe browser...')
153
-
154
- this.isRunning = true
155
-
156
- // TODO Do we have to cleanup the runner?
157
- const runner = this.testcafe.createRunner()
158
-
159
- this.options.browser !== 'remote' ? this._startBrowser(runner) : this._startRemoteBrowser(runner)
160
-
161
- this.t = await testControllerHolder.get()
162
- assert(this.t, 'Expected to have the testcafe test controller')
163
-
164
- if (this.options.windowSize && this.options.windowSize.indexOf('x') > 0) {
165
- const dimensions = this.options.windowSize.split('x')
166
- await this.t.resizeWindow(parseInt(dimensions[0], 10), parseInt(dimensions[1], 10))
167
- }
168
- }
169
-
170
- async _startBrowser(runner) {
171
- runner
172
- .src(this.dummyTestcafeFile)
173
- .screenshots(global.output_dir, !this.options.disableScreenshots)
174
- // .video(global.output_dir) // TODO Make this configurable
175
- .browsers(this.options.show ? this.options.browser : `${this.options.browser}:headless`)
176
- .reporter('minimal')
177
- .run({
178
- skipJsErrors: true,
179
- skipUncaughtErrors: true,
180
- quarantineMode: false,
181
- // debugMode: true,
182
- // debugOnFail: true,
183
- // developmentMode: true,
184
- pageLoadTimeout: this.options.getPageTimeout,
185
- selectorTimeout: this.options.waitForTimeout,
186
- assertionTimeout: this.options.waitForTimeout,
187
- takeScreenshotsOnFails: true,
188
- })
189
- .catch(err => {
190
- this.debugSection('_before', `Error ${err.toString()}`)
191
- this.isRunning = false
192
- this.testcafe.close()
193
- })
194
- }
195
-
196
- async _startRemoteBrowser(runner) {
197
- const remoteConnection = await this.testcafe.createBrowserConnection()
198
- console.log('Connect your device to the following URL or scan QR Code: ', remoteConnection.url)
199
- qrcode.generate(remoteConnection.url)
200
- remoteConnection.once('ready', () => {
201
- runner
202
- .src(this.dummyTestcafeFile)
203
- .browsers(remoteConnection)
204
- .reporter('minimal')
205
- .run({
206
- selectorTimeout: this.options.waitForTimeout,
207
- skipJsErrors: true,
208
- skipUncaughtErrors: true,
209
- })
210
- .catch(err => {
211
- this.debugSection('_before', `Error ${err.toString()}`)
212
- this.isRunning = false
213
- this.testcafe.close()
214
- })
215
- })
216
- }
217
-
218
- async _stopBrowser() {
219
- this.debugSection('_after', 'Stopping testcafe browser...')
220
-
221
- testControllerHolder.free()
222
- if (this.testcafe) {
223
- this.testcafe.close()
224
- }
225
-
226
- fs.unlinkSync(this.dummyTestcafeFile) // remove the dummy test
227
- this.t = undefined
228
-
229
- this.isRunning = false
230
- }
231
-
232
- _init() {}
233
-
234
- async _beforeSuite() {
235
- if (!this.options.restart && !this.options.manualStart && !this.isRunning) {
236
- this.debugSection('Session', 'Starting singleton browser session')
237
- return this._configureAndStartBrowser()
238
- }
239
- }
240
-
241
- async _before() {
242
- if (this.options.restart && !this.options.manualStart) return this._configureAndStartBrowser()
243
- if (!this.isRunning && !this.options.manualStart) return this._configureAndStartBrowser()
244
- this.context = null
245
- }
246
-
247
- async _after() {
248
- if (!this.isRunning) return
249
-
250
- if (this.options.restart) {
251
- this.isRunning = false
252
- return this._stopBrowser()
253
- }
254
-
255
- if (this.options.keepBrowserState) return
256
-
257
- if (!this.options.keepCookies) {
258
- this.debugSection('Session', 'cleaning cookies and localStorage')
259
- await this.clearCookie()
260
-
261
- // TODO IMHO that should only happen when
262
- await this.executeScript(() => localStorage.clear()).catch(err => {
263
- if (!(err.message.indexOf("Storage is disabled inside 'data:' URLs.") > -1)) throw err
264
- })
265
- }
266
- }
267
-
268
- _afterSuite() {}
269
-
270
- async _finishTest() {
271
- if (!this.options.restart && this.isRunning) return this._stopBrowser()
272
- }
273
-
274
- /**
275
- * Use [TestCafe](https://devexpress.github.io/testcafe/documentation/test-api/) API inside a test.
276
- *
277
- * First argument is a description of an action.
278
- * Second argument is async function that gets this helper as parameter.
279
- *
280
- * { [`t`](https://devexpress.github.io/testcafe/documentation/test-api/test-code-structure.html#test-controller)) } object from TestCafe API is available.
281
- *
282
- * ```js
283
- * I.useTestCafeTo('handle browser dialog', async ({ t }) {
284
- * await t.setNativeDialogHandler(() => true);
285
- * });
286
- * ```
287
- *
288
- *
289
- *
290
- * @param {string} description used to show in logs.
291
- * @param {function} fn async functuion that executed with TestCafe helper as argument
292
- */
293
- useTestCafeTo(description, fn) {
294
- return this._useTo(...arguments)
295
- }
296
-
297
- /**
298
- * Get elements by different locator types, including strict locator
299
- * Should be used in custom helpers:
300
- *
301
- * ```js
302
- * const elements = await this.helpers['TestCafe']._locate('.item');
303
- * ```
304
- *
305
- */
306
- async _locate(locator) {
307
- return findElements.call(this, this.context, locator).catch(mapError)
308
- }
309
-
310
- async _withinBegin(locator) {
311
- const els = await this._locate(locator)
312
- assertElementExists(els, locator)
313
- this.context = await els.nth(0)
314
- }
315
-
316
- async _withinEnd() {
317
- this.context = null
318
- }
319
-
320
- /**
321
- * {{> amOnPage }}
322
- */
323
- async amOnPage(url) {
324
- if (!/^\w+\:\/\//.test(url)) {
325
- url = this.options.url + url
326
- }
327
-
328
- return this.t.navigateTo(url).catch(mapError)
329
- }
330
-
331
- /**
332
- * {{> resizeWindow }}
333
- */
334
- async resizeWindow(width, height) {
335
- if (width === 'maximize') {
336
- return this.t.maximizeWindow().catch(mapError)
337
- }
338
-
339
- return this.t.resizeWindow(width, height).catch(mapError)
340
- }
341
-
342
- /**
343
- * {{> focus }}
344
- *
345
- */
346
- async focus(locator) {
347
- const els = await this._locate(locator)
348
- await assertElementExists(els, locator, 'Element to focus')
349
- const element = await els.nth(0)
350
-
351
- const focusElement = ClientFunction(() => element().focus(), {
352
- boundTestRun: this.t,
353
- dependencies: { element },
354
- })
355
-
356
- return focusElement()
357
- }
358
-
359
- /**
360
- * {{> blur }}
361
- *
362
- */
363
- async blur(locator) {
364
- const els = await this._locate(locator)
365
- await assertElementExists(els, locator, 'Element to blur')
366
- const element = await els.nth(0)
367
-
368
- const blurElement = ClientFunction(() => element().blur(), { boundTestRun: this.t, dependencies: { element } })
369
-
370
- return blurElement()
371
- }
372
-
373
- /**
374
- * {{> click }}
375
- *
376
- */
377
- async click(locator, context = null) {
378
- return proceedClick.call(this, locator, context)
379
- }
380
-
381
- /**
382
- * {{> refreshPage }}
383
- */
384
- async refreshPage() {
385
- return this.t.eval(() => location.reload(true), { boundTestRun: this.t }).catch(mapError)
386
- }
387
-
388
- /**
389
- * {{> waitForVisible }}
390
- *
391
- */
392
- async waitForVisible(locator, sec) {
393
- const timeout = sec ? sec * 1000 : undefined
394
-
395
- return (await findElements.call(this, this.context, locator)).with({ visibilityCheck: true, timeout })().catch(mapError)
396
- }
397
-
398
- /**
399
- * {{> fillField }}
400
- */
401
- async fillField(field, value) {
402
- const els = await findFields.call(this, field)
403
- assertElementExists(els, field, 'Field')
404
- const el = await els.nth(0)
405
- return this.t.typeText(el, value.toString(), { replace: true }).catch(mapError)
406
- }
407
-
408
- /**
409
- * {{> clearField }}
410
- */
411
- async clearField(field) {
412
- const els = await findFields.call(this, field)
413
- assertElementExists(els, field, 'Field')
414
- const el = await els.nth(0)
415
-
416
- const res = await this.t.selectText(el).pressKey('delete')
417
- return res
418
- }
419
-
420
- /**
421
- * {{> appendField }}
422
- *
423
- */
424
- async appendField(field, value) {
425
- const els = await findFields.call(this, field)
426
- assertElementExists(els, field, 'Field')
427
- const el = await els.nth(0)
428
-
429
- return this.t.typeText(el, value.toString(), { replace: false }).catch(mapError)
430
- }
431
-
432
- /**
433
- * {{> attachFile }}
434
- *
435
- */
436
- async attachFile(field, pathToFile) {
437
- const els = await findFields.call(this, field)
438
- assertElementExists(els, field, 'Field')
439
- const el = await els.nth(0)
440
- const file = path.join(global.codecept_dir, pathToFile)
441
-
442
- return this.t.setFilesToUpload(el, [file]).catch(mapError)
443
- }
444
-
445
- /**
446
- * {{> pressKey }}
447
- *
448
- * {{ keys }}
449
- */
450
- async pressKey(key) {
451
- assert(key, 'Expected a sequence of keys or key combinations')
452
-
453
- return this.t
454
- .pressKey(key.toLowerCase()) // testcafe keys are lowercase
455
- .catch(mapError)
456
- }
457
-
458
- /**
459
- * {{> moveCursorTo }}
460
- *
461
- */
462
- async moveCursorTo(locator, offsetX = 0, offsetY = 0) {
463
- const els = (await findElements.call(this, this.context, locator)).filterVisible()
464
- await assertElementExists(els, locator)
465
-
466
- return this.t.hover(els.nth(0), { offsetX, offsetY }).catch(mapError)
467
- }
468
-
469
- /**
470
- * {{> doubleClick }}
471
- *
472
- */
473
- async doubleClick(locator, context = null) {
474
- let matcher
475
- if (context) {
476
- const els = await this._locate(context)
477
- await assertElementExists(els, context)
478
- matcher = await els.nth(0)
479
- }
480
-
481
- const els = (await findClickable.call(this, matcher, locator)).filterVisible()
482
- return this.t.doubleClick(els.nth(0)).catch(mapError)
483
- }
484
-
485
- /**
486
- * {{> rightClick }}
487
- *
488
- */
489
- async rightClick(locator, context = null) {
490
- let matcher
491
- if (context) {
492
- const els = await this._locate(context)
493
- await assertElementExists(els, context)
494
- matcher = await els.nth(0)
495
- }
496
- const els = (await findClickable.call(this, matcher, locator)).filterVisible()
497
- assertElementExists(els, locator)
498
- return this.t.rightClick(els.nth(0)).catch(mapError)
499
- }
500
-
501
- /**
502
- * {{> checkOption }}
503
- */
504
- async checkOption(field, context = null) {
505
- const el = await findCheckable.call(this, field, context)
506
-
507
- return this.t.click(el).catch(mapError)
508
- }
509
-
510
- /**
511
- * {{> uncheckOption }}
512
- */
513
- async uncheckOption(field, context = null) {
514
- const el = await findCheckable.call(this, field, context)
515
-
516
- if (await el.checked) {
517
- return this.t.click(el).catch(mapError)
518
- }
519
- }
520
-
521
- /**
522
- * {{> seeCheckboxIsChecked }}
523
- */
524
- async seeCheckboxIsChecked(field) {
525
- return proceedIsChecked.call(this, 'assert', field)
526
- }
527
-
528
- /**
529
- * {{> dontSeeCheckboxIsChecked }}
530
- */
531
- async dontSeeCheckboxIsChecked(field) {
532
- return proceedIsChecked.call(this, 'negate', field)
533
- }
534
-
535
- /**
536
- * {{> selectOption }}
537
- */
538
- async selectOption(select, option) {
539
- const els = await findFields.call(this, select)
540
- assertElementExists(els, select, 'Selectable field')
541
-
542
- const el = await els.filterVisible().nth(0)
543
-
544
- if ((await el.tagName).toLowerCase() !== 'select') {
545
- throw new Error('Element is not <select>')
546
- }
547
- if (!Array.isArray(option)) option = [option]
548
-
549
- // TODO As far as I understand the testcafe docs this should do a multi-select
550
- // but it does not work
551
- // const clickOpts = { ctrl: option.length > 1 };
552
- await this.t.click(el).catch(mapError)
553
-
554
- for (const key of option) {
555
- const opt = key
556
-
557
- let optEl
558
- try {
559
- optEl = el.child('option').withText(opt)
560
- if (await optEl.count) {
561
- await this.t.click(optEl).catch(mapError)
562
- continue
563
- }
564
- } catch (err) {}
565
-
566
- try {
567
- const sel = `[value="${opt}"]`
568
- optEl = el.find(sel)
569
- if (await optEl.count) {
570
- await this.t.click(optEl).catch(mapError)
571
- }
572
- } catch (err) {}
573
- }
574
- }
575
-
576
- /**
577
- * {{> seeInCurrentUrl }}
578
- */
579
- async seeInCurrentUrl(url) {
580
- stringIncludes('url').assert(url, await getPageUrl(this.t)().catch(mapError))
581
- }
582
-
583
- /**
584
- * {{> dontSeeInCurrentUrl }}
585
- */
586
- async dontSeeInCurrentUrl(url) {
587
- stringIncludes('url').negate(url, await getPageUrl(this.t)().catch(mapError))
588
- }
589
-
590
- /**
591
- * {{> seeCurrentUrlEquals }}
592
- */
593
- async seeCurrentUrlEquals(url) {
594
- urlEquals(this.options.url).assert(url, await getPageUrl(this.t)().catch(mapError))
595
- }
596
-
597
- /**
598
- * {{> dontSeeCurrentUrlEquals }}
599
- */
600
- async dontSeeCurrentUrlEquals(url) {
601
- urlEquals(this.options.url).negate(url, await getPageUrl(this.t)().catch(mapError))
602
- }
603
-
604
- /**
605
- * {{> see }}
606
- *
607
- */
608
- async see(text, context = null) {
609
- let els
610
- if (context) {
611
- els = (await findElements.call(this, this.context, context)).withText(normalizeSpacesInString(text))
612
- } else {
613
- els = (await findElements.call(this, this.context, '*')).withText(normalizeSpacesInString(text))
614
- }
615
-
616
- return this.t.expect(els.filterVisible().count).gt(0, `No element with text "${text}" found`).catch(mapError)
617
- }
618
-
619
- /**
620
- * {{> dontSee }}
621
- *
622
- */
623
- async dontSee(text, context = null) {
624
- let els
625
- if (context) {
626
- els = (await findElements.call(this, this.context, context)).withText(text)
627
- } else {
628
- els = (await findElements.call(this, this.context, 'body')).withText(text)
629
- }
630
-
631
- return this.t.expect(els.filterVisible().count).eql(0, `Element with text "${text}" can still be seen`).catch(mapError)
632
- }
633
-
634
- /**
635
- * {{> seeElement }}
636
- */
637
- async seeElement(locator) {
638
- const exists = (await findElements.call(this, this.context, locator)).filterVisible().exists
639
- return this.t
640
- .expect(exists)
641
- .ok(`No element "${new Locator(locator)}" found`)
642
- .catch(mapError)
643
- }
644
-
645
- /**
646
- * {{> dontSeeElement }}
647
- */
648
- async dontSeeElement(locator) {
649
- const exists = (await findElements.call(this, this.context, locator)).filterVisible().exists
650
- return this.t
651
- .expect(exists)
652
- .notOk(`Element "${new Locator(locator)}" is still visible`)
653
- .catch(mapError)
654
- }
655
-
656
- /**
657
- * {{> seeElementInDOM }}
658
- */
659
- async seeElementInDOM(locator) {
660
- const exists = (await findElements.call(this, this.context, locator)).exists
661
- return this.t
662
- .expect(exists)
663
- .ok(`No element "${new Locator(locator)}" found in DOM`)
664
- .catch(mapError)
665
- }
666
-
667
- /**
668
- * {{> dontSeeElementInDOM }}
669
- */
670
- async dontSeeElementInDOM(locator) {
671
- const exists = (await findElements.call(this, this.context, locator)).exists
672
- return this.t
673
- .expect(exists)
674
- .notOk(`Element "${new Locator(locator)}" is still in DOM`)
675
- .catch(mapError)
676
- }
677
-
678
- /**
679
- * {{> seeNumberOfVisibleElements }}
680
- *
681
- */
682
- async seeNumberOfVisibleElements(locator, num) {
683
- const count = (await findElements.call(this, this.context, locator)).filterVisible().count
684
- return this.t.expect(count).eql(num).catch(mapError)
685
- }
686
-
687
- /**
688
- * {{> grabNumberOfVisibleElements }}
689
- */
690
- async grabNumberOfVisibleElements(locator) {
691
- const count = (await findElements.call(this, this.context, locator)).filterVisible().count
692
- return count
693
- }
694
-
695
- /**
696
- * {{> seeInField }}
697
- */
698
- async seeInField(field, value) {
699
- const _value = typeof value === 'boolean' ? value : value.toString()
700
- // const expectedValue = findElements.call(this, this.context, field).value;
701
- const els = await findFields.call(this, field)
702
- assertElementExists(els, field, 'Field')
703
- const el = await els.nth(0)
704
-
705
- return this.t
706
- .expect(await el.value)
707
- .eql(_value)
708
- .catch(mapError)
709
- }
710
-
711
- /**
712
- * {{> dontSeeInField }}
713
- */
714
- async dontSeeInField(field, value) {
715
- const _value = typeof value === 'boolean' ? value : value.toString()
716
- // const expectedValue = findElements.call(this, this.context, field).value;
717
- const els = await findFields.call(this, field)
718
- assertElementExists(els, field, 'Field')
719
- const el = await els.nth(0)
720
-
721
- return this.t.expect(el.value).notEql(_value).catch(mapError)
722
- }
723
-
724
- /**
725
- * Checks that text is equal to provided one.
726
- *
727
- * ```js
728
- * I.seeTextEquals('text', 'h1');
729
- * ```
730
- */
731
- async seeTextEquals(text, context = null) {
732
- const expectedText = findElements.call(this, context, undefined).textContent
733
- return this.t.expect(expectedText).eql(text).catch(mapError)
734
- }
735
-
736
- /**
737
- * {{> seeInSource }}
738
- */
739
- async seeInSource(text) {
740
- const source = await getHtmlSource(this.t)()
741
- stringIncludes('HTML source of a page').assert(text, source)
742
- }
743
-
744
- /**
745
- * {{> dontSeeInSource }}
746
- */
747
- async dontSeeInSource(text) {
748
- const source = await getHtmlSource(this.t)()
749
- stringIncludes('HTML source of a page').negate(text, source)
750
- }
751
-
752
- /**
753
- * {{> saveElementScreenshot }}
754
- *
755
- */
756
- async saveElementScreenshot(locator, fileName) {
757
- const outputFile = path.join(global.output_dir, fileName)
758
-
759
- const sel = await findElements.call(this, this.context, locator)
760
- assertElementExists(sel, locator)
761
- const firstElement = await sel.filterVisible().nth(0)
762
-
763
- this.debug(`Screenshot of ${new Locator(locator)} element has been saved to ${outputFile}`)
764
- return this.t.takeElementScreenshot(firstElement, fileName)
765
- }
766
-
767
- /**
768
- * {{> saveScreenshot }}
769
- */
770
- // TODO Implement full page screenshots
771
- async saveScreenshot(fileName) {
772
- const outputFile = path.join(global.output_dir, fileName)
773
- this.debug(`Screenshot is saving to ${outputFile}`)
774
-
775
- // TODO testcafe automatically creates thumbnail images (which cant be turned off)
776
- return this.t.takeScreenshot(fileName)
777
- }
778
-
779
- /**
780
- * {{> wait }}
781
- */
782
- async wait(sec) {
783
- return new Promise(done => {
784
- setTimeout(done, sec * 1000)
785
- })
786
- }
787
-
788
- /**
789
- * {{> executeScript }}
790
- *
791
- * If a function returns a Promise It will wait for its resolution.
792
- */
793
- async executeScript(fn, ...args) {
794
- const browserFn = createClientFunction(fn, args).with({ boundTestRun: this.t })
795
- return browserFn()
796
- }
797
-
798
- /**
799
- * {{> grabTextFromAll }}
800
- */
801
- async grabTextFromAll(locator) {
802
- const sel = await findElements.call(this, this.context, locator)
803
- const length = await sel.count
804
- const texts = []
805
- for (let i = 0; i < length; i++) {
806
- texts.push(await sel.nth(i).innerText)
807
- }
808
-
809
- return texts
810
- }
811
-
812
- /**
813
- * {{> grabTextFrom }}
814
- */
815
- async grabTextFrom(locator) {
816
- const sel = await findElements.call(this, this.context, locator)
817
- assertElementExists(sel, locator)
818
- const texts = await this.grabTextFromAll(locator)
819
- if (texts.length > 1) {
820
- this.debugSection('GrabText', `Using first element out of ${texts.length}`)
821
- }
822
-
823
- return texts[0]
824
- }
825
-
826
- /**
827
- * {{> grabAttributeFrom }}
828
- */
829
- async grabAttributeFromAll(locator, attr) {
830
- const sel = await findElements.call(this, this.context, locator)
831
- const length = await sel.count
832
- const attrs = []
833
- for (let i = 0; i < length; i++) {
834
- attrs.push(await (await sel.nth(i)).getAttribute(attr))
835
- }
836
-
837
- return attrs
838
- }
839
-
840
- /**
841
- * {{> grabAttributeFrom }}
842
- */
843
- async grabAttributeFrom(locator, attr) {
844
- const sel = await findElements.call(this, this.context, locator)
845
- assertElementExists(sel, locator)
846
- const attrs = await this.grabAttributeFromAll(locator, attr)
847
- if (attrs.length > 1) {
848
- this.debugSection('GrabAttribute', `Using first element out of ${attrs.length}`)
849
- }
850
-
851
- return attrs[0]
852
- }
853
-
854
- /**
855
- * {{> grabValueFromAll }}
856
- */
857
- async grabValueFromAll(locator) {
858
- const sel = await findElements.call(this, this.context, locator)
859
- const length = await sel.count
860
- const values = []
861
- for (let i = 0; i < length; i++) {
862
- values.push(await (await sel.nth(i)).value)
863
- }
864
-
865
- return values
866
- }
867
-
868
- /**
869
- * {{> grabValueFrom }}
870
- */
871
- async grabValueFrom(locator) {
872
- const sel = await findElements.call(this, this.context, locator)
873
- assertElementExists(sel, locator)
874
- const values = await this.grabValueFromAll(locator)
875
- if (values.length > 1) {
876
- this.debugSection('GrabValue', `Using first element out of ${values.length}`)
877
- }
878
-
879
- return values[0]
880
- }
881
-
882
- /**
883
- * {{> grabSource }}
884
- */
885
- async grabSource() {
886
- return ClientFunction(() => document.documentElement.innerHTML).with({ boundTestRun: this.t })()
887
- }
888
-
889
- /**
890
- * Get JS log from browser.
891
- *
892
- * ```js
893
- * let logs = await I.grabBrowserLogs();
894
- * console.log(JSON.stringify(logs))
895
- * ```
896
- */
897
- async grabBrowserLogs() {
898
- // TODO Must map?
899
- return this.t.getBrowserConsoleMessages()
900
- }
901
-
902
- /**
903
- * {{> grabCurrentUrl }}
904
- */
905
- async grabCurrentUrl() {
906
- return ClientFunction(() => document.location.href).with({ boundTestRun: this.t })()
907
- }
908
-
909
- /**
910
- * {{> grabPageScrollPosition }}
911
- */
912
- async grabPageScrollPosition() {
913
- return ClientFunction(() => ({ x: window.pageXOffset, y: window.pageYOffset })).with({ boundTestRun: this.t })()
914
- }
915
-
916
- /**
917
- * {{> scrollPageToTop }}
918
- */
919
- scrollPageToTop() {
920
- return ClientFunction(() => window.scrollTo(0, 0))
921
- .with({ boundTestRun: this.t })()
922
- .catch(mapError)
923
- }
924
-
925
- /**
926
- * {{> scrollPageToBottom }}
927
- */
928
- scrollPageToBottom() {
929
- return ClientFunction(() => {
930
- const body = document.body
931
- const html = document.documentElement
932
- window.scrollTo(0, Math.max(body.scrollHeight, body.offsetHeight, html.clientHeight, html.scrollHeight, html.offsetHeight))
933
- })
934
- .with({ boundTestRun: this.t })()
935
- .catch(mapError)
936
- }
937
-
938
- /**
939
- * {{> scrollTo }}
940
- */
941
- async scrollTo(locator, offsetX = 0, offsetY = 0) {
942
- if (typeof locator === 'number' && typeof offsetX === 'number') {
943
- offsetY = offsetX
944
- offsetX = locator
945
- locator = null
946
- }
947
-
948
- const scrollBy = ClientFunction(offset => {
949
- if (window && window.scrollBy && offset) {
950
- window.scrollBy(offset.x, offset.y)
951
- }
952
- }).with({ boundTestRun: this.t })
953
-
954
- if (locator) {
955
- const els = await this._locate(locator)
956
- assertElementExists(els, locator, 'Element')
957
- const el = await els.nth(0)
958
- const x = (await el.offsetLeft) + offsetX
959
- const y = (await el.offsetTop) + offsetY
960
-
961
- return scrollBy({ x, y }).catch(mapError)
962
- }
963
-
964
- const x = offsetX
965
- const y = offsetY
966
- return scrollBy({ x, y }).catch(mapError)
967
- }
968
-
969
- /**
970
- * {{> switchTo }}
971
- */
972
- async switchTo(locator) {
973
- if (Number.isInteger(locator)) {
974
- throw new Error('Not supported switching to iframe by number')
975
- }
976
-
977
- if (!locator) {
978
- return this.t.switchToMainWindow()
979
- }
980
-
981
- const el = await findElements.call(this, this.context, locator)
982
- return this.t.switchToIframe(el)
983
- }
984
-
985
- // TODO Add url assertions
986
-
987
- /**
988
- * {{> setCookie }}
989
- */
990
- async setCookie(cookie) {
991
- if (Array.isArray(cookie)) {
992
- throw new Error('cookie array is not supported')
993
- }
994
-
995
- cookie.path = cookie.path || '/'
996
- // cookie.expires = cookie.expires || (new Date()).toUTCString();
997
-
998
- const setCookie = ClientFunction(
999
- () => {
1000
- document.cookie = `${cookie.name}=${cookie.value};path=${cookie.path};expires=${cookie.expires};`
1001
- },
1002
- { dependencies: { cookie } },
1003
- ).with({ boundTestRun: this.t })
1004
-
1005
- return setCookie()
1006
- }
1007
-
1008
- /**
1009
- * {{> seeCookie }}
1010
- *
1011
- */
1012
- async seeCookie(name) {
1013
- const cookie = await this.grabCookie(name)
1014
- empty(`cookie ${name} to be set`).negate(cookie)
1015
- }
1016
-
1017
- /**
1018
- * {{> dontSeeCookie }}
1019
- */
1020
- async dontSeeCookie(name) {
1021
- const cookie = await this.grabCookie(name)
1022
- empty(`cookie ${name} not to be set`).assert(cookie)
1023
- }
1024
-
1025
- /**
1026
- * {{> grabCookie }}
1027
- *
1028
- * Returns cookie in JSON format. If name not passed returns all cookies for this domain.
1029
- */
1030
- async grabCookie(name) {
1031
- if (!name) {
1032
- const getCookie = ClientFunction(() => {
1033
- return document.cookie.split(';').map(c => c.split('='))
1034
- }).with({ boundTestRun: this.t })
1035
- const cookies = await getCookie()
1036
- return cookies.map(cookie => ({ name: cookie[0].trim(), value: cookie[1] }))
1037
- }
1038
- const getCookie = ClientFunction(
1039
- () => {
1040
- const v = document.cookie.match('(^|;) ?' + name + '=([^;]*)(;|$)')
1041
- return v ? v[2] : null
1042
- },
1043
- { dependencies: { name } },
1044
- ).with({ boundTestRun: this.t })
1045
- const value = await getCookie()
1046
- if (value) return { name, value }
1047
- }
1048
-
1049
- /**
1050
- * {{> clearCookie }}
1051
- */
1052
- async clearCookie(cookieName) {
1053
- const clearCookies = ClientFunction(
1054
- () => {
1055
- const cookies = document.cookie.split(';')
1056
-
1057
- for (let i = 0; i < cookies.length; i++) {
1058
- const cookie = cookies[i]
1059
- const eqPos = cookie.indexOf('=')
1060
- const name = eqPos > -1 ? cookie.substr(0, eqPos) : cookie
1061
- if (cookieName === undefined || name === cookieName) {
1062
- document.cookie = `${name}=;expires=Thu, 01 Jan 1970 00:00:00 GMT`
1063
- }
1064
- }
1065
- },
1066
- { dependencies: { cookieName } },
1067
- ).with({ boundTestRun: this.t })
1068
-
1069
- return clearCookies()
1070
- }
1071
-
1072
- /**
1073
- * {{> waitInUrl }}
1074
- */
1075
- async waitInUrl(urlPart, sec = null) {
1076
- const waitTimeout = sec ? sec * 1000 : this.options.waitForTimeout
1077
-
1078
- const clientFn = createClientFunction(
1079
- urlPart => {
1080
- const currUrl = decodeURIComponent(decodeURIComponent(decodeURIComponent(window.location.href)))
1081
- return currUrl.indexOf(urlPart) > -1
1082
- },
1083
- [urlPart],
1084
- ).with({ boundTestRun: this.t })
1085
-
1086
- return waitForFunction(clientFn, waitTimeout).catch(async () => {
1087
- const currUrl = await this.grabCurrentUrl()
1088
- throw new Error(`expected url to include ${urlPart}, but found ${currUrl}`)
1089
- })
1090
- }
1091
-
1092
- /**
1093
- * {{> waitUrlEquals }}
1094
- */
1095
- async waitUrlEquals(urlPart, sec = null) {
1096
- const waitTimeout = sec ? sec * 1000 : this.options.waitForTimeout
1097
-
1098
- const baseUrl = this.options.url
1099
- if (urlPart.indexOf('http') < 0) {
1100
- urlPart = baseUrl + urlPart
1101
- }
1102
-
1103
- const clientFn = createClientFunction(
1104
- urlPart => {
1105
- const currUrl = decodeURIComponent(decodeURIComponent(decodeURIComponent(window.location.href)))
1106
- return currUrl === urlPart
1107
- },
1108
- [urlPart],
1109
- ).with({ boundTestRun: this.t })
1110
-
1111
- return waitForFunction(clientFn, waitTimeout).catch(async () => {
1112
- const currUrl = await this.grabCurrentUrl()
1113
- throw new Error(`expected url to be ${urlPart}, but found ${currUrl}`)
1114
- })
1115
- }
1116
-
1117
- /**
1118
- * {{> waitForFunction }}
1119
- */
1120
- async waitForFunction(fn, argsOrSec = null, sec = null) {
1121
- let args = []
1122
- if (argsOrSec) {
1123
- if (Array.isArray(argsOrSec)) {
1124
- args = argsOrSec
1125
- } else if (typeof argsOrSec === 'number') {
1126
- sec = argsOrSec
1127
- }
1128
- }
1129
- const waitTimeout = sec ? sec * 1000 : this.options.waitForTimeout
1130
-
1131
- const clientFn = createClientFunction(fn, args).with({ boundTestRun: this.t })
1132
-
1133
- return waitForFunction(clientFn, waitTimeout)
1134
- }
1135
-
1136
- /**
1137
- * {{> waitNumberOfVisibleElements }}
1138
- */
1139
- async waitNumberOfVisibleElements(locator, num, sec) {
1140
- const waitTimeout = sec ? sec * 1000 : this.options.waitForTimeout
1141
-
1142
- return this.t
1143
- .expect(createSelector(locator).with({ boundTestRun: this.t }).filterVisible().count)
1144
- .eql(num, `The number of elements (${new Locator(locator)}) is not ${num} after ${sec} sec`, {
1145
- timeout: waitTimeout,
1146
- })
1147
- .catch(mapError)
1148
- }
1149
-
1150
- /**
1151
- * {{> waitForElement }}
1152
- */
1153
- async waitForElement(locator, sec) {
1154
- const waitTimeout = sec ? sec * 1000 : this.options.waitForTimeout
1155
-
1156
- return this.t.expect(createSelector(locator).with({ boundTestRun: this.t }).exists).ok({ timeout: waitTimeout })
1157
- }
1158
-
1159
- /**
1160
- * {{> waitToHide }}
1161
- */
1162
- async waitToHide(locator, sec) {
1163
- const waitTimeout = sec ? sec * 1000 : this.options.waitForTimeout
1164
-
1165
- return this.t.expect(createSelector(locator).filterHidden().with({ boundTestRun: this.t }).exists).notOk({ timeout: waitTimeout })
1166
- }
1167
-
1168
- /**
1169
- * {{> waitForInvisible }}
1170
- */
1171
- async waitForInvisible(locator, sec) {
1172
- const waitTimeout = sec ? sec * 1000 : this.options.waitForTimeout
1173
-
1174
- return this.t.expect(createSelector(locator).filterVisible().with({ boundTestRun: this.t }).exists).ok({ timeout: waitTimeout })
1175
- }
1176
-
1177
- /**
1178
- * {{> waitForText }}
1179
- *
1180
- */
1181
- async waitForText(text, sec = null, context = null) {
1182
- const waitTimeout = sec ? sec * 1000 : this.options.waitForTimeout
1183
-
1184
- let els
1185
- if (context) {
1186
- els = await findElements.call(this, this.context, context)
1187
- await this.t.expect(els.exists).ok(`Context element ${context} not found`, { timeout: waitTimeout })
1188
- } else {
1189
- els = await findElements.call(this, this.context, '*')
1190
- }
1191
-
1192
- return this.t
1193
- .expect(els.withText(text).filterVisible().exists)
1194
- .ok(`No element with text "${text}" found in ${context || 'body'}`, { timeout: waitTimeout })
1195
- .catch(mapError)
1196
- }
1197
- }
1198
-
1199
- async function waitForFunction(browserFn, waitTimeout) {
1200
- const pause = () =>
1201
- new Promise(done => {
1202
- setTimeout(done, 50)
1203
- })
1204
-
1205
- const start = Date.now()
1206
-
1207
- while (true) {
1208
- let result
1209
- try {
1210
- result = await browserFn()
1211
- } catch (err) {
1212
- throw new Error(`Error running function ${err.toString()}`)
1213
- }
1214
-
1215
- if (result) return result
1216
-
1217
- const duration = Date.now() - start
1218
- if (duration > waitTimeout) {
1219
- throw new Error('waitForFunction timed out')
1220
- }
1221
- await pause() // make polling
1222
- }
1223
- }
1224
-
1225
- const createSelector = locator => {
1226
- locator = new Locator(locator, 'css')
1227
- if (locator.isXPath()) return elementByXPath(locator.value)
1228
- return Selector(locator.simplify())
1229
- }
1230
-
1231
- const elementByXPath = xpath => {
1232
- assert(xpath, 'xpath is required')
1233
-
1234
- return Selector(
1235
- () => {
1236
- const iterator = document.evaluate(xpath, document, null, XPathResult.UNORDERED_NODE_ITERATOR_TYPE, null)
1237
- const items = []
1238
-
1239
- let item = iterator.iterateNext()
1240
-
1241
- while (item) {
1242
- items.push(item)
1243
- item = iterator.iterateNext()
1244
- }
1245
-
1246
- return items
1247
- },
1248
- { dependencies: { xpath } },
1249
- )
1250
- }
1251
-
1252
- const assertElementExists = async (res, locator, prefix, suffix) => {
1253
- if (!res || !(await res.count) || !(await res.nth(0).tagName)) {
1254
- throw new ElementNotFound(locator, prefix, suffix)
1255
- }
1256
- }
1257
-
1258
- async function findElements(matcher, locator) {
1259
- if (locator && locator.react) throw new Error('react locators are not yet supported')
1260
-
1261
- locator = new Locator(locator, 'css')
1262
-
1263
- if (!locator.isXPath()) {
1264
- return matcher ? matcher.find(locator.simplify()) : Selector(locator.simplify()).with({ timeout: 0, boundTestRun: this.t })
1265
- }
1266
-
1267
- if (!matcher) return elementByXPath(locator.value).with({ timeout: 0, boundTestRun: this.t })
1268
-
1269
- return matcher.find(
1270
- (node, idx, originNode) => {
1271
- const found = document.evaluate(xpath, originNode, null, 5, null)
1272
- let current = null
1273
- while ((current = found.iterateNext())) {
1274
- if (current === node) return true
1275
- }
1276
- return false
1277
- },
1278
- { xpath: locator.value },
1279
- )
1280
- }
1281
-
1282
- async function proceedClick(locator, context = null) {
1283
- let matcher
1284
-
1285
- if (context) {
1286
- const els = await this._locate(context)
1287
- await assertElementExists(els, context)
1288
- matcher = await els.nth(0)
1289
- }
1290
-
1291
- const els = await findClickable.call(this, matcher, locator)
1292
- if (context) {
1293
- await assertElementExists(els, locator, 'Clickable element', `was not found inside element ${new Locator(context).toString()}`)
1294
- } else {
1295
- await assertElementExists(els, locator, 'Clickable element')
1296
- }
1297
-
1298
- const firstElement = await els.filterVisible().nth(0)
1299
-
1300
- return this.t.click(firstElement).catch(mapError)
1301
- }
1302
-
1303
- async function findClickable(matcher, locator) {
1304
- if (locator && locator.react) throw new Error('react locators are not yet supported')
1305
-
1306
- locator = new Locator(locator)
1307
- if (!locator.isFuzzy()) return (await findElements.call(this, matcher, locator)).filterVisible()
1308
-
1309
- let els
1310
-
1311
- // try to use native TestCafe locator
1312
- els = matcher ? matcher.find('a,button') : createSelector('a,button')
1313
- els = await els.withExactText(locator.value).with({ timeout: 0, boundTestRun: this.t })
1314
- if (await els.count) return els
1315
-
1316
- const literal = xpathLocator.literal(locator.value)
1317
-
1318
- els = (await findElements.call(this, matcher, Locator.clickable.narrow(literal))).filterVisible()
1319
- if (await els.count) return els
1320
-
1321
- els = (await findElements.call(this, matcher, Locator.clickable.wide(literal))).filterVisible()
1322
- if (await els.count) return els
1323
-
1324
- els = (await findElements.call(this, matcher, Locator.clickable.self(literal))).filterVisible()
1325
- if (await els.count) return els
1326
-
1327
- return findElements.call(this, matcher, locator.value) // by css or xpath
1328
- }
1329
-
1330
- async function proceedIsChecked(assertType, option) {
1331
- const els = await findCheckable.call(this, option)
1332
- assertElementExists(els, option, 'Checkable')
1333
-
1334
- const selected = await els.checked
1335
-
1336
- return truth(`checkable ${option}`, 'to be checked')[assertType](selected)
1337
- }
1338
-
1339
- async function findCheckable(locator, context) {
1340
- assert(locator, 'locator is required')
1341
- assert(this.t, 'this.t is required')
1342
-
1343
- let contextEl = await this.context
1344
- if (typeof context === 'string') {
1345
- contextEl = (await findElements.call(this, contextEl, new Locator(context, 'css').simplify())).filterVisible()
1346
- contextEl = await contextEl.nth(0)
1347
- }
1348
-
1349
- const matchedLocator = new Locator(locator)
1350
- if (!matchedLocator.isFuzzy()) {
1351
- return (await findElements.call(this, contextEl, matchedLocator.simplify())).filterVisible()
1352
- }
1353
-
1354
- const literal = xpathLocator.literal(locator)
1355
- let els = (await findElements.call(this, contextEl, Locator.checkable.byText(literal))).filterVisible()
1356
- if (await els.count) {
1357
- return els
1358
- }
1359
-
1360
- els = (await findElements.call(this, contextEl, Locator.checkable.byName(literal))).filterVisible()
1361
- if (await els.count) {
1362
- return els
1363
- }
1364
-
1365
- return (await findElements.call(this, contextEl, locator)).filterVisible()
1366
- }
1367
-
1368
- async function findFields(locator) {
1369
- const matchedLocator = new Locator(locator)
1370
- if (!matchedLocator.isFuzzy()) {
1371
- return this._locate(matchedLocator)
1372
- }
1373
- const literal = xpathLocator.literal(locator)
1374
-
1375
- let els = await this._locate({ xpath: Locator.field.labelEquals(literal) })
1376
- if (await els.count) {
1377
- return els
1378
- }
1379
-
1380
- els = await this._locate({ xpath: Locator.field.labelContains(literal) })
1381
- if (await els.count) {
1382
- return els
1383
- }
1384
- els = await this._locate({ xpath: Locator.field.byName(literal) })
1385
- if (await els.count) {
1386
- return els
1387
- }
1388
- return this._locate({ css: locator })
1389
- }
1390
-
1391
- module.exports = TestCafe