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