webship-js 2.0.2 → 2.0.4

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 (181) hide show
  1. package/.circleci/config.yml +7 -31
  2. package/.drone.yml +68 -0
  3. package/.harness/webship-js-pipeline.yml +101 -0
  4. package/.semaphore/semaphore.yml +58 -0
  5. package/.teamcity/pom.xml +52 -0
  6. package/.teamcity/settings.kts +92 -0
  7. package/.travis.yml +24 -3
  8. package/AGENTS.md +109 -0
  9. package/CLAUDE.md +317 -0
  10. package/Jenkinsfile +54 -0
  11. package/azure-pipelines.yml +82 -0
  12. package/bamboo-specs/bamboo.yml +131 -0
  13. package/bin/generate-reports.js +181 -9
  14. package/buildspec.yml +56 -0
  15. package/cloudbuild.yaml +49 -0
  16. package/codefresh.yml +77 -0
  17. package/cucumber.js +48 -5
  18. package/docs/00-quick-start.md +102 -0
  19. package/docs/01-getting-started.md +102 -0
  20. package/docs/02-bbr-smart-waits.md +77 -0
  21. package/docs/03-selector-registry.md +95 -0
  22. package/docs/04-step-reference.md +799 -0
  23. package/docs/05-web-first-assertions.md +91 -0
  24. package/docs/06-network-and-dialogs.md +83 -0
  25. package/docs/07-auth-state.md +75 -0
  26. package/docs/08-clock-mocking.md +59 -0
  27. package/docs/09-api-testing.md +114 -0
  28. package/docs/10-accessibility.md +167 -0
  29. package/docs/11-debugging.md +129 -0
  30. package/docs/12-ai-agent-guide.md +338 -0
  31. package/docs/13-faq.md +236 -0
  32. package/docs/14-recipes-cookbook.md +255 -0
  33. package/docs/15-tag-conventions.md +76 -0
  34. package/docs/16-ci-cd.md +879 -0
  35. package/docs/README.md +113 -0
  36. package/docs/advanced-screenshots/then-i-save-fullscreen-screenshot.md +36 -0
  37. package/docs/advanced-screenshots/then-i-save-width-x-height-screenshot.md +34 -0
  38. package/docs/advanced-screenshots/when-i-save-screenshot-name-filename.md +45 -0
  39. package/docs/advanced-screenshots.md +52 -0
  40. package/docs/advanced-selectors.md +18 -0
  41. package/docs/api-step-definitions.md +45 -0
  42. package/docs/diffy-step-definitions/then-compare-diffy-env1-env2.md +30 -0
  43. package/docs/diffy-step-definitions/then-create-diffy-comparison-name-value.md +21 -0
  44. package/docs/diffy-step-definitions/then-create-diffy-comparison.md +25 -0
  45. package/docs/diffy-step-definitions/then-create-diffy-screenshot-environment-name.md +35 -0
  46. package/docs/diffy-step-definitions/then-i-take-screenshot.md +21 -0
  47. package/docs/diffy-step-definitions/then-i-take-screenshots-all-breakpoints.md +27 -0
  48. package/docs/diffy-step-definitions/then-send-screenshots-diffy-name-value.md +27 -0
  49. package/docs/diffy-step-definitions/then-upload-folder-url-diffy-snapshotname.md +28 -0
  50. package/docs/diffy-step-definitions/then-wait-diffy-comparison-complete.md +21 -0
  51. package/docs/diffy-step-definitions/when-i-resize-window-number.md +29 -0
  52. package/docs/diffy-step-definitions.md +21 -0
  53. package/docs/global-settings.md +295 -0
  54. package/docs/install-webship-js/ddev-webship-js.md +52 -0
  55. package/docs/install-webship-js.md +35 -0
  56. package/docs/overview.md +41 -0
  57. package/docs/step-definitions/given-i-am-anonymous-user.md +67 -0
  58. package/docs/step-definitions/given-i-am-homepage.md +68 -0
  59. package/docs/step-definitions/given-i-am-specific-page.md +72 -0
  60. package/docs/step-definitions/then-i-should-be.md +56 -0
  61. package/docs/step-definitions/then-i-should-see.md +62 -0
  62. package/docs/step-definitions/then-item-checkbox.md +54 -0
  63. package/docs/step-definitions/then-item-link-should-contain-url.md +84 -0
  64. package/docs/step-definitions/then-item-should-contain.md +67 -0
  65. package/docs/step-definitions/then-radio-button-value-should-be-selected.md +68 -0
  66. package/docs/step-definitions/then-response-status-code-should-be-number.md +69 -0
  67. package/docs/step-definitions/then-value-radio-button-selected.md +62 -0
  68. package/docs/step-definitions/when-i-attach-file-file-name-element.md +71 -0
  69. package/docs/step-definitions/when-i-check-checkbox.md +60 -0
  70. package/docs/step-definitions/when-i-click-link.md +51 -0
  71. package/docs/step-definitions/when-i-click-operation-text-row.md +71 -0
  72. package/docs/step-definitions/when-i-fill.md +59 -0
  73. package/docs/step-definitions/when-i-go-homepage.md +60 -0
  74. package/docs/step-definitions/when-i-go-specific-page.md +67 -0
  75. package/docs/step-definitions/when-i-move-backward-one-page.md +49 -0
  76. package/docs/step-definitions/when-i-move-forward-one-page.md +58 -0
  77. package/docs/step-definitions/when-i-press-button.md +58 -0
  78. package/docs/step-definitions/when-i-reload-page.md +51 -0
  79. package/docs/step-definitions/when-i-scroll.md +73 -0
  80. package/docs/step-definitions/when-i-select-option-select-list.md +53 -0
  81. package/docs/step-definitions/when-i-select-radio-button-value.md +62 -0
  82. package/docs/step-definitions/when-i-uncheck-checkbox.md +57 -0
  83. package/docs/step-definitions/when-i-wait-ajax-finish.md +64 -0
  84. package/docs/step-definitions/when-i-wait.md +62 -0
  85. package/docs/step-definitions.md +50 -0
  86. package/examples/a11y.html +31 -0
  87. package/examples/cookies.html +10 -0
  88. package/examples/date.html +12 -0
  89. package/examples/element.html +11 -0
  90. package/examples/field.html +24 -0
  91. package/examples/keyboard.html +11 -0
  92. package/examples/links.html +9 -0
  93. package/examples/modal.html +14 -0
  94. package/examples/path.html +3 -0
  95. package/examples/table.html +13 -0
  96. package/examples/video-demo.html +43 -0
  97. package/package.json +10 -3
  98. package/playwright.config.ts +3 -2
  99. package/tests/features/a11y.feature +39 -0
  100. package/tests/features/cookie.feature +13 -0
  101. package/tests/features/date.feature +11 -0
  102. package/tests/features/element.feature +16 -0
  103. package/tests/features/field.feature +25 -0
  104. package/tests/features/keyboard.feature +10 -0
  105. package/tests/features/link.feature +11 -0
  106. package/tests/features/modal-advanced-example.feature +1 -1
  107. package/tests/features/modal.feature +11 -0
  108. package/tests/features/path.feature +16 -0
  109. package/tests/features/response.feature +8 -0
  110. package/tests/features/responsive.feature +10 -0
  111. package/tests/features/table.feature +18 -0
  112. package/tests/features/video.feature +18 -0
  113. package/tests/features/wait.feature +7 -0
  114. package/tests/features/yaml.feature +102 -0
  115. package/tests/reports/README.md +55 -0
  116. package/tests/selectors/_canonical-keys.json +113 -0
  117. package/tests/selectors/back-end-selectors.json +7 -1
  118. package/tests/selectors/cms-contentful-admin.json +35 -0
  119. package/tests/selectors/cms-craft-admin.json +39 -0
  120. package/tests/selectors/cms-drupal-cms-gin.json +56 -0
  121. package/tests/selectors/cms-drupal-core-claro.json +50 -0
  122. package/tests/selectors/cms-generic-admin.json +34 -0
  123. package/tests/selectors/cms-ghost-admin.json +34 -0
  124. package/tests/selectors/cms-joomla-admin.json +41 -0
  125. package/tests/selectors/cms-magento2-admin.json +32 -0
  126. package/tests/selectors/cms-prestashop-admin.json +38 -0
  127. package/tests/selectors/cms-shopify-admin.json +25 -0
  128. package/tests/selectors/cms-strapi-admin.json +42 -0
  129. package/tests/selectors/cms-typo3-admin.json +41 -0
  130. package/tests/selectors/cms-woocommerce-front.json +50 -0
  131. package/tests/selectors/cms-wordpress-admin.json +31 -0
  132. package/tests/selectors/framework-ant-design.json +80 -0
  133. package/tests/selectors/framework-bootstrap.json +86 -0
  134. package/tests/selectors/framework-bulma.json +74 -0
  135. package/tests/selectors/framework-chakra.json +58 -0
  136. package/tests/selectors/framework-foundation.json +51 -0
  137. package/tests/selectors/framework-material-ui.json +72 -0
  138. package/tests/selectors/framework-shadcn.json +51 -0
  139. package/tests/selectors/framework-tailwind.json +40 -0
  140. package/tests/selectors/framework-vuetify.json +61 -0
  141. package/tests/step-definitions/a11y.steps.js +800 -0
  142. package/tests/step-definitions/action.steps.js +167 -0
  143. package/tests/step-definitions/{webship-api.js → api.steps.js} +41 -23
  144. package/tests/step-definitions/assertion.steps.js +352 -0
  145. package/tests/step-definitions/auth.steps.js +126 -0
  146. package/tests/step-definitions/clock.steps.js +128 -0
  147. package/tests/step-definitions/cookie.steps.js +216 -0
  148. package/tests/step-definitions/debug.steps.js +39 -0
  149. package/tests/step-definitions/dialog.steps.js +193 -0
  150. package/tests/step-definitions/element.steps.js +356 -0
  151. package/tests/step-definitions/field.steps.js +653 -0
  152. package/tests/step-definitions/file-download.steps.js +211 -0
  153. package/tests/step-definitions/form.steps.js +333 -0
  154. package/tests/step-definitions/iframe.steps.js +228 -0
  155. package/tests/step-definitions/input.steps.js +202 -0
  156. package/tests/step-definitions/javascript.steps.js +232 -0
  157. package/tests/step-definitions/keyboard.steps.js +112 -0
  158. package/tests/step-definitions/link.steps.js +142 -0
  159. package/tests/step-definitions/metatag.steps.js +91 -0
  160. package/tests/step-definitions/modal.steps.js +244 -0
  161. package/tests/step-definitions/navigation.steps.js +218 -0
  162. package/tests/step-definitions/network.steps.js +280 -0
  163. package/tests/step-definitions/path.steps.js +141 -0
  164. package/tests/step-definitions/response.steps.js +98 -0
  165. package/tests/step-definitions/responsive.steps.js +125 -0
  166. package/tests/step-definitions/rest.steps.js +111 -0
  167. package/tests/step-definitions/{webship-screenshot.js → screenshot.steps.js} +1 -5
  168. package/tests/step-definitions/scroll.steps.js +189 -0
  169. package/tests/step-definitions/{webship-selectors.js → selectors.steps.js} +64 -27
  170. package/tests/step-definitions/storage.steps.js +194 -0
  171. package/tests/step-definitions/table.steps.js +181 -0
  172. package/tests/step-definitions/video.steps.js +178 -0
  173. package/tests/step-definitions/wait.steps.js +400 -0
  174. package/tests/step-definitions/web-first.steps.js +298 -0
  175. package/tests/step-definitions/webship.js +741 -1477
  176. package/tests/step-definitions/xml.steps.js +411 -0
  177. package/tests/step-definitions/yaml.steps.js +913 -0
  178. package/tests/step-definitions-diffy/webship-diffy.js +0 -13
  179. package/tsconfig.json +19 -3
  180. package/videos/README.md +32 -0
  181. package/.travis-ci.yml +0 -16
@@ -1,98 +1,241 @@
1
1
  'use strict';
2
2
 
3
- const { setWorldConstructor, World, Before, After, BeforeStep, AfterStep, setDefaultTimeout, Given, When, Then } = require('@cucumber/cucumber');
3
+ const { setWorldConstructor, World, Before, After, BeforeStep, AfterStep, setDefaultTimeout } = require('@cucumber/cucumber');
4
4
  const playwright = require('playwright');
5
5
  const playwrightConfig = require(require('path').join(process.cwd(), 'playwright.config'));
6
- const assert = require('assert');
7
- const axios = require('axios');
8
6
  const path = require('path');
9
7
 
10
8
  // ---------------------------------------------------------------------------
11
- // Auto HTML report on cucumber-js process exit.
12
- // Disable: WEBSHIP_REPORT_DISABLE=1. Extra flags: WEBSHIP_REPORT_ARGS="--theme hierarchy --layout 2".
13
- // Registered once per process.
9
+ // Output filter — strip noisy `✔ Before # ...` / `✔ After # ...` hook lines
10
+ // from cucumber-js's failure dump so tester-facing output stays focused on
11
+ // the failing step + hint. Disable with WEBSHIP_FILTER_HOOK_LINES=off.
14
12
  // ---------------------------------------------------------------------------
15
- if (!global.__WEBSHIP_AUTO_REPORT__) {
16
- global.__WEBSHIP_AUTO_REPORT__ = true;
17
- process.on('exit', () => {
18
- if (process.env.WEBSHIP_REPORT_DISABLE) return;
19
- try {
20
- const { run } = require(path.join(__dirname, '..', '..', 'bin', 'generate-reports'));
21
- const extra = (process.env.WEBSHIP_REPORT_ARGS || '').split(/\s+/).filter(Boolean);
22
- run(extra);
23
- } catch (err) {
24
- console.error('[webship-js] Report generation failed:', err.message);
25
- }
26
- });
13
+ if (process.env.WEBSHIP_FILTER_HOOK_LINES !== 'off') {
14
+ const HOOK_LINE = /^\s*[✔✖✗⚠?-]\s+(?:Before|After|BeforeStep|AfterStep)\b.*$/;
15
+ const wrap = (stream) => {
16
+ const orig = stream.write.bind(stream);
17
+ stream.write = (chunk, encoding, cb) => {
18
+ if (typeof chunk === 'string' || Buffer.isBuffer(chunk)) {
19
+ const text = typeof chunk === 'string' ? chunk : chunk.toString('utf8');
20
+ const filtered = text
21
+ .split('\n')
22
+ .filter((line) => !HOOK_LINE.test(line.replace(/\x1b\[[0-9;]*m/g, '')))
23
+ .join('\n');
24
+ return orig(filtered, encoding, cb);
25
+ }
26
+ return orig(chunk, encoding, cb);
27
+ };
28
+ };
29
+ wrap(process.stdout);
30
+ wrap(process.stderr);
27
31
  }
28
32
 
33
+ // ===========================================================================
34
+ // Internal helpers (BBR smart settle, modal probes, selector + text utilities).
35
+ // Imported by every *.steps.js file via require('./webship'). Defined here
36
+ // rather than in a shared sub-module so there is a single, canonical entry
37
+ // point — `tests/step-definitions/webship.js`.
38
+ // ===========================================================================
39
+
40
+ /**
41
+ * Shared shape of every Cucumber `this` (the World) at step time.
42
+ *
43
+ * @typedef {Object} WebshipWorld
44
+ * @property {import('playwright').Page} [page] - Active page (set in Before hook).
45
+ * @property {import('playwright').BrowserContext} [context] - Active browser context.
46
+ * @property {import('playwright').Browser} [browser] - Active browser instance.
47
+ * @property {import('playwright').FrameLocator} [frame] - Active iframe scope (set by iframe steps).
48
+ * @property {Object<string, string>} [__selectorsCss] - Named CSS selectors (registry).
49
+ * @property {Object<string, string>} [__selectorsXpath] - Named XPath selectors (registry).
50
+ * @property {Object} [parameters] - cucumber.js worldParameters.
51
+ */
52
+
29
53
  // ---------------------------------------------------------------------------
30
- // World
54
+ // BBR-style smart settle
55
+ //
56
+ // Behaviour-Based Robotics (BBR) principle: react to the environment, not
57
+ // the clock. smartSettle returns when the page is at the *edge* of activity,
58
+ // bounded by a budget so a runaway page cannot stall the run.
59
+ //
60
+ // The probe checks:
61
+ // 1. <body> attached
62
+ // 2. DOMContentLoaded fired
63
+ // 3. Playwright "networkidle" (500ms with no in-flight network)
64
+ // 4. window.__webshipAjaxCount === 0 (custom fetch/XHR counter)
65
+ // 5. window.__webshipPendingTimers === 0 (custom setTimeout counter)
66
+ // 6. Date.now() - window.__webshipLastMutation >= quietMs (DOM-quiet)
67
+ //
68
+ // Steps 4/5/6 are evaluated atomically via a single waitForFunction, so a
69
+ // late-firing setTimeout that mutates the DOM re-arms the wait correctly.
31
70
  // ---------------------------------------------------------------------------
32
- setDefaultTimeout(30 * 1000);
33
-
34
- class PlaywrightWorld extends World {
35
- constructor(options) {
36
- super(options);
37
- this.launchUrl = this.parameters.launchUrl;
38
- this.minWaitTime = this.parameters.minWaitTime;
39
- this.playwrightBrowser = null;
40
- this.context = null;
41
- this.page = null;
42
- this.assetsFolder = path.join(__dirname, '../assets/');
43
- }
44
71
 
45
- async openBrowser() {
46
- const { browser: browserName, launchOptions, contextOptions } = playwrightConfig;
47
- this.playwrightBrowser = await playwright[browserName].launch(launchOptions);
48
- this.context = await this.playwrightBrowser.newContext(contextOptions);
49
- this.page = await this.context.newPage();
50
- }
72
+ /**
73
+ * Wait for the page to reach an "edge" of activity — DOM ready, network
74
+ * idle, no pending AJAX or timers, and no DOM mutations for ≥250 ms.
75
+ *
76
+ * @param {import('playwright').Page} page - Page being probed.
77
+ * @param {number} [timeout=10000] - Total budget in ms.
78
+ * @returns {Promise<void>}
79
+ */
80
+ async function smartSettle(page, timeout) {
81
+ const total = typeof timeout === 'number' && timeout > 0 ? timeout : 10000;
82
+ const deadline = Date.now() + total;
83
+ const remaining = () => Math.max(0, deadline - Date.now());
51
84
 
52
- async closeBrowser() {
53
- if (this.playwrightBrowser) {
54
- await this.playwrightBrowser.close();
55
- this.playwrightBrowser = null;
56
- this.context = null;
57
- this.page = null;
58
- }
59
- }
85
+ try { await page.waitForSelector('body', { state: 'attached', timeout: remaining() }); } catch { /* keep going */ }
86
+ try { await page.waitForLoadState('domcontentloaded', { timeout: remaining() }); } catch { /* keep going */ }
87
+ try { await page.waitForLoadState('networkidle', { timeout: remaining() }); } catch { /* keep going */ }
88
+ try {
89
+ await page.waitForFunction(
90
+ (quietMs) => {
91
+ const ajax = window.__webshipAjaxCount;
92
+ const timers = window.__webshipPendingTimers;
93
+ const last = window.__webshipLastMutation;
94
+ if (typeof ajax === 'number' && ajax > 0) return false;
95
+ if (typeof timers === 'number' && timers > 0) return false;
96
+ if (typeof last === 'number' && Date.now() - last < quietMs) return false;
97
+ return true;
98
+ },
99
+ 250,
100
+ { timeout: remaining(), polling: 50 }
101
+ );
102
+ } catch { /* keep going */ }
60
103
  }
61
104
 
62
- setWorldConstructor(PlaywrightWorld);
105
+ /**
106
+ * Convenience alias for {@link smartSettle}. Kept for readability inside
107
+ * navigation steps where "wait for page to load" reads more naturally.
108
+ *
109
+ * @param {import('playwright').Page} page
110
+ * @param {number} [timeout]
111
+ * @returns {Promise<void>}
112
+ */
113
+ async function waitForPageLoad(page, timeout) {
114
+ await smartSettle(page, timeout);
115
+ }
63
116
 
64
- Before(async function () {
65
- await this.openBrowser();
66
- if (this.minWaitTime.before_scenario > 0) {
67
- await this.page.waitForTimeout(this.minWaitTime.before_scenario);
117
+ // ---------------------------------------------------------------------------
118
+ // Modal helpers — use the named "modal" selector from the registry, falling
119
+ // back to ARIA role + native <dialog>.
120
+ // ---------------------------------------------------------------------------
121
+ /**
122
+ * Resolve the CSS selector that targets a modal dialog. Prefers a named
123
+ * `modal` selector from the registry; otherwise falls back to ARIA + native.
124
+ *
125
+ * @param {WebshipWorld} world
126
+ * @returns {string}
127
+ */
128
+ function getModalSelector(world) {
129
+ if (world && world.__selectorsCss && world.__selectorsCss['modal']) {
130
+ return world.__selectorsCss['modal'];
68
131
  }
69
- });
132
+ return '[role="dialog"], dialog';
133
+ }
70
134
 
71
- After(async function () {
72
- if (this.minWaitTime.after_scenario > 0) {
73
- await this.page.waitForTimeout(this.minWaitTime.after_scenario);
74
- }
75
- await this.closeBrowser();
76
- });
135
+ /**
136
+ * Locator pointing at modal dialogs on the given page.
137
+ *
138
+ * @param {import('playwright').Page} page
139
+ * @param {WebshipWorld} world
140
+ * @returns {import('playwright').Locator}
141
+ */
142
+ function getModalLocator(page, world) {
143
+ return page.locator(getModalSelector(world));
144
+ }
77
145
 
78
- BeforeStep(async function () {
79
- if (this.page && this.minWaitTime.before_step > 0) {
80
- await this.page.waitForTimeout(this.minWaitTime.before_step);
146
+ /**
147
+ * Wait until a modal is visible or hidden. Visibility is derived from
148
+ * computed styles (display + visibility + opacity), which is more
149
+ * reliable than `offsetParent` for fixed-position modal containers.
150
+ *
151
+ * @param {import('playwright').Page} page
152
+ * @param {'visible'|'hidden'} state
153
+ * @param {number} [timeout=10000]
154
+ * @param {WebshipWorld} world
155
+ * @returns {Promise<void>}
156
+ */
157
+ async function waitForModalState(page, state, timeout, world) {
158
+ const sel = getModalSelector(world);
159
+ const total = typeof timeout === 'number' && timeout > 0 ? timeout : 10000;
160
+ if (state === 'visible') {
161
+ await page.waitForFunction(
162
+ (s) => Array.from(document.querySelectorAll(s)).some((el) => {
163
+ const cs = window.getComputedStyle(el);
164
+ return cs.display !== 'none' && cs.visibility !== 'hidden' && cs.opacity !== '0';
165
+ }),
166
+ sel, { timeout: total }
167
+ );
168
+ } else {
169
+ await page.waitForFunction(
170
+ (s) => !Array.from(document.querySelectorAll(s)).some((el) => {
171
+ const cs = window.getComputedStyle(el);
172
+ return cs.display !== 'none' && cs.visibility !== 'hidden' && cs.opacity !== '0';
173
+ }),
174
+ sel, { timeout: total }
175
+ );
81
176
  }
82
- });
177
+ }
83
178
 
84
- AfterStep(async function () {
85
- if (this.page && this.minWaitTime.after_step > 0) {
86
- await this.page.waitForTimeout(this.minWaitTime.after_step);
179
+ /**
180
+ * Return the first visible modal locator. Throws a friendly error with
181
+ * remediation hints when no modal is on screen.
182
+ *
183
+ * @param {import('playwright').Page} page
184
+ * @param {WebshipWorld} world
185
+ * @returns {Promise<import('playwright').Locator>}
186
+ */
187
+ async function findVisibleModal(page, world) {
188
+ const all = getModalLocator(page, world);
189
+ const count = await all.count();
190
+ for (let i = 0; i < count; i++) {
191
+ if (await all.nth(i).isVisible()) return all.nth(i);
87
192
  }
88
- });
193
+ const sel = getModalSelector(world);
194
+ throw friendly(
195
+ `No visible modal found.\n` +
196
+ ` Selector tried: ${sel}\n` +
197
+ ` Hint: did you "wait for the modal to appear" first?\n` +
198
+ ` Or: register a custom "modal" CSS selector in tests/selectors/<preset>.json.`
199
+ );
200
+ }
201
+
202
+ /**
203
+ * Quick check — true when any element matching the modal selector is
204
+ * visible per the same computed-style probe as `waitForModalState`.
205
+ *
206
+ * @param {import('playwright').Page} page
207
+ * @param {WebshipWorld} world
208
+ * @returns {Promise<boolean>}
209
+ */
210
+ async function isAnyModalVisible(page, world) {
211
+ const sel = getModalSelector(world);
212
+ return page.evaluate((s) =>
213
+ Array.from(document.querySelectorAll(s)).some((el) => {
214
+ const cs = window.getComputedStyle(el);
215
+ return cs.display !== 'none' && cs.visibility !== 'hidden' && cs.opacity !== '0';
216
+ }),
217
+ sel
218
+ );
219
+ }
89
220
 
90
221
  // ---------------------------------------------------------------------------
91
- // Helper: build CSS selector from attrValue + optional attr argument.
222
+ // Resilient CSS selector builder.
223
+ // Honors id (#x), class (.x), or attribute selectors ([x]) verbatim.
224
+ // Otherwise tries id / class / name / data-testid / data-test-id / data-test
225
+ // / data-cy / aria-label / value / placeholder / title in priority order.
92
226
  // ---------------------------------------------------------------------------
227
+ /**
228
+ * Compose a CSS selector that tries multiple addressable attributes.
229
+ * Verbatim selectors (`#id`, `.class`, `[attr]`) pass through untouched;
230
+ * bare names fan out across `name`, `data-testid`, `aria-label`, etc.
231
+ *
232
+ * @param {string} attrValue - Value to match (e.g. `"submit-btn"`).
233
+ * @param {string} [attr] - Optional explicit attribute name; when given, returns `[attr="value" i]`.
234
+ * @returns {string} CSS selector union.
235
+ */
93
236
  function buildSelector(attrValue, attr) {
94
237
  const hasASpace = attrValue.indexOf(' ');
95
- if ((attrValue.startsWith('#') || attrValue.startsWith('.')) && hasASpace === -1) {
238
+ if ((attrValue.startsWith('#') || attrValue.startsWith('.') || attrValue.startsWith('[')) && hasASpace === -1) {
96
239
  return attrValue;
97
240
  }
98
241
  if (!attr && hasASpace === -1) {
@@ -100,38 +243,74 @@ function buildSelector(attrValue, attr) {
100
243
  attrValue +
101
244
  ',#' + attrValue +
102
245
  ',.' + attrValue +
103
- ',[name=' + attrValue + '],' +
104
- '[value="' + attrValue + '"],[placeholder="' + attrValue + '"]' +
246
+ ',[name="' + attrValue + '"]' +
247
+ ',[data-testid="' + attrValue + '"]' +
248
+ ',[data-test-id="' + attrValue + '"]' +
249
+ ',[data-test="' + attrValue + '"]' +
250
+ ',[data-cy="' + attrValue + '"]' +
251
+ ',[aria-label="' + attrValue + '"]' +
252
+ ',[value="' + attrValue + '"]' +
253
+ ',[placeholder="' + attrValue + '"]' +
105
254
  ',[title="' + attrValue + '"]'
106
255
  );
107
256
  }
108
257
  if (!attr && hasASpace > -1) {
109
- return '[value="' + attrValue + '"],[placeholder="' + attrValue + '"]';
258
+ return '[value="' + attrValue + '"],[placeholder="' + attrValue + '"],[aria-label="' + attrValue + '"],[title="' + attrValue + '"]';
110
259
  }
111
260
  return '[' + attr + '="' + attrValue + '" i]';
112
261
  }
113
262
 
114
- // ---------------------------------------------------------------------------
115
- // Helper: wait for domcontentloaded
116
- // ---------------------------------------------------------------------------
117
- async function waitForPageLoad(page, timeout) {
118
- await page.waitForLoadState('domcontentloaded', { timeout: timeout || 10000 });
119
- }
120
-
121
- // ---------------------------------------------------------------------------
122
- // Helper: navigate to a URL, tolerating empty-response errors (Firefox)
123
- // ---------------------------------------------------------------------------
263
+ // Navigate to a URL with friendly errors. Tolerates Firefox / WebKit
264
+ // empty-response edge cases so a redirect to about:blank or a 204 does
265
+ // not crash the suite. All other failures rethrow with extra context
266
+ // (URL + likely cause).
267
+ /**
268
+ * Navigate to a URL with friendly error messages for common failures
269
+ * (server down, DNS, empty response). All other errors rethrow with
270
+ * preserved stack + extra context.
271
+ *
272
+ * @param {import('playwright').Page} page
273
+ * @param {string} url
274
+ * @returns {Promise<void>}
275
+ */
124
276
  async function gotoUrl(page, url) {
125
277
  try {
126
278
  await page.goto(url, { waitUntil: 'domcontentloaded' });
127
279
  } catch (e) {
128
- if (!/NS_ERROR_NET_EMPTY_RESPONSE|net::ERR_EMPTY_RESPONSE/.test(e.message)) throw e;
280
+ const msg = e.message || '';
281
+ // Empty response: harmless, swallow.
282
+ if (/NS_ERROR_NET_EMPTY_RESPONSE|net::ERR_EMPTY_RESPONSE/.test(msg)) return;
283
+ // Connection refused: server probably not running.
284
+ if (/ECONNREFUSED|net::ERR_CONNECTION_REFUSED/.test(msg)) {
285
+ throw friendly(
286
+ `Could not reach "${url}".\n` +
287
+ ` ${msg.split('\n')[0]}\n` +
288
+ ` Hint: is your dev server running? Check LAUNCH_URL env var.`
289
+ );
290
+ }
291
+ // DNS failure.
292
+ if (/ERR_NAME_NOT_RESOLVED|NS_ERROR_UNKNOWN_HOST/.test(msg)) {
293
+ throw friendly(
294
+ `Could not resolve host for "${url}".\n` +
295
+ ` ${msg.split('\n')[0]}\n` +
296
+ ` Hint: double-check the hostname in LAUNCH_URL or your "Given I am on" path.`
297
+ );
298
+ }
299
+ // Anything else — strip the stack trace too.
300
+ throw friendly(`Failed to navigate to "${url}":\n ${e.message}`);
129
301
  }
130
302
  }
131
303
 
132
- // ---------------------------------------------------------------------------
133
- // Helper: fill a field located by label, placeholder, or name
134
- // ---------------------------------------------------------------------------
304
+ /**
305
+ * Fill a form field located by label, placeholder, or `[name]`. Resolution
306
+ * order: label → placeholder → name. Throws a friendly error when none
307
+ * match, suggesting the by-attr variant.
308
+ *
309
+ * @param {import('playwright').Page} page
310
+ * @param {string} field - Label / placeholder / name.
311
+ * @param {string} value - Value to type.
312
+ * @returns {Promise<void>}
313
+ */
135
314
  async function fillField(page, field, value) {
136
315
  const byLabel = page.getByLabel(field, { exact: true });
137
316
  if (await byLabel.count() > 0) {
@@ -143,12 +322,26 @@ async function fillField(page, field, value) {
143
322
  await byPlaceholder.fill(value);
144
323
  return;
145
324
  }
146
- await page.locator(`[name="${field}"]`).first().fill(value);
325
+ const byName = page.locator(`[name="${field}"]`).first();
326
+ if (await byName.count() > 0) {
327
+ await byName.fill(value);
328
+ return;
329
+ }
330
+ throw friendly(
331
+ `Could not find a field for "${field}".\n` +
332
+ ` Tried: getByLabel(exact), getByPlaceholder(exact), [name="${field}"].\n` +
333
+ ` Hints: check the label/placeholder text matches exactly (case-sensitive),\n` +
334
+ ` or use the attribute variant: 'I fill in "${field}" with "${value}" by attr'.`
335
+ );
147
336
  }
148
337
 
149
- // ---------------------------------------------------------------------------
150
- // Helper: get text from a locator — input value or text content
151
- // ---------------------------------------------------------------------------
338
+ /**
339
+ * Read text from a locator. Falls back to `textContent` when the element
340
+ * is not an `<input>` / `<textarea>`.
341
+ *
342
+ * @param {import('playwright').Locator} locator
343
+ * @returns {Promise<string>}
344
+ */
152
345
  async function getLocatorText(locator) {
153
346
  try {
154
347
  return await locator.inputValue();
@@ -157,1477 +350,548 @@ async function getLocatorText(locator) {
157
350
  }
158
351
  }
159
352
 
160
- const MODAL_SELECTOR = '.modal, .modal.show, .modal.in, [role="dialog"], .dialog, .popup';
161
-
162
- // ---------------------------------------------------------------------------
163
- // Helper: wait for any matching modal element to reach a state
164
- // ---------------------------------------------------------------------------
165
- async function waitForModalState(page, state, timeout) {
166
- const sel = MODAL_SELECTOR;
167
- if (state === 'visible') {
168
- await page.waitForFunction(
169
- (s) => Array.from(document.querySelectorAll(s)).some(el => {
170
- const cs = window.getComputedStyle(el);
171
- return cs.display !== 'none' && cs.visibility !== 'hidden' && el.offsetParent !== null;
172
- }),
173
- sel, { timeout }
174
- );
175
- } else {
176
- await page.waitForFunction(
177
- (s) => !Array.from(document.querySelectorAll(s)).some(el => {
178
- const cs = window.getComputedStyle(el);
179
- return cs.display !== 'none' && cs.visibility !== 'hidden' && el.offsetParent !== null;
180
- }),
181
- sel, { timeout }
182
- );
183
- }
184
- }
185
-
186
- // ---------------------------------------------------------------------------
187
- // Helper: find the first visible modal locator
188
- // ---------------------------------------------------------------------------
189
- async function findVisibleModal(page) {
190
- const all = page.locator(MODAL_SELECTOR);
191
- const count = await all.count();
192
- for (let i = 0; i < count; i++) {
193
- if (await all.nth(i).isVisible()) return all.nth(i);
194
- }
195
- throw new Error('No visible modal found');
196
- }
197
-
198
- // ---------------------------------------------------------------------------
199
- // Helper: check if any modal is currently visible
200
- // ---------------------------------------------------------------------------
201
- async function isAnyModalVisible(page) {
202
- return page.evaluate((sel) =>
203
- Array.from(document.querySelectorAll(sel)).some(el => {
204
- const cs = window.getComputedStyle(el);
205
- return cs.display !== 'none' && cs.visibility !== 'hidden' && el.offsetParent !== null;
206
- }),
207
- MODAL_SELECTOR
208
- );
209
- }
210
-
211
- /**
212
- * Clear cookies and navigate to the launch URL as an anonymous visitor.
213
- *
214
- * Example #1: Given I am an anonymous user
215
- * Example #2: Given we are an anonymous user
216
- * Example #3: Given an anonymous user
217
- *
218
- */
219
- Given(/^(I am |we are )?an anonymous user$/, async function (pronounCase) {
220
- await this.context.clearCookies();
221
- await gotoUrl(this.page, this.launchUrl);
222
- await waitForPageLoad(this.page, this.minWaitTime.page || 3000);
223
- });
224
-
225
353
  /**
226
- * Open the homepage.
227
- *
228
- * Example #1: Given I am on homepage
229
- * Example #2: Given I am on the homepage
230
- * Example #3: Given I am on frontpage
231
- * Example #4: Given I am on the frontpage
232
- * Example #5: Given we are on homepage
233
- * Example #6: Given we are on the frontpage
234
- * Example #7: Given on homepage
235
- * Example #8: Given on the homepage
236
- * Example #9: Given on frontpage
237
- * Example #10: Given on the frontpage
354
+ * Left-pad a number with zeros to the requested width.
238
355
  *
356
+ * @param {number} n
357
+ * @param {number} width
358
+ * @returns {string}
239
359
  */
240
- Given(/^(I am |we are )?on( the)* (homepage|frontpage)$/, async function (pronounCase, theCase, pageCase) {
241
- const defaultTime = this.minWaitTime.page || 3000;
242
- await gotoUrl(this.page, this.launchUrl);
243
- await this.page.waitForSelector('body', { state: 'attached', timeout: defaultTime });
244
- await waitForPageLoad(this.page, defaultTime);
245
- });
360
+ function pad(n, width) {
361
+ const s = String(n);
362
+ return s.length >= width ? s : '0'.repeat(width - s.length) + s;
363
+ }
246
364
 
247
- /**
248
- * Open a specific page under the launch URL.
249
- *
250
- * Example #1: Given I am on "/about-us.html"
251
- * Example #2: Given I am on the "/about-us.html" page
252
- * Example #3: Given we are on "/user/login"
253
- * Example #4: Given we are on the "/contact-us.html" page
254
- * Example #5: Given on "/about-us.html"
255
- * Example #6: Given on the "/about-us.html" page
256
- * Example #7: Given I am on "https://un.org"
257
- *
258
- */
259
- Given(/^(I am |we are )*on( the)* "([^"]*)?"( page)*$/, async function (pronounCase, theCase, url, pageCase) {
260
- await gotoUrl(this.page, this.launchUrl + url);
261
- await this.page.waitForSelector('body', { state: 'attached', timeout: 10000 });
262
- await waitForPageLoad(this.page);
263
- });
365
+ // ---------------------------------------------------------------------------
366
+ // Relative-date token resolver
367
+ //
368
+ // Replaces [relative:OFFSET] and [relative:OFFSET#FORMAT] tokens in step
369
+ // arguments before pattern matching. Resolution happens automatically via
370
+ // the BeforeStep hook registered below.
371
+ //
372
+ // OFFSET any expression understood by parseRelativeOffset()
373
+ // examples: "now", "-1 day", "+2 hours", "+1 week", "next monday"
374
+ // FORMAT subset of date-fns-style tokens: YYYY, MM, DD, HH, mm, ss
375
+ // examples: "YYYY-MM-DD", "DD/MM/YYYY HH:mm"
376
+ //
377
+ // Without FORMAT the resolved value is the Unix timestamp in seconds.
378
+ //
379
+ // Examples:
380
+ // [relative:-1 day] -> "1714867200"
381
+ // [relative:-1 day#YYYY-MM-DD] -> "2026-05-06"
382
+ // ---------------------------------------------------------------------------
264
383
 
265
- /**
266
- * Navigate to the homepage.
267
- *
268
- * Example #1: When I go to homepage
269
- * Example #2: When I go to the homepage
270
- * Example #3: When I navigate to the homepage
271
- * Example #4: When navigating to the homepage
272
- * Example #5: When navigating to homepage
273
- * Example #6: When navigating to the frontpage
274
- * Example #7: When we go to the homepage
275
- * Example #8: When we navigate to the homepage
276
- *
277
- */
278
- When(/^(I go |I navigate |we go |we navigate |navigating )?to( the)* (homepage|frontpage)$/, async function (pronounCase, theCase, pageCase) {
279
- const defaultTime = this.minWaitTime.page || 3000;
280
- await gotoUrl(this.page, this.launchUrl);
281
- await this.page.waitForSelector('body', { state: 'attached', timeout: defaultTime });
282
- await waitForPageLoad(this.page, defaultTime);
283
- });
384
+ const RELATIVE_TOKEN_RE = /\[relative:([^\]#]+)(?:#([^\]]+))?\]/g;
284
385
 
285
386
  /**
286
- * Navigate to a specific page.
287
- *
288
- * Example #1: When I go to "/contact-us.html"
289
- * Example #2: When I go to "/user/login"
290
- * Example #3: When I navigate to "/admin/dashboard"
291
- * Example #4: When navigating to "/products"
292
- * Example #5: When we go to "/products"
293
- * Example #6: When we navigate to "/terms"
387
+ * Format a Date with a tiny token vocabulary (`YYYY`, `MM`, `DD`, `HH`,
388
+ * `mm`, `ss`). Sufficient for typical step-arg date formats.
294
389
  *
390
+ * @param {Date} date
391
+ * @param {string} fmt
392
+ * @returns {string}
295
393
  */
296
- When(/^(I go |I navigate |we go |we navigate |navigating )?to "([^"]*)?"$/, async function (pronounCase, url) {
297
- const defaultTime = this.minWaitTime.page || 3000;
298
- await gotoUrl(this.page, this.launchUrl + url);
299
- await this.page.waitForSelector('body', { state: 'attached', timeout: defaultTime });
300
- await waitForPageLoad(this.page, defaultTime);
301
- });
394
+ function formatRelativeDate(date, fmt) {
395
+ return fmt
396
+ .replace(/YYYY/g, date.getFullYear())
397
+ .replace(/MM/g, pad(date.getMonth() + 1, 2))
398
+ .replace(/DD/g, pad(date.getDate(), 2))
399
+ .replace(/HH/g, pad(date.getHours(), 2))
400
+ .replace(/mm/g, pad(date.getMinutes(), 2))
401
+ .replace(/ss/g, pad(date.getSeconds(), 2));
402
+ }
302
403
 
303
404
  /**
304
- * Assert that text is or is not present on the page.
305
- *
306
- * Example #1: Then I should see "Welcome"
307
- * Example #2: Then we should see "Your accounts for the group is public"
308
- * Example #3: Then I should not see "Access denied"
309
- * Example #4: Then we should not see "Edit layout"
310
- *
311
- */
312
- Then(/^(I |we )*should( not)* see "([^"]*)?"$/, async function (pronounCase, notCase, expectedText) {
313
- if (notCase) {
314
- const text = await this.page.locator('body').textContent() || '';
315
- assert.ok(!text.includes(expectedText), `Page should NOT contain "${expectedText}" but it does.`);
316
- } else {
317
- await this.page.locator('body').filter({ hasText: expectedText }).waitFor({ timeout: 5000 });
405
+ * Parse a relative-date offset expression and return absolute ms.
406
+ * Accepts `"now"`, `"+1 day"`, `"-2 hours"`, `"next monday"`, etc.
407
+ *
408
+ * @param {string} offset
409
+ * @param {number} baseMs - Reference epoch in ms.
410
+ * @returns {number} Resolved epoch in ms.
411
+ */
412
+ function parseRelativeOffset(offset, baseMs) {
413
+ const trimmed = offset.trim().toLowerCase();
414
+ if (trimmed === 'now') return baseMs;
415
+
416
+ const weekdayMatch = trimmed.match(/^(next|last)\s+(sunday|monday|tuesday|wednesday|thursday|friday|saturday)$/);
417
+ if (weekdayMatch) {
418
+ const direction = weekdayMatch[1] === 'next' ? 1 : -1;
419
+ const target = ['sunday', 'monday', 'tuesday', 'wednesday', 'thursday', 'friday', 'saturday'].indexOf(weekdayMatch[2]);
420
+ const d = new Date(baseMs);
421
+ let diff = (target - d.getDay()) * direction;
422
+ if (diff <= 0) diff += 7;
423
+ d.setDate(d.getDate() + diff * direction);
424
+ return d.getTime();
425
+ }
426
+
427
+ const m = trimmed.match(/^([+-]?\d+)\s*(second|minute|hour|day|week|month|year)s?$/);
428
+ if (m) {
429
+ const n = parseInt(m[1], 10);
430
+ const unit = m[2];
431
+ const d = new Date(baseMs);
432
+ switch (unit) {
433
+ case 'second': d.setSeconds(d.getSeconds() + n); break;
434
+ case 'minute': d.setMinutes(d.getMinutes() + n); break;
435
+ case 'hour': d.setHours(d.getHours() + n); break;
436
+ case 'day': d.setDate(d.getDate() + n); break;
437
+ case 'week': d.setDate(d.getDate() + n * 7); break;
438
+ case 'month': d.setMonth(d.getMonth() + n); break;
439
+ case 'year': d.setFullYear(d.getFullYear() + n); break;
440
+ }
441
+ return d.getTime();
318
442
  }
319
- });
320
443
 
321
- /**
322
- * Moves forward one page in browser history.
323
- *
324
- * Example #1: When I move forward one page
325
- * Example #2: When we move forward one page
326
- * Example #3: And move forward one page
327
- *
328
- */
329
- When(/^(I |we )*move forward one page$/, async function (pronounCase) {
330
- await this.page.goForward();
331
- });
444
+ const parsed = Date.parse(offset);
445
+ if (!Number.isNaN(parsed)) return parsed;
332
446
 
333
- /**
334
- * Moves backward one page in browser history.
335
- *
336
- * Example #1: When I move backward one page
337
- * Example #2: When we move backward one page
338
- * Example #3: And move backward one page
339
- *
340
- */
341
- When(/^(I |we )*move backward one page$/, async function (pronounCase) {
342
- await this.page.goBack();
343
- });
447
+ throw new Error(`Cannot evaluate relative date offset: "${offset}"`);
448
+ }
344
449
 
345
450
  /**
346
- * Press a button, submit input, or link by its visible text.
347
- *
348
- * Example #1: When I press "Log In"
349
- * Example #2: And I press the "Log In" button
350
- * Example #3: And I press the "Save as" button
351
- * Example #4: When we press "Submit"
352
- * Example #5: And press "Cancel"
451
+ * Resolve `[relative:OFFSET]` / `[relative:OFFSET#FORMAT]` tokens in any
452
+ * string. Without `#FORMAT` the token expands to a Unix timestamp in
453
+ * seconds; with it, to the formatted string.
353
454
  *
455
+ * @param {string} value - Step argument that may contain tokens.
456
+ * @param {number} [nowMs=Date.now()] - Reference epoch for resolution.
457
+ * @returns {string} Value with tokens replaced.
354
458
  */
355
- When(/^(I |we )*press( the)* "([^"]*)?"( button)*$/, async function (pronounCase, theCase, element, buttonCase) {
356
- const esc = element.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
357
- await this.page.locator('button, input[type="button"], input[type="submit"], [role="button"], .btn, a')
358
- .filter({ hasText: new RegExp('^' + esc + '$') })
359
- .first()
360
- .click();
361
- });
459
+ function resolveRelativeDate(value, nowMs) {
460
+ if (typeof value !== 'string' || !value.includes('[relative:')) return value;
461
+ const base = nowMs || Date.now();
462
+ return value.replace(RELATIVE_TOKEN_RE, (_, offset, fmt) => {
463
+ const ms = parseRelativeOffset(offset, base);
464
+ if (fmt) return formatRelativeDate(new Date(ms), fmt);
465
+ return String(Math.floor(ms / 1000));
466
+ });
467
+ }
362
468
 
363
- /**
364
- * Press a button by its attribute (id, class, name, placeholder, data-*).
365
- *
366
- * Example #1: When I press "btn-pressid" by attr
367
- * Example #2: When I press "btn-pressid" by attribute
368
- * Example #3: And I press "Your full name" by "placeholder" attribute
369
- * Example #4: And I press "Your full name" by its "placeholder" attribute
370
- * Example #5: And I press "save-name" by "data-selector" attr
371
- *
372
- */
373
- When(/^(I |we )*press "([^"]*)?" by( its)*(?: "([^"]*)?")* (attribute|attr)$/, async function (pronounCase, attrValue, itsCase, attr, attrWord) {
374
- await this.page.locator(buildSelector(attrValue, attr)).first().click();
375
- });
469
+ // BeforeStep hook — transform every string argument (and DataTable cells)
470
+ // in the current pickle step before the step definition runs.
471
+ BeforeStep(function (scope) {
472
+ const step = scope && scope.pickleStep;
473
+ if (!step) return;
376
474
 
377
- /**
378
- * Click a link or button by its visible text.
379
- *
380
- * Example #1: When I click "Contact Us"
381
- * Example #2: And I click "aboutUs"
382
- * Example #3: When we click "Read more"
383
- * Example #4: And click "Home"
384
- *
385
- */
386
- When(/^(I |we )*click "([^"]*)?"$/, async function (pronounCase, item) {
387
- const esc = item.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
388
- await this.page.locator('a, button, [role="button"], .btn, input[type="button"], input[type="submit"]')
389
- .filter({ hasText: new RegExp('^' + esc + '$') })
390
- .first()
391
- .click();
392
- });
475
+ if (typeof step.text === 'string' && step.text.includes('[relative:')) {
476
+ step.text = resolveRelativeDate(step.text);
477
+ }
393
478
 
394
- /**
395
- * Click a link or button by its attribute (id, class, name, data-*).
396
- *
397
- * Example #1: When I click "#about-us-id" by attr
398
- * Example #2: When I click "data-selector-about" by attribute
399
- * Example #3: And I click "about-us-css" by "class" attr
400
- * Example #4: And I click "about-us-id" by its "id" attribute
401
- *
402
- */
403
- When(/^(I |we )*click "([^"]*)?" by( its)*(?: "([^"]*)?")* (attribute|attr)$/, async function (pronounCase, attrValue, itsCase, attr, attrWord) {
404
- await this.page.locator(buildSelector(attrValue, attr)).first().click();
405
- });
479
+ if (!step.argument) return;
406
480
 
407
- /**
408
- * Click a clickable element inside a table row identified by text.
409
- *
410
- * Example #1: When I click "Edit" in the "John Smith" row
411
- * Example #2: When I click "Delete" in the "Product A" row
412
- * Example #3: When we click "View Details" in the "Order #12345" row
413
- * Example #4: And I click "Download" in the "Report 2024" row
414
- *
415
- */
416
- When(/^(I |we )*click "([^"]*)?" in( the)* "([^"]*)?" row$/, async function (pronounCase, clickText, theCase, rowIdentifier) {
417
- const esc = clickText.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
418
- const row = this.page.locator('tr').filter({ hasText: rowIdentifier }).first();
419
- const clickable = row.locator('a, button, [role="button"], .btn, input[type="submit"], input[type="button"]')
420
- .filter({ hasText: new RegExp('^' + esc + '$') });
421
- if (await clickable.count() > 0) {
422
- await clickable.first().click();
423
- } else {
424
- await row.getByText(clickText, { exact: true }).first().click();
481
+ if (step.argument.docString && typeof step.argument.docString.content === 'string') {
482
+ step.argument.docString.content = resolveRelativeDate(step.argument.docString.content);
425
483
  }
426
- });
427
484
 
428
- /**
429
- * Assert text is or is not visible inside a table row identified by text.
430
- *
431
- * Example #1: Then I should see "Active" in the "John Smith" row
432
- * Example #2: Then I should see "In Stock" in the "Product A" row
433
- * Example #3: Then we should see "Processing" in the "Order #12345" row
434
- * Example #4: And I should see "Admin" in the "john.smith@example.com" row
435
- * Example #5: Then I should not see "Admin" in the "Jane Doe" row
436
- * Example #6: Then I should not see "Out of Stock" in the "Product A" row
437
- * Example #7: And I should not see "Inactive" in the "john.smith@example.com" row
438
- *
439
- */
440
- Then(/^(I |we )*should( not)* see "([^"]*)?" in( the)* "([^"]*)?" row$/, async function (pronounCase, notCase, expectedText, theCase, rowIdentifier) {
441
- const found = await this.page.evaluate(({ id, text }) => {
442
- const rows = Array.from(document.querySelectorAll('tr'));
443
- return rows.filter(r => r.textContent.includes(id)).some(r => r.textContent.includes(text));
444
- }, { id: rowIdentifier, text: expectedText });
445
- if (notCase) {
446
- assert.ok(!found, `Found "${expectedText}" in the "${rowIdentifier}" row, but it should not be there.`);
447
- } else {
448
- assert.ok(found, `Could not find "${expectedText}" in the "${rowIdentifier}" row.`);
485
+ if (step.argument.dataTable && Array.isArray(step.argument.dataTable.rows)) {
486
+ for (const row of step.argument.dataTable.rows) {
487
+ if (!row || !Array.isArray(row.cells)) continue;
488
+ for (const cell of row.cells) {
489
+ if (cell && typeof cell.value === 'string') {
490
+ cell.value = resolveRelativeDate(cell.value);
491
+ }
492
+ }
493
+ }
449
494
  }
450
495
  });
451
496
 
452
497
  /**
453
- * Reloads the current page.
454
- *
455
- * Example #1: When I reload
456
- * Example #2: And I reload the page
457
- * Example #3: And we reload page
458
- * Example #4: And we reload the page
459
- *
460
- */
461
- When(/^(I |we )*reload( the)*( page)*$/, async function (pronounCase, theCase, pageCase) {
462
- await this.page.reload();
463
- });
498
+ * Translate a raw Playwright / Node / HTTP error message into one short,
499
+ * plain-English sentence aimed at non-coder testers. Falls back to a
500
+ * cleaned-up first line of the original when no pattern matches.
501
+ *
502
+ * @param {Error|string} err
503
+ * @returns {string}
504
+ */
505
+ function humanize(err) {
506
+ const msg = typeof err === 'string' ? err : (err && err.message) || '';
507
+ const first = msg.split('\n')[0].trim();
508
+ // Common Playwright / Node patterns → plain English.
509
+ const map = [
510
+ [/Timeout\s+\d+ms\s+exceeded/i, 'the page took too long to respond'],
511
+ [/locator\.(click|press|fill|hover|dblclick|tap|focus|dispatchEvent|scrollIntoViewIfNeeded)/i,
512
+ 'the element could not be reached'],
513
+ [/strict mode violation/i, 'the locator matched more than one element'],
514
+ [/element is not visible/i, 'the element is hidden or off-screen'],
515
+ [/element is not attached/i, 'the element was removed from the page'],
516
+ [/element is not enabled/i, 'the element is disabled'],
517
+ [/element is outside of the viewport/i, 'the element is outside the visible area'],
518
+ [/intercepts pointer events/i, 'another element is on top of the target'],
519
+ [/ECONNREFUSED|net::ERR_CONNECTION_REFUSED/i, 'the server is not running or refused the connection'],
520
+ [/ERR_NAME_NOT_RESOLVED|NS_ERROR_UNKNOWN_HOST/i, 'the hostname could not be resolved'],
521
+ [/ERR_HTTP_RESPONSE_CODE_FAILURE/i, 'the page returned an HTTP error status'],
522
+ [/ENOENT/i, 'the file could not be found'],
523
+ [/EACCES|EPERM/i, 'the file is not readable or writable'],
524
+ [/Invalid (regular expression|regex)/i, 'the regular expression is invalid'],
525
+ [/Unexpected token|Unexpected end of JSON input/i, 'the JSON could not be parsed'],
526
+ [/Target page, context or browser has been closed/i, 'the browser closed before the step finished'],
527
+ [/page\.goto:/i, 'the page could not be opened'],
528
+ [/frameLocator|content frame/i, 'the iframe content was not ready'],
529
+ [/Cookies? not found|Cookie .* not (set|found)/i, 'the cookie does not exist on this page'],
530
+ [/setViewportSize/i, 'the viewport cannot be resized for this browser context'],
531
+ ];
532
+ for (const [re, plain] of map) {
533
+ if (re.test(msg)) return plain;
534
+ }
535
+ // Strip noisy "Call log:" suffix common in Playwright errors.
536
+ return first.replace(/^\w+\.\w+:\s*/, '').replace(/\s+Call log:.*$/i, '');
537
+ }
464
538
 
465
539
  /**
466
- * Fill an input field located by its label, placeholder, or name.
467
- *
468
- * Example #1: When I fill in "Username" with "John Smith"
469
- * Example #2: When I fill in "Email" with "jon@example.com"
470
- * Example #3: And we fill in "Organization" with "Webship.co"
471
- * Example #4: And I fill in "Password" with "1234"
540
+ * Build a tester-friendly error.
472
541
  *
473
- */
474
- When(/^(I |we )*fill in "([^"]*)?" with "([^"]*)?"$/, async function (pronounCase, field, value) {
475
- await fillField(this.page, field, value);
476
- });
477
-
478
- /**
479
- * Fill an input field located by its attribute.
542
+ * Three forms:
543
+ * 1. `friendly(message)` — message becomes the stack.
544
+ * 2. `friendly(message, err)` — appends "Why: <humanized>" + cleaned cause.
545
+ * 3. `friendly({ action, target, hint, cause })` — builds a structured message.
480
546
  *
481
- * Example #1: When I fill in "#uname" with "John Smith" by attr
482
- * Example #2: When I fill in "uname" with "John Smith" by attr
483
- * Example #3: And I fill in "pwordcss" with "1234" by "class" attr
484
- * Example #4: And I fill in "Your full name" with "John Smith" by its "placeholder" attribute
547
+ * The Error's `.stack` is set to the rendered message, so cucumber-js does
548
+ * not print a JS stack trace — only the lines we authored.
485
549
  *
550
+ * @param {string|Object} input
551
+ * @param {Error} [cause]
552
+ * @returns {Error}
486
553
  */
487
- When(/^(I |we )*fill in "([^"]*)?" with "([^"]*)?" by( its)*(?: "([^"]*)?")* (attribute|attr)$/, async function (pronounCase, attrValue, txtValue, itsCase, attr, attrWord) {
488
- await this.page.locator(buildSelector(attrValue, attr)).first().fill(txtValue);
489
- });
490
-
491
- /**
492
- * Clear an input field located by its label.
493
- *
494
- * Example #1: When I fill in "Username" with:
495
- * Example #2: And we fill in "Email" with:
496
- * Example #3: And I fill in "Password" with:
497
- *
498
- */
499
- When(/^(I |we )*fill in "([^"]*)?" with:$/, async function (pronounCase, field) {
500
- await fillField(this.page, field, '');
501
- });
502
-
503
- /**
504
- * Clear an input field located by its attribute.
505
- *
506
- * Example #1: When I fill in "#uname" with: by attr
507
- * Example #2: When I fill in "uname" with: by attr
508
- * Example #3: And I fill in "pwordcss" with: by "class" attr
509
- * Example #4: And I fill in "Your full name" with: by its "placeholder" attribute
510
- *
511
- */
512
- When(/^(I |we )*fill in "([^"]*)?" with: by( its)*(?: "([^"]*)?")* (attribute|attr)$/, async function (pronounCase, attrValue, itsCase, attr, attrWord) {
513
- await this.page.locator(buildSelector(attrValue, attr)).first().fill('');
514
- });
515
-
516
- /**
517
- * Fill an input field located by label (reverse syntax).
518
- *
519
- * Example #1: When I fill in "jon-smith" for "Username"
520
- * Example #2: When we fill in "Testing" for "Organization options"
521
- * Example #3: And I fill in "1234" for "Password"
522
- *
523
- */
524
- When(/^(I |we )*fill in "([^"]*)?" for "([^"]*)?"$/, async function (pronounCase, value, field) {
525
- await fillField(this.page, field, value);
526
- });
527
-
528
- /**
529
- * Fill an input field located by attribute (reverse syntax).
530
- *
531
- * Example #1: When I fill in "John Smith" for "#uname" by attr
532
- * Example #2: When I fill in "John Smith" for "uname" by attr
533
- * Example #3: And I fill in "1234" for "password" by "class" attr
534
- * Example #4: And I fill in "John Smith" for "Your full name" by its "placeholder" attribute
535
- *
536
- */
537
- When(/^(I |we )*fill in "([^"]*)?" for "([^"]*)?" by( its)*(?: "([^"]*)?")* (attribute|attr)$/, async function (pronounCase, txtValue, attrValue, itsCase, attr, attrWord) {
538
- await this.page.locator(buildSelector(attrValue, attr)).first().fill(txtValue);
539
- });
540
-
541
- /**
542
- * Fills multiple form fields from a data table, located by their labels.
543
- *
544
- * Example #1: When I fill in the following:
545
- * | Username | webshipco |
546
- * | Password | 1234 |
547
- * Example #2: And we fill in the following:
548
- * | Email | jon@example.com |
549
- * | Organization | Webship.co |
550
- *
551
- */
552
- When(/^(I |we )*fill in( the)* following:$/, async function (pronounCase, theCase, table) {
553
- for (const [field, value] of table.raw()) {
554
- await fillField(this.page, field, value);
555
- }
556
- });
557
-
558
- /**
559
- * Fills multiple form fields from a data table, located by their attributes.
560
- *
561
- * Example #1: When I fill in the following: by attr
562
- * | #uname | John Smith |
563
- * | password | 1234 |
564
- * Example #2: When I fill in the following: by its "placeholder" attribute
565
- * | Your full name | John Smith |
566
- * | Your Password | 1234 |
567
- *
568
- */
569
- When(/^(I |we )*fill in( the)* following: by( its)*(?: "([^"]*)?")* (attribute|attr)$/, async function (pronounCase, theCase, itsCase, attr, attrWord, table) {
570
- for (const [attrValue, value] of table.raw()) {
571
- await this.page.locator(buildSelector(attrValue, attr)).first().fill(value);
572
- }
573
- });
574
-
575
- /**
576
- * Select an option from a dropdown by label, id, class, or name.
577
- *
578
- * Example #1: When I select "Mercedes" from "Cars"
579
- * Example #2: When I select "saab" from "#cars"
580
- * Example #3: When I select "Mercedes" from "cars"
581
- * Example #4: And we select "English" from "Language"
582
- *
583
- */
584
- When(/^(I |we )*select "([^"]*)?" from "([^"]*)?"$/, async function (pronounCase, option, selectList) {
585
- let loc;
586
- if (selectList.startsWith('#') || selectList.startsWith('.')) {
587
- loc = this.page.locator(selectList);
588
- } else if (!selectList.includes(' ')) {
589
- loc = this.page.locator(`[name="${selectList}"], #${selectList}`).first();
590
- } else {
591
- loc = this.page.getByLabel(selectList, { exact: true });
592
- }
593
- try {
594
- await loc.selectOption({ label: option }, { timeout: 3000 });
595
- } catch {
596
- await loc.selectOption(option);
597
- }
598
- });
599
-
600
- /**
601
- * Add an option to a <select multiple> without clearing the existing selection.
602
- * Resolves the select by label, then by [name]/#id fallback.
603
- *
604
- * Example #1: When I additionally select "Red" from "Colors"
605
- * Example #2: When I additionally select "Blue" from "Colors"
606
- * Example #3: When we additionally select "Green" from "Colors"
607
- * Example #4: And additionally select "Yellow" from "Colors"
608
- * Example #5: When I additionally select "Admin" from "Roles"
609
- * Example #6: When we additionally select "Editor" from "Roles"
610
- * Example #7: When I additionally select "Viewer" from "Roles"
611
- * Example #8: And I additionally select "EN" from "Languages"
612
- * Example #9: When I additionally select "FR" from "Languages"
613
- * Example #10: When we additionally select "ES" from "Languages"
614
- *
615
- * Advanced:
616
- * Example #11: Build a full multi-selection in sequence:
617
- * When I select "Red" from "Colors"
618
- * And I additionally select "Blue" from "Colors"
619
- * And I additionally select "Green" from "Colors"
620
- * Example #12: Works against a [name] select:
621
- * When I additionally select "tag-a" from "tags"
622
- * And I additionally select "tag-b" from "tags"
623
- * Example #13: Confirm the select stays multi-valued after adds:
624
- * When I select "One" from "Items"
625
- * And I additionally select "Two" from "Items"
626
- */
627
- When(/^(I |we )*additionally select "([^"]*)" from "([^"]*)"$/, async function (pronounCase, option, select) {
628
- const loc = this.page.getByLabel(select).or(
629
- this.page.locator(`select[name="${select}"], select#${select}`)
630
- ).first();
631
-
632
- const currentValues = await loc.evaluate((el) => {
633
- if (!el || !el.selectedOptions) return [];
634
- return Array.from(el.selectedOptions).map((o) => o.value);
635
- });
636
-
637
- const nextValueForLabel = await loc.evaluate((el, label) => {
638
- const opt = Array.from(el.options || []).find((o) => o.label === label || o.text === label);
639
- return opt ? opt.value : null;
640
- }, option);
641
-
642
- if (nextValueForLabel === null) {
643
- throw new Error(`Option "${option}" not found in select "${select}".`);
644
- }
645
-
646
- const combined = Array.from(new Set([...currentValues, nextValueForLabel]));
647
- await loc.selectOption(combined);
648
- });
649
-
650
- /**
651
- * Checks the specified checkbox by label, id, class, or name.
652
- *
653
- * Example #1: When I check "Remember me"
654
- * Example #2: When we check "Put site into maintenance mode"
655
- * Example #3: And I check "#newsletter"
656
- * Example #4: And we check ".terms-and-conditions"
657
- *
658
- */
659
- When(/^(I |we )*check "([^"]*)?"$/, async function (pronounCase, item) {
660
- if (item.startsWith('#') || item.startsWith('.')) {
661
- await this.page.locator(item).check();
662
- } else {
663
- const byLabel = this.page.getByLabel(item, { exact: true });
664
- if (await byLabel.count() > 0) {
665
- await byLabel.check();
666
- } else {
667
- await this.page.locator(`input[type="checkbox"][id="${item}"], input[type="checkbox"][name="${item}"], input[type="checkbox"][value="${item}"]`).first().check();
554
+ function friendly(input, cause) {
555
+ let body;
556
+ if (typeof input === 'string') {
557
+ body = input;
558
+ if (cause) {
559
+ body += `\n Why: ${humanize(cause)}`;
668
560
  }
669
- }
670
- });
561
+ } else if (input && typeof input === 'object') {
562
+ const lines = [];
563
+ if (input.action && input.target) lines.push(`Could not ${input.action} "${input.target}".`);
564
+ else if (input.action) lines.push(`Could not ${input.action}.`);
565
+ else if (input.message) lines.push(input.message);
566
+ if (input.cause) lines.push(` Why: ${humanize(input.cause)}`);
567
+ if (input.hint) lines.push(` Hint: ${input.hint}`);
568
+ body = lines.join('\n');
569
+ } else {
570
+ body = String(input);
571
+ }
572
+ const e = new Error(body);
573
+ e.stack = body;
574
+ return e;
575
+ }
671
576
 
672
- /**
673
- * Unchecks the specified checkbox by label, id, class, or name.
674
- *
675
- * Example #1: When I uncheck "Remember me"
676
- * Example #2: When we uncheck "Put site into maintenance mode"
677
- * Example #3: And I uncheck "#newsletter"
678
- * Example #4: And we uncheck ".terms-and-conditions"
679
- *
680
- */
681
- When(/^(I |we )*uncheck "([^"]*)?"$/, async function (pronounCase, item) {
682
- if (item.startsWith('#') || item.startsWith('.')) {
683
- await this.page.locator(item).uncheck();
684
- } else {
685
- const byLabel = this.page.getByLabel(item, { exact: true });
686
- if (await byLabel.count() > 0) {
687
- await byLabel.uncheck();
688
- } else {
689
- await this.page.locator(`input[type="checkbox"][id="${item}"], input[type="checkbox"][name="${item}"], input[type="checkbox"][value="${item}"]`).first().uncheck();
690
- }
691
- }
692
- });
577
+ module.exports = {
578
+ smartSettle,
579
+ waitForPageLoad,
580
+ getModalSelector,
581
+ getModalLocator,
582
+ waitForModalState,
583
+ findVisibleModal,
584
+ isAnyModalVisible,
585
+ buildSelector,
586
+ gotoUrl,
587
+ fillField,
588
+ getLocatorText,
589
+ pad,
590
+ resolveRelativeDate,
591
+ parseRelativeOffset,
592
+ formatRelativeDate,
593
+ friendly,
594
+ humanize,
595
+ };
693
596
 
694
- /**
695
- * Selects a radio button by label, value, id, or class.
696
- *
697
- * Example #1: When I select radio button "Male"
698
- * Example #2: When I select radio button "female"
699
- * Example #3: When I select radio button "#gender-male"
700
- * Example #4: When we select radio button "option1"
701
- *
702
- */
703
- When(/^(I |we )*select radio button "([^"]*)?"$/, async function (pronounCase, item) {
704
- if (item.startsWith('#') || item.startsWith('.')) {
705
- await this.page.locator(item).check();
706
- } else {
707
- const byValue = this.page.locator(`input[type="radio"][value="${item}"]`);
708
- if (await byValue.count() > 0) {
709
- await byValue.first().check();
710
- } else {
711
- await this.page.getByLabel(item, { exact: true }).check();
597
+ // ---------------------------------------------------------------------------
598
+ // Auto HTML report on cucumber-js process exit.
599
+ // Disable: WEBSHIP_REPORT_DISABLE=1. Extra flags: WEBSHIP_REPORT_ARGS="--theme hierarchy --layout 2".
600
+ // Registered once per process.
601
+ // ---------------------------------------------------------------------------
602
+ if (!global.__WEBSHIP_AUTO_REPORT__) {
603
+ global.__WEBSHIP_AUTO_REPORT__ = true;
604
+ process.on('exit', () => {
605
+ if (process.env.WEBSHIP_REPORT_DISABLE) return;
606
+ try {
607
+ const { run } = require(path.join(__dirname, '..', '..', 'bin', 'generate-reports'));
608
+ const extra = (process.env.WEBSHIP_REPORT_ARGS || '').split(/\s+/).filter(Boolean);
609
+ run(extra);
610
+ } catch (err) {
611
+ console.error('[webship-js] Report generation failed:', err.message);
712
612
  }
713
- }
714
- });
613
+ });
614
+ }
715
615
 
716
- /**
717
- * Assert that the current page is or is not the homepage.
718
- *
719
- * Example #1: Then I should be on homepage
720
- * Example #2: And I should be on the homepage
721
- * Example #3: Then I should be on frontpage
722
- * Example #4: And should be on the homepage
723
- * Example #5: Then should be on homepage
724
- * Example #6: And we should be on homepage
725
- * Example #7: Then should be on frontpage
726
- * Example #8: And we should be on the homepage
727
- * Example #9: Then I should not be on homepage
728
- * Example #10: And I should not be on the homepage
729
- *
730
- */
731
- Then(/^(I |we )*should( not)* be on( the)* (homepage|frontpage)$/, async function (pronounCase, notCase, theCase, pageCase) {
732
- const currentUrl = this.page.url();
733
- if (notCase) {
734
- assert.ok(currentUrl !== this.launchUrl && !currentUrl.startsWith(this.launchUrl + '/'),
735
- `Should NOT be on homepage but current URL is: ${currentUrl}`);
736
- } else {
737
- assert.ok(currentUrl.startsWith(this.launchUrl),
738
- `Should be on homepage but current URL is: ${currentUrl}`);
739
- }
740
- });
616
+ // ---------------------------------------------------------------------------
617
+ // World
618
+ // ---------------------------------------------------------------------------
619
+ // Step timeout must exceed Playwright's 30s default so that locator timeouts
620
+ // (e.g. click() with no match) reach our try/catch wrappers BEFORE cucumber
621
+ // trips its own timeout — otherwise testers see "function timed out" instead
622
+ // of the friendly Why/Hint message.
623
+ setDefaultTimeout(45 * 1000);
741
624
 
742
- /**
743
- * Assert that the current path is or is not equal to the specified path.
744
- *
745
- * Example #1: Then I should be on "/"
746
- * Example #2: And I should be on "/user/login"
747
- * Example #3: And I should be on "https://un.org"
748
- * Example #4: Then we should be on the "/" page
749
- * Example #5: And we should be on "/user/login"
750
- * Example #6: Then should be on the "/user/reset" page
751
- * Example #7: Then I should not be on "/"
752
- * Example #8: And I should not be on "/user/login"
753
- * Example #9: And I should not be on "https://un.org"
754
- * Example #10: And we should not be on the "https://un.org" page
755
- *
756
- */
757
- Then(/^(I |we )*should( not)* be on( the)* "([^"]*)?"( page)*$/, async function (pronounCase, notCase, theCase, url, pageCase) {
758
- const currentUrl = this.page.url();
759
- if (notCase) {
760
- assert.ok(!currentUrl.includes(url), `URL should NOT contain "${url}" but it is: ${currentUrl}`);
761
- } else {
762
- assert.ok(currentUrl.includes(url), `URL should contain "${url}" but it is: ${currentUrl}`);
625
+ class PlaywrightWorld extends World {
626
+ constructor(options) {
627
+ super(options);
628
+ this.launchUrl = this.parameters.launchUrl;
629
+ this.minWaitTime = this.parameters.minWaitTime;
630
+ this.playwrightBrowser = null;
631
+ this.context = null;
632
+ this.page = null;
633
+ this.assetsFolder = path.join(__dirname, '../assets/');
763
634
  }
764
- });
765
635
 
766
- /**
767
- * Assert that a link (located by its visible text) contains the given URL.
768
- *
769
- * Example #1: Then the "Login" link should contain "/log-in"
770
- * Example #2: And the "About Us" link should contain "/about"
771
- * Example #3: Then "Home" link should contain "/"
772
- *
773
- */
774
- Then(/^(the )*"([^"]*)?" link should contain "([^"]*)?"$/, async function (theCase, element, url) {
775
- const loc = this.page.getByText(element, { exact: true }).first();
776
- await loc.waitFor({ timeout: 5000 });
777
- const href = await loc.evaluate(el => el.href || el.getAttribute('href') || '');
778
- assert.ok(href.includes(url), `Expected link "${element}" href to contain "${url}" but got "${href}"`);
779
- });
780
-
781
- /**
782
- * Assert that a link located by its attribute contains the given URL.
783
- *
784
- * Example #1: Then the "#about-us-id" link should contain "about" by attr
785
- * Example #2: And the "aboutUs" link should contain "about" by its "class" attribute
786
- * Example #3: And the ".contactUs" link should contain "/contact-" by attr
787
- *
788
- */
789
- Then(/^(the )*"([^"]*)?" link should contain "([^"]*)?" by( its)*(?: "([^"]*)?")* (attribute|attr)$/, async function (theCase, attrValue, url, itsCase, attr, attrWord) {
790
- const loc = this.page.locator(buildSelector(attrValue, attr)).first();
791
- await loc.waitFor({ timeout: 5000 });
792
- const href = await loc.evaluate(el => el.href || el.getAttribute('href') || '');
793
- assert.ok(href.includes(url), `Expected element href to contain "${url}" but got "${href}"`);
794
- });
636
+ async openBrowser(extraContextOptions) {
637
+ const { browser: browserName, launchOptions, contextOptions } = playwrightConfig;
638
+ this.playwrightBrowser = await playwright[browserName].launch(launchOptions);
639
+ const merged = Object.assign({}, contextOptions, extraContextOptions || {});
640
+ this.context = await this.playwrightBrowser.newContext(merged);
641
+ // BBR: install in-flight fetch/XHR counter on every page (init script runs
642
+ // before any document script). The counter lets smartSettle() detect the
643
+ // edge of background activity rather than guessing a fixed delay.
644
+ await this.context.addInitScript(() => {
645
+ if (window.__webshipAjaxInstalled) return;
646
+ window.__webshipAjaxInstalled = true;
647
+ window.__webshipAjaxCount = 0;
648
+ window.__webshipPendingTimers = 0;
649
+ window.__webshipLastMutation = Date.now();
650
+
651
+ // Track in-flight fetch requests.
652
+ const origFetch = window.fetch;
653
+ if (typeof origFetch === 'function') {
654
+ window.fetch = function (...args) {
655
+ window.__webshipAjaxCount++;
656
+ const p = origFetch.apply(this, args);
657
+ const settle = () => { window.__webshipAjaxCount--; };
658
+ p.then(settle, settle);
659
+ return p;
660
+ };
661
+ }
795
662
 
796
- /**
797
- * Assert that HTML response contains or does not contain specific text.
798
- *
799
- * Example #1: Then the response should contain "Welcome visitor, How can I help you?"
800
- * Example #2: Then the response should not contain "Access denied"
801
- *
802
- */
803
- Then(/^(the )*response should( not)* contain "([^"]*)?"$/, async function (theCase, notCase, expectedText) {
804
- const text = await this.page.locator('html').textContent() || '';
805
- if (notCase) {
806
- assert.ok(!text.includes(expectedText), `Response should NOT contain "${expectedText}" but it does.`);
807
- } else {
808
- assert.ok(text.includes(expectedText), `Response should contain "${expectedText}" but it does not.`);
809
- }
810
- });
663
+ // Track in-flight XMLHttpRequests.
664
+ const XHR = window.XMLHttpRequest;
665
+ if (XHR && XHR.prototype) {
666
+ const origSend = XHR.prototype.send;
667
+ XHR.prototype.send = function (...args) {
668
+ window.__webshipAjaxCount++;
669
+ const settle = () => { window.__webshipAjaxCount--; };
670
+ this.addEventListener('loadend', settle, { once: true });
671
+ return origSend.apply(this, args);
672
+ };
673
+ }
811
674
 
812
- /**
813
- * Assert that an element (found by its label) contains or does not contain text.
814
- *
815
- * Example #1: Then I should see "John Smith" in the "Username" element
816
- * Example #2: Then I should not see "Joe Smith" in the "Username" element
817
- * Example #3: And we should see "1234" in the "Password" element
818
- *
819
- */
820
- Then(/^(I |we )*should( not)* see "([^"]*)?" in( the)* "([^"]*)?" element$/, async function (pronounCase, notCase, expectedText, theCase, element) {
821
- const forAttr = await this.page.getByText(element, { exact: true }).getAttribute('for').catch(() => null);
822
- const loc = this.page.locator(forAttr ? '#' + forAttr : element).first();
823
- await loc.waitFor({ timeout: 5000 });
824
- const content = await getLocatorText(loc);
825
- if (notCase) {
826
- assert.ok(!content.includes(expectedText), `Element should NOT contain "${expectedText}" but it does.`);
827
- } else {
828
- assert.ok(content.includes(expectedText), `Element should contain "${expectedText}" but it does not.`);
829
- }
830
- });
675
+ // Track pending setTimeout callbacks. Many client-side frameworks use
676
+ // setTimeout to schedule UI updates (animation frames, throttled
677
+ // re-renders, fade-out → display:none). BBR demands we wait for those
678
+ // timers to drain rather than guess a fixed delay.
679
+ const origSetTimeout = window.setTimeout;
680
+ const origClearTimeout = window.clearTimeout;
681
+ const liveTimers = new Set();
682
+ if (typeof origSetTimeout === 'function') {
683
+ window.setTimeout = function (cb, delay, ...args) {
684
+ window.__webshipPendingTimers++;
685
+ let id;
686
+ const wrapped = function () {
687
+ try {
688
+ if (typeof cb === 'function') return cb.apply(this, args);
689
+ } finally {
690
+ if (liveTimers.delete(id)) window.__webshipPendingTimers--;
691
+ }
692
+ };
693
+ id = origSetTimeout(wrapped, delay);
694
+ liveTimers.add(id);
695
+ return id;
696
+ };
697
+ if (typeof origClearTimeout === 'function') {
698
+ window.clearTimeout = function (id) {
699
+ if (liveTimers.delete(id)) window.__webshipPendingTimers--;
700
+ return origClearTimeout(id);
701
+ };
702
+ }
703
+ }
831
704
 
832
- /**
833
- * Assert that an element (found by its attribute) contains or does not contain text.
834
- *
835
- * Example #1: Then I should see "John Smith" in the "uname" element by its "id" attr
836
- * Example #2: Then I should see "1234" in the "pwordcss" element by attr
837
- * Example #3: Then I should not see "John Smith" in the "uname" element by its "id" attr
838
- * Example #4: Then I should not see "1234" in the "pwordcss" element by attr
839
- *
840
- */
841
- Then(/^(I |we )*should( not)* see "([^"]*)?" in( the)* "([^"]*)?" element by( its)*(?: "([^"]*)?")* (attribute|attr)$/, async function (pronounCase, notCase, expectedText, theCase, attrValue, itsCase, attr, attrWord) {
842
- const loc = this.page.locator(buildSelector(attrValue, attr)).first();
843
- await loc.waitFor({ timeout: 10000 });
844
- const content = await getLocatorText(loc);
845
- if (notCase) {
846
- assert.ok(!content.includes(expectedText), `Element should NOT contain "${expectedText}" but it does.`);
847
- } else {
848
- assert.ok(content.includes(expectedText), `Element should contain "${expectedText}" but it does not.`);
705
+ // Track last DOM mutation so smartSettle can wait for the *edge* of
706
+ // client-side rendering (animations, async hydration, transitions).
707
+ const startObserver = () => {
708
+ if (!document || !document.documentElement) return false;
709
+ try {
710
+ new MutationObserver(() => { window.__webshipLastMutation = Date.now(); })
711
+ .observe(document.documentElement, { childList: true, subtree: true, attributes: true, characterData: true });
712
+ return true;
713
+ } catch (e) { return false; }
714
+ };
715
+ if (!startObserver()) {
716
+ document.addEventListener('DOMContentLoaded', startObserver, { once: true });
717
+ }
718
+ });
719
+ this.page = await this.context.newPage();
849
720
  }
850
- });
851
721
 
852
- /**
853
- * Assert that an element with a given label exists (or does not) on the page.
854
- *
855
- * Example #1: Then I should see a "Username" element
856
- * Example #2: Then I should not see a "Username" element
857
- * Example #3: And we should see an "Email" element
858
- *
859
- */
860
- Then(/^(I |we )*should( not)* see (a|an) "([^"]*)?" element$/, async function (pronounCase, notCase, aAnCase, element) {
861
- if (notCase) {
862
- const text = await this.page.locator('body').textContent() || '';
863
- assert.ok(!text.includes(element), `Page should NOT contain element text "${element}" but it does.`);
864
- } else {
865
- const loc = this.page.getByText(element, { exact: true }).first();
866
- const forAttr = await loc.getAttribute('for').catch(() => null);
867
- if (forAttr) {
868
- await this.page.locator('#' + forAttr).waitFor({ state: 'visible', timeout: 3000 });
869
- } else {
870
- await loc.waitFor({ state: 'visible', timeout: 3000 });
722
+ async closeBrowser() {
723
+ if (this.playwrightBrowser) {
724
+ await this.playwrightBrowser.close();
725
+ this.playwrightBrowser = null;
726
+ this.context = null;
727
+ this.page = null;
871
728
  }
872
729
  }
873
- });
874
-
875
- /**
876
- * Assert that an element, identified by attribute, exists (or does not) on the page.
877
- *
878
- * Example #1: Then I should see a "uname" element by its "id" attr
879
- * Example #2: Then I should see a "pwordcss" element by attr
880
- * Example #3: Then I should not see an "emailId" element by its "id" attr
881
- * Example #4: And I should not see a "countryCss" element by attr
882
- *
883
- */
884
- Then(/^(I |we )*should( not)* see (a|an) "([^"]*)?" element by( its)*(?: "([^"]*)?")* (attribute|attr)$/, async function (pronounCase, notCase, aAnCase, attrValue, itsCase, attr, attrWord) {
885
- const loc = this.page.locator(buildSelector(attrValue, attr));
886
- if (notCase) {
887
- assert.strictEqual(await loc.count(), 0, `Element should NOT be present but it is.`);
888
- } else {
889
- await loc.first().waitFor({ state: 'visible', timeout: 3000 });
890
- }
891
- });
892
-
893
- /**
894
- * Assert that an element has or does not have a specific CSS property.
895
- *
896
- * Example #1: Then the "body" element should contain "color:white;"
897
- * Example #2: Then the "body" element should not contain "color:white;"
898
- * Example #3: Then the "#uname" element should not contain "border:solid 5px red;"
899
- * Example #4: Then the "pword" element should not contain "font-size: 26px;"
900
- *
901
- */
902
- Then(/^(the )*"([^"]*)?" element should( not)* contain "([^"]*)?"$/, async function (theCase, selectorRaw, notCase, elementCss) {
903
- const cssClean = elementCss.replace(/;$/, '');
904
- const colonIdx = cssClean.indexOf(':');
905
- const cssProperty = cssClean.substring(0, colonIdx).trim();
906
- const expectedValue = cssClean.substring(colonIdx + 1).trim();
907
-
908
- const loc = this.page.locator(buildSelector(selectorRaw)).first();
909
- await loc.waitFor({ timeout: 10000 });
910
- const matches = await loc.evaluate((el, { prop, expectedVal }) => {
911
- function colorToRgb(color) {
912
- const canvas = document.createElement('canvas');
913
- canvas.width = canvas.height = 1;
914
- const ctx = canvas.getContext('2d');
915
- ctx.fillStyle = 'rgb(1, 2, 3)';
916
- ctx.fillStyle = color.trim();
917
- ctx.fillRect(0, 0, 1, 1);
918
- const d = ctx.getImageData(0, 0, 1, 1).data;
919
- return 'rgb(' + d[0] + ', ' + d[1] + ', ' + d[2] + ')';
920
- }
921
- function isValidColor(value) { return colorToRgb(value) !== 'rgb(1, 2, 3)'; }
922
- function normalizeColorTokens(value) {
923
- return value.replace(/rgb\([^)]+\)|rgba\([^)]+\)|#[0-9a-fA-F]+|\b[a-zA-Z]+\b/g,
924
- (token) => isValidColor(token) ? colorToRgb(token) : token);
925
- }
926
- function tokenize(value) {
927
- const tokens = [], regex = /rgb\([^)]+\)|rgba\([^)]+\)|[^\s]+/g;
928
- let m;
929
- while ((m = regex.exec(value)) !== null) tokens.push(m[0]);
930
- return tokens;
931
- }
932
- const computed = window.getComputedStyle(el).getPropertyValue(prop).trim();
933
- return tokenize(normalizeColorTokens(expectedVal.toLowerCase()))
934
- .every(token => normalizeColorTokens(computed.toLowerCase()).includes(token));
935
- }, { prop: cssProperty, expectedVal: expectedValue });
730
+ }
936
731
 
937
- if (notCase) {
938
- assert.ok(!matches, `Element should NOT have CSS "${cssProperty}: ${expectedValue}" but it does.`);
939
- } else {
940
- assert.ok(matches, `Element should have CSS "${cssProperty}: ${expectedValue}".`);
941
- }
942
- });
732
+ setWorldConstructor(PlaywrightWorld);
943
733
 
944
- /**
945
- * Assert that a form field contains or does not contain specific text.
946
- *
947
- * Example #1: Then the "Username" field should contain "John Smith"
948
- * Example #2: Then the "#username" field should not contain "John Smith"
949
- * Example #3: And the "Email" field should contain "jon@example.com"
950
- *
951
- */
952
- Then(/^(the )*"([^"]*)?" field should( not)* contain "([^"]*)?"$/, async function (theCase, field, notCase, expectedText) {
953
- let selector = field;
954
- if (!field.startsWith('#') && !field.startsWith('.')) {
955
- const forAttr = await this.page.getByText(field, { exact: true }).getAttribute('for').catch(() => null);
956
- if (forAttr) selector = '#' + forAttr;
957
- }
958
- const loc = this.page.locator(selector).first();
959
- await loc.waitFor({ timeout: 5000 });
960
- const content = await getLocatorText(loc);
961
- if (notCase) {
962
- assert.ok(!content.includes(expectedText), `Field should NOT contain "${expectedText}" but it does.`);
963
- } else {
964
- assert.ok(content.includes(expectedText), `Field should contain "${expectedText}" but it does not.`);
965
- }
966
- });
734
+ // ---------------------------------------------------------------------------
735
+ // Video recording — Playwright records at browser-context creation. The
736
+ // helpers below resolve config + tags into either an empty {} (no
737
+ // recording) or { recordVideo: { dir, size } } that gets merged into the
738
+ // context options.
739
+ // ---------------------------------------------------------------------------
967
740
 
968
- /**
969
- * Assert that a checkbox should or should not be checked.
970
- *
971
- * Example #1: Then the "#PrivacyPolicy" checkbox should be checked
972
- * Example #2: Then the "#PrivacyPolicy" checkbox should not be checked
973
- *
974
- */
975
- Then(/^(the )*"([^"]*)?" checkbox should( not)* be checked$/, async function (theCase, checkbox, notCase) {
976
- const isChecked = await this.page.locator(checkbox).isChecked();
977
- if (notCase) {
978
- assert.ok(!isChecked, `Checkbox "${checkbox}" should NOT be checked but it is.`);
979
- } else {
980
- assert.ok(isChecked, `Checkbox "${checkbox}" should be checked but it is not.`);
981
- }
982
- });
741
+ const VIDEO_MODES = new Set(['off', 'on', 'on-failure', 'tag']);
742
+
743
+ function videoSettings(world, scope) {
744
+ const cfg = (world.parameters && world.parameters.video) || {};
745
+ let mode = process.env.WEBSHIP_VIDEO || cfg.mode || 'off';
746
+ if (!VIDEO_MODES.has(mode)) mode = 'off';
747
+ return {
748
+ mode,
749
+ dir: process.env.WEBSHIP_VIDEO_DIR || cfg.dir || './videos',
750
+ size: cfg.size || { width: 1280, height: 720 },
751
+ filenamePattern: cfg.filenamePattern || '{datetime}.{feature_file}.{scenario}.{status}.{ext}',
752
+ };
753
+ }
983
754
 
984
- /**
985
- * Assert that a checkbox is or is not checked.
986
- *
987
- * Example #1: Then the "#rememberMe" checkbox is checked
988
- * Example #2: Then the "#rememberMe" checkbox is not checked
989
- *
990
- */
991
- Then(/^(the )*"([^"]*)?" checkbox is( not)* checked$/, async function (theCase, checkbox, notCase) {
992
- const isChecked = await this.page.locator(checkbox).isChecked();
993
- if (notCase) {
994
- assert.ok(!isChecked, `Checkbox "${checkbox}" should NOT be checked but it is.`);
995
- } else {
996
- assert.ok(isChecked, `Checkbox "${checkbox}" should be checked but it is not.`);
997
- }
998
- });
755
+ function videoHasTag(scope, name) {
756
+ return !!(scope && scope.pickle && Array.isArray(scope.pickle.tags) &&
757
+ scope.pickle.tags.some((t) => t.name === name));
758
+ }
999
759
 
1000
- /**
1001
- * Assert that a named checkbox should or should not be checked.
1002
- *
1003
- * Example #1: Then the checkbox "#PrivacyPolicy" should be checked
1004
- * Example #2: Then the checkbox "#PrivacyPolicy" should not be checked
1005
- *
1006
- */
1007
- Then(/^(the )*checkbox "([^"]*)?" should( not)* be checked$/, async function (theCase, checkbox, notCase) {
1008
- const isChecked = await this.page.locator(checkbox).isChecked();
1009
- if (notCase) {
1010
- assert.ok(!isChecked, `Checkbox "${checkbox}" should NOT be checked but it is.`);
1011
- } else {
1012
- assert.ok(isChecked, `Checkbox "${checkbox}" should be checked but it is not.`);
1013
- }
1014
- });
760
+ function shouldRecordAtStart(s, scope) {
761
+ if (videoHasTag(scope, '@no-video')) return false;
762
+ if (videoHasTag(scope, '@video')) return true;
763
+ return s.mode === 'on' || s.mode === 'on-failure';
764
+ }
1015
765
 
1016
- /**
1017
- * Assert that a named checkbox is or is not checked.
1018
- *
1019
- * Example #1: Then the checkbox "#rememberMe" is checked
1020
- * Example #2: Then the checkbox "#rememberMe" is not checked
1021
- *
1022
- */
1023
- Then(/^(the )*checkbox "([^"]*)?" is( not)* checked$/, async function (theCase, checkbox, notCase) {
1024
- const isChecked = await this.page.locator(checkbox).isChecked();
1025
- if (notCase) {
1026
- assert.ok(!isChecked, `Checkbox "${checkbox}" should NOT be checked but it is.`);
1027
- } else {
1028
- assert.ok(isChecked, `Checkbox "${checkbox}" should be checked but it is not.`);
1029
- }
1030
- });
766
+ function sanitisePart(s) {
767
+ return String(s || '').replace(/[^a-zA-Z0-9._-]+/g, '_').slice(0, 80);
768
+ }
1031
769
 
1032
- /**
1033
- * Assert that a radio button should or should not be selected.
1034
- *
1035
- * Example #1: Then the radio button "#gender-male" should be selected
1036
- * Example #2: Then the radio button "#gender-female" should not be selected
1037
- * Example #3: Then the radio button ".option-1" should be selected
1038
- *
1039
- */
1040
- Then(/^(the )*radio button "([^"]*)?" should( not)* be selected$/, async function (theCase, radioButton, notCase) {
1041
- const isChecked = await this.page.locator(radioButton).isChecked();
1042
- if (notCase) {
1043
- assert.ok(!isChecked, `Radio button "${radioButton}" should NOT be selected but it is.`);
1044
- } else {
1045
- assert.ok(isChecked, `Radio button "${radioButton}" should be selected but it is not.`);
1046
- }
1047
- });
770
+ function buildVideoFilename(template, scope, status) {
771
+ const featurePath = (scope && scope.gherkinDocument && scope.gherkinDocument.uri) || 'unknown';
772
+ const feature = (scope && scope.gherkinDocument && scope.gherkinDocument.feature && scope.gherkinDocument.feature.name) || 'feature';
773
+ const scenario = (scope && scope.pickle && scope.pickle.name) || 'scenario';
774
+ const featureFile = featurePath.split('/').pop().replace(/\.feature$/, '');
775
+ const dt = new Date().toISOString().replace(/[:.]/g, '-');
776
+ return template
777
+ .replace('{datetime}', dt)
778
+ .replace('{feature_file}', sanitisePart(featureFile))
779
+ .replace('{feature}', sanitisePart(feature))
780
+ .replace('{scenario}', sanitisePart(scenario))
781
+ .replace('{status}', sanitisePart(status))
782
+ .replace('{ext}', 'webm');
783
+ }
1048
784
 
1049
- /**
1050
- * Assert that a radio button with a given value should or should not be selected.
1051
- *
1052
- * Example #1: Then the radio button with value "male" should be selected
1053
- * Example #2: Then the radio button with value "female" should not be selected
1054
- *
1055
- */
1056
- Then(/^(the )*radio button with value "([^"]*)?" should( not)* be selected$/, async function (theCase, radioValue, notCase) {
1057
- const isChecked = await this.page.locator(`input[type="radio"][value="${radioValue}"]`).first().isChecked();
1058
- if (notCase) {
1059
- assert.ok(!isChecked, `Radio button with value "${radioValue}" should NOT be selected but it is.`);
1060
- } else {
1061
- assert.ok(isChecked, `Radio button with value "${radioValue}" should be selected but it is not.`);
1062
- }
1063
- });
785
+ Before({ order: 5 }, async function (scope) {
786
+ this._videoSettings = videoSettings(this, scope);
787
+ this._videoRequested = shouldRecordAtStart(this._videoSettings, scope);
788
+ this._videoForcedByTag = videoHasTag(scope, '@video');
1064
789
 
1065
- /**
1066
- * Assert that the radio button is or is not selected.
1067
- *
1068
- * Example #1: Then the "#gender-male" radio button is selected
1069
- * Example #2: Then the "#gender-female" radio button is not selected
1070
- *
1071
- */
1072
- Then(/^(the )*"([^"]*)?" radio button is( not)* selected$/, async function (theCase, radioButton, notCase) {
1073
- const isChecked = await this.page.locator(radioButton).isChecked();
1074
- if (notCase) {
1075
- assert.ok(!isChecked, `Radio button "${radioButton}" should NOT be selected but it is.`);
1076
- } else {
1077
- assert.ok(isChecked, `Radio button "${radioButton}" should be selected but it is not.`);
790
+ const extra = {};
791
+ if (this._videoRequested) {
792
+ require('fs').mkdirSync(this._videoSettings.dir, { recursive: true });
793
+ extra.recordVideo = {
794
+ dir: this._videoSettings.dir,
795
+ size: this._videoSettings.size,
796
+ };
1078
797
  }
1079
- });
1080
798
 
1081
- /**
1082
- * Assert that the current page's response status is or is not a given code.
1083
- *
1084
- * Example #1: Then the response status code should be 200
1085
- * Example #2: And the response status code should not be 404
1086
- * Example #3: Then the response status code should be 301
1087
- *
1088
- */
1089
- Then(/^(the )*response status code should( not)* be (\d+)$/, async function (theCase, notCase, expectedStatusCode) {
1090
- const currentURL = this.page.url();
1091
- try {
1092
- const response = await axios.get(currentURL);
1093
- const status = response.status;
1094
- if (notCase) {
1095
- assert.notStrictEqual(status, parseInt(expectedStatusCode), `Status code should NOT be ${expectedStatusCode}`);
1096
- } else {
1097
- assert.strictEqual(status, parseInt(expectedStatusCode), `Expected status ${expectedStatusCode} but got ${status}`);
1098
- }
1099
- } catch (error) {
1100
- const status = error.response ? error.response.status : null;
1101
- if (notCase) {
1102
- if (status !== null) assert.notStrictEqual(status, parseInt(expectedStatusCode));
1103
- } else {
1104
- assert.strictEqual(status, parseInt(expectedStatusCode), `Expected status ${expectedStatusCode} but got ${status}`);
1105
- }
799
+ await this.openBrowser(extra);
800
+ if (this.minWaitTime.before_scenario > 0) {
801
+ await this.page.waitForTimeout(this.minWaitTime.before_scenario);
1106
802
  }
1107
803
  });
1108
804
 
1109
- /**
1110
- * Assert that page contains or does not contain text matching a regex pattern.
1111
- *
1112
- * Example #1: Then I should see text matching "^T\w+"
1113
- * Example #2: Then I should not see text matching "^O\w+"
1114
- * Example #3: And we should see text matching "\d{4}"
1115
- *
1116
- */
1117
- Then(/^(I |we )*should( not)* see text matching "([^"]*)?"$/, async function (pronounCase, notCase, textPattern) {
1118
- const bodyText = await this.page.evaluate(() => document.body.innerText || '');
1119
- const regex = new RegExp(textPattern);
1120
- if (notCase) {
1121
- assert.ok(!regex.test(bodyText), `Page text should NOT match "${textPattern}" but it does.`);
1122
- } else {
1123
- assert.ok(regex.test(bodyText), `Page text should match "${textPattern}" but it does not.`);
805
+ After({ order: 5 }, async function (scope) {
806
+ if (this.minWaitTime.after_scenario > 0) {
807
+ try { await this.page.waitForTimeout(this.minWaitTime.after_scenario); } catch { /* page already closed */ }
1124
808
  }
1125
- });
1126
809
 
1127
- /**
1128
- * Assert that an element contains or does not contain text matching a pattern.
1129
- *
1130
- * Example #1: Then I should see text matching "(0?[1-9]|[12][0-9]|3[01])[\/\-](0?[1-9]|1[012])[\/\-]\d{4}" in the "#date" element
1131
- * Example #2: Then I should not see text matching "(0?[1-9]|[12][0-9]|3[01])[\/\-](0?[1-9]|1[012])[\/\-]\d{4}" in the "#date" element
1132
- *
1133
- */
1134
- Then(/^(I |we )*should( not)* see text matching "([^"]*)?" in( the)* "([^"]*)?" element$/, async function (pronounCase, notCase, textPattern, theCase, element) {
1135
- const loc = this.page.locator(element).first();
1136
- await loc.waitFor({ timeout: 5000 });
1137
- const text = await getLocatorText(loc);
1138
- const regex = new RegExp(textPattern);
1139
- if (notCase) {
1140
- assert.ok(!regex.test(text), `Element "${element}" text should NOT match "${textPattern}" but it does.`);
1141
- } else {
1142
- assert.ok(regex.test(text), `Element "${element}" text should match "${textPattern}" but it does not.`);
810
+ const status = (scope && scope.result && scope.result.status) || 'unknown';
811
+ const videoRef = (this._videoRequested && this.page) ? this.page.video() : null;
812
+ // Capture the raw Playwright path BEFORE closing the context — after
813
+ // close, the remote handle is gone and video.path() throws.
814
+ let rawPath = null;
815
+ if (videoRef) {
816
+ try { rawPath = await videoRef.path(); } catch { /* may throw on remote */ }
1143
817
  }
1144
- });
1145
818
 
1146
- /**
1147
- * Assert that the current URL matches or does not match a regex pattern.
1148
- *
1149
- * Example #1: Then the url should match "/contact-us.html"
1150
- * Example #2: Then the url should not match "/contact-us.html"
1151
- * Example #3: And the url should match "^https://"
1152
- *
1153
- */
1154
- Then(/^(the )*url should( not)* match "([^"]*)?"$/, async function (theCase, notCase, pattern) {
1155
- const currentUrl = this.page.url();
1156
- const regex = new RegExp(pattern);
1157
- if (notCase) {
1158
- assert.ok(!regex.test(currentUrl), `URL "${currentUrl}" should NOT match "${pattern}" but it does.`);
1159
- } else {
1160
- assert.ok(regex.test(currentUrl), `URL "${currentUrl}" should match "${pattern}" but it does not.`);
819
+ // Close the *context* (flushes the webm to disk). Browser stays up so
820
+ // saveAs() / delete() can still talk to it.
821
+ if (this.context) {
822
+ try { await this.context.close(); } catch { /* ignore */ }
1161
823
  }
1162
- });
1163
824
 
1164
- /**
1165
- * Attach a file from tests/assets/ to a file input.
1166
- *
1167
- * Example #1: When I attach the file "profileIcon.jpg" to "#profile-icon-upload"
1168
- * Example #2: And we attach file "resume.pdf" to "#resume"
1169
- *
1170
- */
1171
- When(/^(I |we )*attach( the)* file "([^"]*)?" to "([^"]*)?"$/, async function (pronounCase, theCase, fileName, element) {
1172
- await this.page.locator(element).setInputFiles(path.resolve(this.assetsFolder, fileName));
1173
- });
1174
-
1175
- /**
1176
- * Wait a specific number of seconds.
1177
- *
1178
- * Example #1: When I wait 1 second
1179
- * Example #2: When I wait 5 seconds
1180
- * Example #3: When we wait 3s
1181
- * Example #4: And wait 2s
1182
- * Example #5: And wait 2 seconds
1183
- * Example #6: When we wait 1 second
1184
- * Example #7: When we wait 5 seconds
1185
- * Example #8: When we wait 4s
1186
- *
1187
- */
1188
- When(/^(I |we )*wait (\d*)( second| seconds|s)?$/, async function (pronounCase, number, withSecondWord) {
1189
- await this.page.waitForTimeout(parseInt(number) * 1000);
1190
- });
1191
-
1192
- /**
1193
- * Wait a max number of seconds until the page body is present.
1194
- *
1195
- * Example #1: When I wait max of 1 second
1196
- * Example #2: When I wait max of 5 seconds
1197
- * Example #3: When we wait max of 3s
1198
- * Example #4: And wait max of 2s
1199
- * Example #5: And wait max of 2 seconds
1200
- * Example #6: When we wait max of 1 second
1201
- * Example #7: When we wait max of 5 seconds
1202
- * Example #8: When we wait max of 4s
1203
- *
1204
- */
1205
- When(/^(I |we )*wait max of (\d*)( second| seconds|s)?$/, async function (pronounCase, number, withSecondWord) {
1206
- await this.page.waitForTimeout(parseInt(number) * 1000);
1207
- });
1208
-
1209
- /**
1210
- * Wait a specific number of minutes.
1211
- *
1212
- * Example #1: When I wait 1 minute
1213
- * Example #2: When I wait 10 minutes
1214
- * Example #3: When we wait 1m
1215
- * Example #4: And wait 2m
1216
- * Example #5: And wait 2 minutes
1217
- * Example #6: When we wait 1 minute
1218
- * Example #7: When we wait 10 minutes
1219
- *
1220
- */
1221
- When(/^(I |we )*wait (\d*)( minute| minutes|m)?$/, async function (pronounCase, number, withMinuteWord) {
1222
- await this.page.waitForTimeout(parseInt(number) * 1000 * 60);
1223
- });
1224
-
1225
- /**
1226
- * Wait a max number of minutes until the page body is present.
1227
- *
1228
- * Example #1: When I wait max of 1 minute
1229
- * Example #2: When I wait max of 10 minutes
1230
- * Example #3: When we wait max of 1m
1231
- * Example #4: And wait max of 2m
1232
- * Example #5: And wait max of 2 minutes
1233
- *
1234
- */
1235
- When(/^(I |we )*wait max of (\d*)( minute| minutes|m)?$/, async function (pronounCase, number, withMinuteWord) {
1236
- await this.page.waitForTimeout(parseInt(number) * 1000 * 60);
1237
- });
1238
-
1239
- /**
1240
- * Wait until the page is loaded.
1241
- *
1242
- * Example #1: When I wait until the page is loaded
1243
- * Example #2: When we wait until the page is loaded
1244
- * Example #3: When wait until page loaded
1245
- *
1246
- */
1247
- When(/^(I |we )*wait until( the)* page( is)* loaded*$/, async function (pronounCase, theCase, withIs) {
1248
- await waitForPageLoad(this.page, 10000);
1249
- });
1250
-
1251
- /**
1252
- * Wait for active XHR/fetch requests to complete.
1253
- *
1254
- * Example #1: When I wait for AJAX to finish
1255
- * Example #2: And I wait for AJAX to finish
1256
- * Example #3: When we wait for AJAX to finish
1257
- * Example #4: And wait for AJAX to finish
1258
- *
1259
- */
1260
- When(/^(I |we )*wait for AJAX to finish$/, async function (pronounCase) {
1261
- await this.page.waitForLoadState('networkidle', { timeout: 10000 }).catch(() => {});
1262
- });
1263
-
1264
- /**
1265
- * Scrolls the page down by a custom number of pixels (default 350).
1266
- *
1267
- * Example #1: And I scroll down
1268
- * Example #2: When I scroll down 800
1269
- * Example #3: And we scroll down 500
1270
- * Example #4: When scrolling down 1200
1271
- *
1272
- */
1273
- When(/^(I scroll|we scroll|scrolling)? down(?: (\d+))?$/, async function (pronounCase, numValue) {
1274
- await this.page.evaluate((v) => window.scrollBy(0, v), numValue ? parseInt(numValue, 10) : 350);
1275
- });
1276
-
1277
- /**
1278
- * Scrolls the page up by a custom number of pixels (default 350).
1279
- *
1280
- * Example #1: And I scroll up
1281
- * Example #2: When I scroll up 1000
1282
- * Example #3: And we scroll up 300
1283
- * Example #4: When scrolling up 750
1284
- *
1285
- */
1286
- When(/^(I scroll|we scroll|scrolling)? up(?: (\d+))?$/, async function (pronounCase, numValue) {
1287
- await this.page.evaluate((v) => window.scrollBy(0, -v), numValue ? parseInt(numValue, 10) : 350);
1288
- });
1289
-
1290
- /**
1291
- * Scrolls to the very top of the current page.
1292
- *
1293
- * Example #1: When I scroll to top
1294
- * Example #2: And we scroll to the top
1295
- * Example #3: When scrolling to the top of the page
1296
- *
1297
- */
1298
- When(/^(I scroll|we scroll|scrolling)? to( the)* top( of the page)*$/, async function (pronounCase, theCase, pageCase) {
1299
- await this.page.evaluate(() => window.scrollTo(0, 0));
1300
- });
1301
-
1302
- /**
1303
- * Scrolls to the bottom of the current page.
1304
- *
1305
- * Example #1: When I scroll to the bottom
1306
- * Example #2: And we scroll to bottom
1307
- * Example #3: When scrolling to the bottom of the page
1308
- *
1309
- */
1310
- When(/^(I scroll|we scroll|scrolling)? to( the)* bottom( of the page)*$/, async function (pronounCase, theCase, pageCase) {
1311
- await this.page.evaluate(() => {
1312
- window.scrollTo(0, document.body.scrollHeight);
1313
- document.querySelectorAll('*').forEach(el => {
1314
- const s = window.getComputedStyle(el);
1315
- if ((s.overflowY === 'scroll' || s.overflowY === 'auto') && el.scrollHeight > el.clientHeight) {
1316
- el.scrollTop = el.scrollHeight;
1317
- el.dispatchEvent(new Event('scroll', { bubbles: true }));
825
+ if (videoRef) {
826
+ const settings = this._videoSettings;
827
+ const filename = this._videoSaveAsName || buildVideoFilename(settings.filenamePattern, scope, status);
828
+ const dest = require('path').join(settings.dir, filename);
829
+ try {
830
+ const passed = status === 'PASSED' || status === 'passed';
831
+ if (settings.mode === 'on-failure' && passed && !this._videoForcedByTag) {
832
+ await videoRef.delete().catch(() => {});
833
+ } else {
834
+ await videoRef.saveAs(dest);
835
+ await videoRef.delete().catch(() => {});
836
+ process.stderr.write(`\n[webship-js] video saved → ${dest}\n`);
1318
837
  }
1319
- });
1320
- });
1321
- });
1322
-
1323
- /**
1324
- * Scrolls to the top of a specific element identified by a CSS selector.
1325
- *
1326
- * Example #1: When I scroll to top of "#off-canvas"
1327
- * Example #2: And we scroll to top of "#sidebar"
1328
- * Example #3: When scrolling to top of "#main-container"
1329
- *
1330
- */
1331
- When(/^(I scroll|we scroll|scrolling)? to top of "([^"]*)"$/, async function (pronounCase, selector) {
1332
- await this.page.locator(selector).evaluate(el => {
1333
- el.scrollTop = 0;
1334
- el.dispatchEvent(new Event('scroll', { bubbles: true }));
1335
- });
1336
- });
1337
-
1338
- /**
1339
- * Scrolls to the bottom of a specific element identified by a CSS selector.
1340
- *
1341
- * Example #1: When I scroll to bottom of "#off-canvas"
1342
- * Example #2: And we scroll to bottom of "#sidebar"
1343
- * Example #3: When scrolling to bottom of "#main-container"
1344
- *
1345
- */
1346
- When(/^(I scroll|we scroll|scrolling)? to bottom of "([^"]*)"$/, async function (pronounCase, selector) {
1347
- await this.page.locator(selector).evaluate(el => {
1348
- el.scrollTop = el.scrollHeight;
1349
- el.dispatchEvent(new Event('scroll', { bubbles: true }));
1350
- });
1351
- });
1352
-
1353
- /**
1354
- * Scrolls the page right by a custom number of pixels (default 350).
1355
- *
1356
- * Example #1: And I scroll right
1357
- * Example #2: When I scroll right 1000
1358
- * Example #3: And we scroll right 300
1359
- * Example #4: When scrolling right 750
1360
- *
1361
- */
1362
- When(/^(I scroll|we scroll|scrolling)? right(?: (\d+))?$/, async function (pronounCase, numValue) {
1363
- await this.page.evaluate((v) => window.scrollBy(v, 0), numValue ? parseInt(numValue, 10) : 350);
1364
- });
1365
-
1366
- /**
1367
- * Scrolls the page left by a custom number of pixels (default 350).
1368
- *
1369
- * Example #1: And I scroll left
1370
- * Example #2: When I scroll left 800
1371
- * Example #3: And we scroll left 500
1372
- * Example #4: When scrolling left 1200
1373
- *
1374
- */
1375
- When(/^(I scroll|we scroll|scrolling)? left(?: (\d+))?$/, async function (pronounCase, numValue) {
1376
- await this.page.evaluate((v) => window.scrollBy(-v, 0), numValue ? parseInt(numValue, 10) : 350);
1377
- });
1378
-
1379
- /**
1380
- * Scrolls to the start (horizontal origin) of the page.
1381
- *
1382
- * Example #1: When I scroll to start
1383
- * Example #2: And we scroll to the start
1384
- * Example #3: When scrolling to the start of the page
1385
- *
1386
- */
1387
- When(/^(I scroll|we scroll|scrolling)? to( the)* start( of the page)*$/, async function (pronounCase, theCase, pageCase) {
1388
- await this.page.evaluate(() => window.scrollTo(0, window.scrollY));
1389
- });
1390
-
1391
- /**
1392
- * Scrolls to the end (horizontal maximum) of the page.
1393
- *
1394
- * Example #1: When I scroll to the end
1395
- * Example #2: And we scroll to end
1396
- * Example #3: When scrolling to the end of the page
1397
- *
1398
- */
1399
- When(/^(I scroll|we scroll|scrolling)? to( the)* end( of the page)*$/, async function (pronounCase, theCase, pageCase) {
1400
- await this.page.evaluate(() => window.scrollTo(document.body.scrollWidth, window.scrollY));
1401
- });
1402
-
1403
- /**
1404
- * Scrolls to the start of a specific element identified by a CSS selector.
1405
- *
1406
- * Example #1: When I scroll to start of "#off-canvas"
1407
- * Example #2: And we scroll to start of "#sidebar"
1408
- * Example #3: When scrolling to start of "#main-container"
1409
- *
1410
- */
1411
- When(/^(I scroll|we scroll|scrolling)? to start of "([^"]*)"$/, async function (pronounCase, selector) {
1412
- await this.page.locator(selector).evaluate(el => { el.scrollLeft = 0; });
1413
- });
1414
-
1415
- /**
1416
- * Scrolls to the end of a specific element identified by a CSS selector.
1417
- *
1418
- * Example #1: When I scroll to end of "#off-canvas"
1419
- * Example #2: And we scroll to end of "#sidebar"
1420
- * Example #3: When scrolling to end of "#main-container"
1421
- *
1422
- */
1423
- When(/^(I scroll|we scroll|scrolling)? to end of "([^"]*)"$/, async function (pronounCase, selector) {
1424
- await this.page.locator(selector).evaluate(el => { el.scrollLeft = el.scrollWidth; });
1425
- });
1426
-
1427
- /**
1428
- * Assert that a modal dialog is visible or not visible on the page.
1429
- *
1430
- * Example #1: Then I should see a modal
1431
- * Example #2: Then I should see the modal
1432
- * Example #3: Then we should see a modal dialog
1433
- * Example #4: Then I should not see a modal
1434
- * Example #5: Then I should not see the modal dialog
1435
- *
1436
- */
1437
- Then(/^(I |we )*should( not)* see (a |the )*modal( dialog)*$/, async function (pronounCase, notCase, aTheCase, dialogCase) {
1438
- const visible = await isAnyModalVisible(this.page);
1439
- if (notCase) {
1440
- assert.ok(!visible, 'Modal dialog is visible, but it should not be.');
1441
- } else {
1442
- assert.ok(visible, 'Modal dialog is not visible, but it should be.');
1443
- }
1444
- });
1445
-
1446
- /**
1447
- * Assert that a modal dialog with a given title is visible or not visible.
1448
- *
1449
- * Example #1: Then I should see a modal with title "Confirm Action"
1450
- * Example #2: Then I should see the modal with title "Welcome"
1451
- * Example #3: Then we should see a modal with title "Welcome Message"
1452
- * Example #4: Then I should not see a modal with title "Error"
1453
- * Example #5: Then I should not see the modal with title "Validation Error"
1454
- *
1455
- */
1456
- Then(/^(I |we )*should( not)* see (a |the )*modal with title "([^"]*)?"$/, async function (pronounCase, notCase, aTheCase, title) {
1457
- const modal = this.page.locator(MODAL_SELECTOR);
1458
- const byHeading = modal.locator('.modal-title, .dialog-title, h1, h2, h3').filter({ hasText: title });
1459
- const byAttr = modal.locator(`[title*="${title}"], [aria-label*="${title}"]`);
1460
- const found = await byHeading.count() > 0 || await byAttr.count() > 0;
1461
- if (notCase) {
1462
- assert.ok(!found, `Modal with title "${title}" is visible, but it should not be.`);
1463
- } else {
1464
- assert.ok(found, `Modal with title "${title}" is not visible or not found.`);
838
+ } catch (e) {
839
+ process.stderr.write(`\n[webship-js] video save failed: ${e.message}\n`);
840
+ }
841
+ // Fallback: remove the Playwright scratch file via fs if it still exists.
842
+ if (rawPath) {
843
+ try { require('fs').unlinkSync(rawPath); } catch { /* already gone */ }
844
+ }
1465
845
  }
1466
- });
1467
846
 
1468
- /**
1469
- * Assert that a specific modal by id/class/data-modal is visible or not.
1470
- *
1471
- * Example #1: Then I should see a "confirmation-modal" modal
1472
- * Example #2: Then I should see the "#delete-modal" modal
1473
- * Example #3: Then we should see a "settings-modal" modal
1474
- * Example #4: Then I should not see a "error-modal" modal
1475
- * Example #5: Then I should not see the "#success-modal" modal
1476
- *
1477
- */
1478
- Then(/^(I |we )*should( not)* see (a |the )*"([^"]*)?" modal$/, async function (pronounCase, notCase, aTheCase, identifier) {
1479
- const selector = (identifier.startsWith('#') || identifier.startsWith('.'))
1480
- ? identifier
1481
- : `#${identifier}, .${identifier}, [data-modal="${identifier}"]`;
1482
- const visible = await this.page.locator(selector).first().isVisible();
1483
- if (notCase) {
1484
- assert.ok(!visible, `Modal "${identifier}" is visible, but it should not be.`);
1485
- } else {
1486
- assert.ok(visible, `Modal "${identifier}" is not visible or not found.`);
847
+ // Finally close the browser.
848
+ if (this.playwrightBrowser) {
849
+ try { await this.playwrightBrowser.close(); } catch { /* ignore */ }
850
+ this.playwrightBrowser = null;
1487
851
  }
852
+ this.context = null;
853
+ this.page = null;
1488
854
  });
1489
855
 
1490
- /**
1491
- * Assert that a modal contains or does not contain specific text.
1492
- *
1493
- * Example #1: Then I should see "Are you sure?" in the modal
1494
- * Example #2: Then I should see "Delete this item" in the modal
1495
- * Example #3: Then we should see "Confirmation required" in the modal dialog
1496
- * Example #4: Then I should not see "Error occurred" in the modal
1497
- *
1498
- */
1499
- Then(/^(I |we )*should( not)* see "([^"]*)?" in( the)* modal( dialog)*$/, async function (pronounCase, notCase, expectedText, theCase, dialogCase) {
1500
- const found = await this.page.locator(MODAL_SELECTOR).filter({ hasText: expectedText }).count() > 0;
1501
- if (notCase) {
1502
- assert.ok(!found, `Found "${expectedText}" in modal, but it should not be there.`);
1503
- } else {
1504
- assert.ok(found, `Could not find "${expectedText}" in modal.`);
856
+ BeforeStep(async function () {
857
+ if (this.page && this.minWaitTime.before_step > 0) {
858
+ await this.page.waitForTimeout(this.minWaitTime.before_step);
1505
859
  }
1506
860
  });
1507
861
 
1508
- /**
1509
- * Click a button or link inside a modal dialog.
1510
- *
1511
- * Example #1: When I click "Confirm" in the modal
1512
- * Example #2: When I click "Cancel" in the modal dialog
1513
- * Example #3: When we click "OK" button in the modal
1514
- * Example #4: And I click "Close" in the modal
1515
- *
1516
- */
1517
- When(/^(I |we )*click "([^"]*)?"( button)* in( the)* modal( dialog)*$/, async function (pronounCase, buttonText, buttonCase, theCase, dialogCase) {
1518
- await waitForModalState(this.page, 'visible', 10000);
1519
- const modal = await findVisibleModal(this.page);
1520
- await modal.locator('button, a, [role="button"], input[type="button"], input[type="submit"], .btn')
1521
- .filter({ hasText: buttonText })
1522
- .first()
1523
- .click();
1524
- });
862
+ // BBR: regex matches steps that mutate page state (click/press/fill/check/etc.).
863
+ // After such a step, run a short smartSettle so assertions in the next step
864
+ // observe the post-action edge instead of mid-transition state.
865
+ const STATE_MUTATING_STEP = /\b(click|press|fill|submit|select|check|uncheck|choose|attach|reload|move (?:back|forward)|go to|navigate|on (?:the )?(?:home|front)page)\b/i;
1525
866
 
1526
- /**
1527
- * Close or dismiss a modal dialog (uses close button, or Escape fallback).
1528
- *
1529
- * Example #1: When I close the modal
1530
- * Example #2: When I dismiss the modal dialog
1531
- * Example #3: When we close the modal
1532
- * Example #4: And I dismiss the modal
1533
- *
1534
- */
1535
- When(/^(I |we )*(close|dismiss)( the)* modal( dialog)*$/, async function (pronounCase, closeOrDismiss, theCase, dialogCase) {
1536
- await waitForModalState(this.page, 'visible', 10000);
1537
- const modal = await findVisibleModal(this.page);
1538
- const closeBtn = modal.locator('.close, .modal-close, [data-dismiss="modal"], [aria-label="Close"], .btn-close, button[class*="close"]').first();
1539
- if (await closeBtn.isVisible()) {
1540
- await closeBtn.click();
1541
- } else {
1542
- await modal.press('Escape');
867
+ AfterStep(async function (scope) {
868
+ if (!this.page) return;
869
+ if (this.minWaitTime.after_step > 0) {
870
+ await this.page.waitForTimeout(this.minWaitTime.after_step);
1543
871
  }
872
+ // Auto-settle only after state-changing steps. Skip if disabled via env var.
873
+ if (process.env.WEBSHIP_AUTO_SETTLE === 'off') return;
874
+ const text = scope && scope.pickleStep && scope.pickleStep.text;
875
+ if (typeof text !== 'string') return;
876
+ if (!STATE_MUTATING_STEP.test(text)) return;
877
+ try { await smartSettle(this.page, 1500); } catch { /* best effort */ }
1544
878
  });
1545
879
 
1546
- /**
1547
- * Wait for a modal dialog to appear or disappear.
1548
- *
1549
- * Example #1: When I wait for the modal to appear
1550
- * Example #2: When I wait for the modal to disappear
1551
- * Example #3: When we wait for modal to appear
1552
- * Example #4: And I wait for the modal dialog to disappear
1553
- *
1554
- */
1555
- When(/^(I |we )*wait for( the)* modal( dialog)* to (appear|disappear)$/, async function (pronounCase, theCase, dialogCase, appearOrDisappear) {
1556
- const state = appearOrDisappear === 'appear' ? 'visible' : 'hidden';
1557
- await waitForModalState(this.page, state, 10000);
1558
- });
1559
880
 
1560
881
  // ===========================================================================
1561
- // STEP DEFINITIONS — Follow link, count elements, debug helpers.
882
+ // All step definitions previously defined in this file have been split out
883
+ // by topic. Cucumber-js auto-loads every *.steps.js in tests/step-definitions/,
884
+ // so feature files keep working unchanged.
885
+ //
886
+ // Topical homes:
887
+ // navigation.steps.js Given/When/Then for sessions, homepage, paths, history
888
+ // action.steps.js press, click (text/attr/row), follow, attach file
889
+ // form.steps.js fill, select, additionally select, check, uncheck, radio
890
+ // assertion.steps.js should see / not see, in row, in element, response,
891
+ // text matching, link href, count, status code
892
+ // field.steps.js field/checkbox/radio state assertions
893
+ // modal.steps.js modal visibility, content, button click, close
894
+ // wait.steps.js every BBR wait phrasing
895
+ // scroll.steps.js page + scoped element scrolling
896
+ // debug.steps.js print URL / response (debug only)
1562
897
  // ===========================================================================
1563
-
1564
- /**
1565
- * Follow a link by its visible text.
1566
- * Uses Playwright's accessibility-first `getByRole('link', { name })` with a
1567
- * text-match fallback.
1568
- *
1569
- * Example #1: When I follow "Contact Us"
1570
- * Example #2: When I follow "About"
1571
- * Example #3: When we follow "Home"
1572
- * Example #4: And follow "Read more"
1573
- * Example #5: When I follow "Documentation"
1574
- * Example #6: When we follow "Sign in"
1575
- * Example #7: When I follow "Log out"
1576
- * Example #8: When I follow "Download report"
1577
- * Example #9: And I follow "Previous"
1578
- * Example #10: When I follow "Next"
1579
- */
1580
- When(/^(I |we )*follow "([^"]*)"$/, async function (pronounCase, link) {
1581
- const esc = link.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
1582
- const loc = this.page.getByRole('link', { name: link, exact: true }).or(
1583
- this.page.locator('a').filter({ hasText: new RegExp('^' + esc + '$') })
1584
- ).first();
1585
- await loc.click();
1586
- });
1587
-
1588
- /**
1589
- * Assert the exact number of elements matching a CSS selector.
1590
- *
1591
- * Example #1: Then I should see 3 "li" elements
1592
- * Example #2: Then I should see 1 "h1" element
1593
- * Example #3: Then we should see 5 ".card" elements
1594
- * Example #4: Then I should see 0 ".error" elements
1595
- * Example #5: And I should see 10 "table tr" elements
1596
- * Example #6: Then I should see 2 "nav a" elements
1597
- * Example #7: Then we should see 4 "ul li" elements
1598
- * Example #8: Then I should see 1 "form" element
1599
- * Example #9: And should see 6 ".product" elements
1600
- * Example #10: Then I should see 8 "[data-testid='row']" elements
1601
- */
1602
- Then(/^(I |we )*should see (\d+) "([^"]*)" elements?$/, async function (pronounCase, num, selector) {
1603
- const expected = parseInt(num, 10);
1604
- const actual = await this.page.locator(selector).count();
1605
- if (actual !== expected) {
1606
- throw new Error(`Expected ${expected} "${selector}" element(s), got ${actual}.`);
1607
- }
1608
- });
1609
-
1610
- /**
1611
- * Print the current page URL to console (debug).
1612
- *
1613
- * Example #1: Then print current URL
1614
- * Example #2: When print current URL
1615
- * Example #3: And print current URL
1616
- */
1617
- Then(/^print current URL$/, function () {
1618
- console.log('\n--- Current URL ---');
1619
- console.log(` ${this.page.url()}`);
1620
- });
1621
-
1622
- /**
1623
- * Print the full page HTML (last response) to console (debug).
1624
- *
1625
- * Example #1: Then print last response
1626
- * Example #2: When print last response
1627
- * Example #3: And print last response
1628
- */
1629
- Then(/^print last response$/, async function () {
1630
- const html = await this.page.content();
1631
- console.log('\n--- Last Response (HTML) ---');
1632
- console.log(html);
1633
- });