webship-js 2.0.2 → 2.0.3

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 (162) hide show
  1. package/AGENTS.md +109 -0
  2. package/CLAUDE.md +317 -0
  3. package/bin/generate-reports.js +181 -9
  4. package/cucumber.js +10 -4
  5. package/docs/00-quick-start.md +102 -0
  6. package/docs/01-getting-started.md +102 -0
  7. package/docs/02-bbr-smart-waits.md +77 -0
  8. package/docs/03-selector-registry.md +95 -0
  9. package/docs/04-step-reference.md +728 -0
  10. package/docs/05-web-first-assertions.md +91 -0
  11. package/docs/06-network-and-dialogs.md +83 -0
  12. package/docs/07-auth-state.md +75 -0
  13. package/docs/08-clock-mocking.md +59 -0
  14. package/docs/09-api-testing.md +114 -0
  15. package/docs/10-accessibility.md +167 -0
  16. package/docs/11-debugging.md +129 -0
  17. package/docs/12-ai-agent-guide.md +338 -0
  18. package/docs/13-faq.md +236 -0
  19. package/docs/14-recipes-cookbook.md +255 -0
  20. package/docs/15-tag-conventions.md +76 -0
  21. package/docs/advanced-screenshots/then-i-save-fullscreen-screenshot.md +36 -0
  22. package/docs/advanced-screenshots/then-i-save-width-x-height-screenshot.md +34 -0
  23. package/docs/advanced-screenshots/when-i-save-screenshot-name-filename.md +45 -0
  24. package/docs/advanced-screenshots.md +52 -0
  25. package/docs/advanced-selectors.md +18 -0
  26. package/docs/api-step-definitions.md +45 -0
  27. package/docs/diffy-step-definitions/then-compare-diffy-env1-env2.md +30 -0
  28. package/docs/diffy-step-definitions/then-create-diffy-comparison-name-value.md +21 -0
  29. package/docs/diffy-step-definitions/then-create-diffy-comparison.md +25 -0
  30. package/docs/diffy-step-definitions/then-create-diffy-screenshot-environment-name.md +35 -0
  31. package/docs/diffy-step-definitions/then-i-take-screenshot.md +21 -0
  32. package/docs/diffy-step-definitions/then-i-take-screenshots-all-breakpoints.md +27 -0
  33. package/docs/diffy-step-definitions/then-send-screenshots-diffy-name-value.md +27 -0
  34. package/docs/diffy-step-definitions/then-upload-folder-url-diffy-snapshotname.md +28 -0
  35. package/docs/diffy-step-definitions/then-wait-diffy-comparison-complete.md +21 -0
  36. package/docs/diffy-step-definitions/when-i-resize-window-number.md +29 -0
  37. package/docs/diffy-step-definitions.md +21 -0
  38. package/docs/global-settings.md +244 -0
  39. package/docs/index.md +104 -0
  40. package/docs/install-webship-js/ddev-webship-js.md +52 -0
  41. package/docs/install-webship-js.md +35 -0
  42. package/docs/overview.md +41 -0
  43. package/docs/step-definitions/given-i-am-anonymous-user.md +67 -0
  44. package/docs/step-definitions/given-i-am-homepage.md +68 -0
  45. package/docs/step-definitions/given-i-am-specific-page.md +72 -0
  46. package/docs/step-definitions/then-i-should-be.md +56 -0
  47. package/docs/step-definitions/then-i-should-see.md +62 -0
  48. package/docs/step-definitions/then-item-checkbox.md +54 -0
  49. package/docs/step-definitions/then-item-link-should-contain-url.md +84 -0
  50. package/docs/step-definitions/then-item-should-contain.md +67 -0
  51. package/docs/step-definitions/then-radio-button-value-should-be-selected.md +68 -0
  52. package/docs/step-definitions/then-response-status-code-should-be-number.md +69 -0
  53. package/docs/step-definitions/then-value-radio-button-selected.md +62 -0
  54. package/docs/step-definitions/when-i-attach-file-file-name-element.md +71 -0
  55. package/docs/step-definitions/when-i-check-checkbox.md +60 -0
  56. package/docs/step-definitions/when-i-click-link.md +51 -0
  57. package/docs/step-definitions/when-i-click-operation-text-row.md +71 -0
  58. package/docs/step-definitions/when-i-fill.md +59 -0
  59. package/docs/step-definitions/when-i-go-homepage.md +60 -0
  60. package/docs/step-definitions/when-i-go-specific-page.md +67 -0
  61. package/docs/step-definitions/when-i-move-backward-one-page.md +49 -0
  62. package/docs/step-definitions/when-i-move-forward-one-page.md +58 -0
  63. package/docs/step-definitions/when-i-press-button.md +58 -0
  64. package/docs/step-definitions/when-i-reload-page.md +51 -0
  65. package/docs/step-definitions/when-i-scroll.md +73 -0
  66. package/docs/step-definitions/when-i-select-option-select-list.md +53 -0
  67. package/docs/step-definitions/when-i-select-radio-button-value.md +62 -0
  68. package/docs/step-definitions/when-i-uncheck-checkbox.md +57 -0
  69. package/docs/step-definitions/when-i-wait-ajax-finish.md +64 -0
  70. package/docs/step-definitions/when-i-wait.md +62 -0
  71. package/docs/step-definitions.md +50 -0
  72. package/examples/a11y.html +31 -0
  73. package/examples/cookies.html +10 -0
  74. package/examples/date.html +12 -0
  75. package/examples/element.html +11 -0
  76. package/examples/field.html +24 -0
  77. package/examples/keyboard.html +11 -0
  78. package/examples/links.html +9 -0
  79. package/examples/modal.html +14 -0
  80. package/examples/path.html +3 -0
  81. package/examples/table.html +13 -0
  82. package/package.json +10 -3
  83. package/playwright.config.ts +3 -2
  84. package/tests/features/a11y.feature +39 -0
  85. package/tests/features/cookie.feature +13 -0
  86. package/tests/features/date.feature +11 -0
  87. package/tests/features/element.feature +16 -0
  88. package/tests/features/field.feature +25 -0
  89. package/tests/features/keyboard.feature +10 -0
  90. package/tests/features/link.feature +11 -0
  91. package/tests/features/modal-advanced-example.feature +1 -1
  92. package/tests/features/modal.feature +11 -0
  93. package/tests/features/path.feature +16 -0
  94. package/tests/features/response.feature +8 -0
  95. package/tests/features/responsive.feature +10 -0
  96. package/tests/features/table.feature +18 -0
  97. package/tests/features/wait.feature +7 -0
  98. package/tests/features/yaml.feature +102 -0
  99. package/tests/reports/README.md +55 -0
  100. package/tests/selectors/_canonical-keys.json +113 -0
  101. package/tests/selectors/back-end-selectors.json +7 -1
  102. package/tests/selectors/cms-contentful-admin.json +35 -0
  103. package/tests/selectors/cms-craft-admin.json +39 -0
  104. package/tests/selectors/cms-drupal-cms-gin.json +56 -0
  105. package/tests/selectors/cms-drupal-core-claro.json +50 -0
  106. package/tests/selectors/cms-generic-admin.json +34 -0
  107. package/tests/selectors/cms-ghost-admin.json +34 -0
  108. package/tests/selectors/cms-joomla-admin.json +41 -0
  109. package/tests/selectors/cms-magento2-admin.json +32 -0
  110. package/tests/selectors/cms-prestashop-admin.json +38 -0
  111. package/tests/selectors/cms-shopify-admin.json +25 -0
  112. package/tests/selectors/cms-strapi-admin.json +42 -0
  113. package/tests/selectors/cms-typo3-admin.json +41 -0
  114. package/tests/selectors/cms-woocommerce-front.json +50 -0
  115. package/tests/selectors/cms-wordpress-admin.json +31 -0
  116. package/tests/selectors/framework-ant-design.json +80 -0
  117. package/tests/selectors/framework-bootstrap.json +86 -0
  118. package/tests/selectors/framework-bulma.json +74 -0
  119. package/tests/selectors/framework-chakra.json +58 -0
  120. package/tests/selectors/framework-foundation.json +51 -0
  121. package/tests/selectors/framework-material-ui.json +72 -0
  122. package/tests/selectors/framework-shadcn.json +51 -0
  123. package/tests/selectors/framework-tailwind.json +40 -0
  124. package/tests/selectors/framework-vuetify.json +61 -0
  125. package/tests/step-definitions/a11y.steps.js +798 -0
  126. package/tests/step-definitions/action.steps.js +167 -0
  127. package/tests/step-definitions/{webship-api.js → api.steps.js} +24 -7
  128. package/tests/step-definitions/assertion.steps.js +352 -0
  129. package/tests/step-definitions/auth.steps.js +124 -0
  130. package/tests/step-definitions/clock.steps.js +128 -0
  131. package/tests/step-definitions/cookie.steps.js +216 -0
  132. package/tests/step-definitions/debug.steps.js +31 -0
  133. package/tests/step-definitions/dialog.steps.js +193 -0
  134. package/tests/step-definitions/element.steps.js +314 -0
  135. package/tests/step-definitions/field.steps.js +653 -0
  136. package/tests/step-definitions/file-download.steps.js +193 -0
  137. package/tests/step-definitions/form.steps.js +333 -0
  138. package/tests/step-definitions/iframe.steps.js +178 -0
  139. package/tests/step-definitions/input.steps.js +163 -0
  140. package/tests/step-definitions/javascript.steps.js +71 -0
  141. package/tests/step-definitions/keyboard.steps.js +78 -0
  142. package/tests/step-definitions/link.steps.js +142 -0
  143. package/tests/step-definitions/metatag.steps.js +91 -0
  144. package/tests/step-definitions/modal.steps.js +219 -0
  145. package/tests/step-definitions/navigation.steps.js +218 -0
  146. package/tests/step-definitions/network.steps.js +238 -0
  147. package/tests/step-definitions/path.steps.js +141 -0
  148. package/tests/step-definitions/response.steps.js +98 -0
  149. package/tests/step-definitions/responsive.steps.js +123 -0
  150. package/tests/step-definitions/rest.steps.js +111 -0
  151. package/tests/step-definitions/{webship-screenshot.js → screenshot.steps.js} +1 -5
  152. package/tests/step-definitions/scroll.steps.js +189 -0
  153. package/tests/step-definitions/{webship-selectors.js → selectors.steps.js} +46 -11
  154. package/tests/step-definitions/storage.steps.js +194 -0
  155. package/tests/step-definitions/table.steps.js +181 -0
  156. package/tests/step-definitions/wait.steps.js +400 -0
  157. package/tests/step-definitions/web-first.steps.js +296 -0
  158. package/tests/step-definitions/webship.js +552 -1507
  159. package/tests/step-definitions/xml.steps.js +409 -0
  160. package/tests/step-definitions/yaml.steps.js +911 -0
  161. package/tests/step-definitions-diffy/webship-diffy.js +0 -13
  162. package/tsconfig.json +19 -3
@@ -1,98 +1,216 @@
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
- // ---------------------------------------------------------------------------
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.
14
- // ---------------------------------------------------------------------------
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
- });
27
- }
8
+ // ===========================================================================
9
+ // Internal helpers (BBR smart settle, modal probes, selector + text utilities).
10
+ // Imported by every *.steps.js file via require('./webship'). Defined here
11
+ // rather than in a shared sub-module so there is a single, canonical entry
12
+ // point — `tests/step-definitions/webship.js`.
13
+ // ===========================================================================
14
+
15
+ /**
16
+ * Shared shape of every Cucumber `this` (the World) at step time.
17
+ *
18
+ * @typedef {Object} WebshipWorld
19
+ * @property {import('playwright').Page} [page] - Active page (set in Before hook).
20
+ * @property {import('playwright').BrowserContext} [context] - Active browser context.
21
+ * @property {import('playwright').Browser} [browser] - Active browser instance.
22
+ * @property {import('playwright').FrameLocator} [frame] - Active iframe scope (set by iframe steps).
23
+ * @property {Object<string, string>} [__selectorsCss] - Named CSS selectors (registry).
24
+ * @property {Object<string, string>} [__selectorsXpath] - Named XPath selectors (registry).
25
+ * @property {Object} [parameters] - cucumber.js worldParameters.
26
+ */
28
27
 
29
28
  // ---------------------------------------------------------------------------
30
- // World
29
+ // BBR-style smart settle
30
+ //
31
+ // Behaviour-Based Robotics (BBR) principle: react to the environment, not
32
+ // the clock. smartSettle returns when the page is at the *edge* of activity,
33
+ // bounded by a budget so a runaway page cannot stall the run.
34
+ //
35
+ // The probe checks:
36
+ // 1. <body> attached
37
+ // 2. DOMContentLoaded fired
38
+ // 3. Playwright "networkidle" (500ms with no in-flight network)
39
+ // 4. window.__webshipAjaxCount === 0 (custom fetch/XHR counter)
40
+ // 5. window.__webshipPendingTimers === 0 (custom setTimeout counter)
41
+ // 6. Date.now() - window.__webshipLastMutation >= quietMs (DOM-quiet)
42
+ //
43
+ // Steps 4/5/6 are evaluated atomically via a single waitForFunction, so a
44
+ // late-firing setTimeout that mutates the DOM re-arms the wait correctly.
31
45
  // ---------------------------------------------------------------------------
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
46
 
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
- }
47
+ /**
48
+ * Wait for the page to reach an "edge" of activity — DOM ready, network
49
+ * idle, no pending AJAX or timers, and no DOM mutations for ≥250 ms.
50
+ *
51
+ * @param {import('playwright').Page} page - Page being probed.
52
+ * @param {number} [timeout=10000] - Total budget in ms.
53
+ * @returns {Promise<void>}
54
+ */
55
+ async function smartSettle(page, timeout) {
56
+ const total = typeof timeout === 'number' && timeout > 0 ? timeout : 10000;
57
+ const deadline = Date.now() + total;
58
+ const remaining = () => Math.max(0, deadline - Date.now());
51
59
 
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
- }
60
+ try { await page.waitForSelector('body', { state: 'attached', timeout: remaining() }); } catch { /* keep going */ }
61
+ try { await page.waitForLoadState('domcontentloaded', { timeout: remaining() }); } catch { /* keep going */ }
62
+ try { await page.waitForLoadState('networkidle', { timeout: remaining() }); } catch { /* keep going */ }
63
+ try {
64
+ await page.waitForFunction(
65
+ (quietMs) => {
66
+ const ajax = window.__webshipAjaxCount;
67
+ const timers = window.__webshipPendingTimers;
68
+ const last = window.__webshipLastMutation;
69
+ if (typeof ajax === 'number' && ajax > 0) return false;
70
+ if (typeof timers === 'number' && timers > 0) return false;
71
+ if (typeof last === 'number' && Date.now() - last < quietMs) return false;
72
+ return true;
73
+ },
74
+ 250,
75
+ { timeout: remaining(), polling: 50 }
76
+ );
77
+ } catch { /* keep going */ }
60
78
  }
61
79
 
62
- setWorldConstructor(PlaywrightWorld);
80
+ /**
81
+ * Convenience alias for {@link smartSettle}. Kept for readability inside
82
+ * navigation steps where "wait for page to load" reads more naturally.
83
+ *
84
+ * @param {import('playwright').Page} page
85
+ * @param {number} [timeout]
86
+ * @returns {Promise<void>}
87
+ */
88
+ async function waitForPageLoad(page, timeout) {
89
+ await smartSettle(page, timeout);
90
+ }
63
91
 
64
- Before(async function () {
65
- await this.openBrowser();
66
- if (this.minWaitTime.before_scenario > 0) {
67
- await this.page.waitForTimeout(this.minWaitTime.before_scenario);
92
+ // ---------------------------------------------------------------------------
93
+ // Modal helpers — use the named "modal" selector from the registry, falling
94
+ // back to ARIA role + native <dialog>.
95
+ // ---------------------------------------------------------------------------
96
+ /**
97
+ * Resolve the CSS selector that targets a modal dialog. Prefers a named
98
+ * `modal` selector from the registry; otherwise falls back to ARIA + native.
99
+ *
100
+ * @param {WebshipWorld} world
101
+ * @returns {string}
102
+ */
103
+ function getModalSelector(world) {
104
+ if (world && world.__selectorsCss && world.__selectorsCss['modal']) {
105
+ return world.__selectorsCss['modal'];
68
106
  }
69
- });
107
+ return '[role="dialog"], dialog';
108
+ }
70
109
 
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
- });
110
+ /**
111
+ * Locator pointing at modal dialogs on the given page.
112
+ *
113
+ * @param {import('playwright').Page} page
114
+ * @param {WebshipWorld} world
115
+ * @returns {import('playwright').Locator}
116
+ */
117
+ function getModalLocator(page, world) {
118
+ return page.locator(getModalSelector(world));
119
+ }
77
120
 
78
- BeforeStep(async function () {
79
- if (this.page && this.minWaitTime.before_step > 0) {
80
- await this.page.waitForTimeout(this.minWaitTime.before_step);
121
+ /**
122
+ * Wait until a modal is visible or hidden. Visibility is derived from
123
+ * computed styles (display + visibility + opacity), which is more
124
+ * reliable than `offsetParent` for fixed-position modal containers.
125
+ *
126
+ * @param {import('playwright').Page} page
127
+ * @param {'visible'|'hidden'} state
128
+ * @param {number} [timeout=10000]
129
+ * @param {WebshipWorld} world
130
+ * @returns {Promise<void>}
131
+ */
132
+ async function waitForModalState(page, state, timeout, world) {
133
+ const sel = getModalSelector(world);
134
+ const total = typeof timeout === 'number' && timeout > 0 ? timeout : 10000;
135
+ if (state === 'visible') {
136
+ await page.waitForFunction(
137
+ (s) => Array.from(document.querySelectorAll(s)).some((el) => {
138
+ const cs = window.getComputedStyle(el);
139
+ return cs.display !== 'none' && cs.visibility !== 'hidden' && cs.opacity !== '0';
140
+ }),
141
+ sel, { timeout: total }
142
+ );
143
+ } else {
144
+ await page.waitForFunction(
145
+ (s) => !Array.from(document.querySelectorAll(s)).some((el) => {
146
+ const cs = window.getComputedStyle(el);
147
+ return cs.display !== 'none' && cs.visibility !== 'hidden' && cs.opacity !== '0';
148
+ }),
149
+ sel, { timeout: total }
150
+ );
81
151
  }
82
- });
152
+ }
83
153
 
84
- AfterStep(async function () {
85
- if (this.page && this.minWaitTime.after_step > 0) {
86
- await this.page.waitForTimeout(this.minWaitTime.after_step);
154
+ /**
155
+ * Return the first visible modal locator. Throws a friendly error with
156
+ * remediation hints when no modal is on screen.
157
+ *
158
+ * @param {import('playwright').Page} page
159
+ * @param {WebshipWorld} world
160
+ * @returns {Promise<import('playwright').Locator>}
161
+ */
162
+ async function findVisibleModal(page, world) {
163
+ const all = getModalLocator(page, world);
164
+ const count = await all.count();
165
+ for (let i = 0; i < count; i++) {
166
+ if (await all.nth(i).isVisible()) return all.nth(i);
87
167
  }
88
- });
168
+ const sel = getModalSelector(world);
169
+ throw new Error(
170
+ `No visible modal found.\n` +
171
+ ` Selector tried: ${sel}\n` +
172
+ ` Hint: did you "wait for the modal to appear" first?\n` +
173
+ ` Or: register a custom "modal" CSS selector in tests/selectors/<preset>.json.`
174
+ );
175
+ }
176
+
177
+ /**
178
+ * Quick check — true when any element matching the modal selector is
179
+ * visible per the same computed-style probe as `waitForModalState`.
180
+ *
181
+ * @param {import('playwright').Page} page
182
+ * @param {WebshipWorld} world
183
+ * @returns {Promise<boolean>}
184
+ */
185
+ async function isAnyModalVisible(page, world) {
186
+ const sel = getModalSelector(world);
187
+ return page.evaluate((s) =>
188
+ Array.from(document.querySelectorAll(s)).some((el) => {
189
+ const cs = window.getComputedStyle(el);
190
+ return cs.display !== 'none' && cs.visibility !== 'hidden' && cs.opacity !== '0';
191
+ }),
192
+ sel
193
+ );
194
+ }
89
195
 
90
196
  // ---------------------------------------------------------------------------
91
- // Helper: build CSS selector from attrValue + optional attr argument.
197
+ // Resilient CSS selector builder.
198
+ // Honors id (#x), class (.x), or attribute selectors ([x]) verbatim.
199
+ // Otherwise tries id / class / name / data-testid / data-test-id / data-test
200
+ // / data-cy / aria-label / value / placeholder / title in priority order.
92
201
  // ---------------------------------------------------------------------------
202
+ /**
203
+ * Compose a CSS selector that tries multiple addressable attributes.
204
+ * Verbatim selectors (`#id`, `.class`, `[attr]`) pass through untouched;
205
+ * bare names fan out across `name`, `data-testid`, `aria-label`, etc.
206
+ *
207
+ * @param {string} attrValue - Value to match (e.g. `"submit-btn"`).
208
+ * @param {string} [attr] - Optional explicit attribute name; when given, returns `[attr="value" i]`.
209
+ * @returns {string} CSS selector union.
210
+ */
93
211
  function buildSelector(attrValue, attr) {
94
212
  const hasASpace = attrValue.indexOf(' ');
95
- if ((attrValue.startsWith('#') || attrValue.startsWith('.')) && hasASpace === -1) {
213
+ if ((attrValue.startsWith('#') || attrValue.startsWith('.') || attrValue.startsWith('[')) && hasASpace === -1) {
96
214
  return attrValue;
97
215
  }
98
216
  if (!attr && hasASpace === -1) {
@@ -100,38 +218,75 @@ function buildSelector(attrValue, attr) {
100
218
  attrValue +
101
219
  ',#' + attrValue +
102
220
  ',.' + attrValue +
103
- ',[name=' + attrValue + '],' +
104
- '[value="' + attrValue + '"],[placeholder="' + attrValue + '"]' +
221
+ ',[name="' + attrValue + '"]' +
222
+ ',[data-testid="' + attrValue + '"]' +
223
+ ',[data-test-id="' + attrValue + '"]' +
224
+ ',[data-test="' + attrValue + '"]' +
225
+ ',[data-cy="' + attrValue + '"]' +
226
+ ',[aria-label="' + attrValue + '"]' +
227
+ ',[value="' + attrValue + '"]' +
228
+ ',[placeholder="' + attrValue + '"]' +
105
229
  ',[title="' + attrValue + '"]'
106
230
  );
107
231
  }
108
232
  if (!attr && hasASpace > -1) {
109
- return '[value="' + attrValue + '"],[placeholder="' + attrValue + '"]';
233
+ return '[value="' + attrValue + '"],[placeholder="' + attrValue + '"],[aria-label="' + attrValue + '"],[title="' + attrValue + '"]';
110
234
  }
111
235
  return '[' + attr + '="' + attrValue + '" i]';
112
236
  }
113
237
 
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
- // ---------------------------------------------------------------------------
238
+ // Navigate to a URL with friendly errors. Tolerates Firefox / WebKit
239
+ // empty-response edge cases so a redirect to about:blank or a 204 does
240
+ // not crash the suite. All other failures rethrow with extra context
241
+ // (URL + likely cause).
242
+ /**
243
+ * Navigate to a URL with friendly error messages for common failures
244
+ * (server down, DNS, empty response). All other errors rethrow with
245
+ * preserved stack + extra context.
246
+ *
247
+ * @param {import('playwright').Page} page
248
+ * @param {string} url
249
+ * @returns {Promise<void>}
250
+ */
124
251
  async function gotoUrl(page, url) {
125
252
  try {
126
253
  await page.goto(url, { waitUntil: 'domcontentloaded' });
127
254
  } catch (e) {
128
- if (!/NS_ERROR_NET_EMPTY_RESPONSE|net::ERR_EMPTY_RESPONSE/.test(e.message)) throw e;
255
+ const msg = e.message || '';
256
+ // Empty response: harmless, swallow.
257
+ if (/NS_ERROR_NET_EMPTY_RESPONSE|net::ERR_EMPTY_RESPONSE/.test(msg)) return;
258
+ // Connection refused: server probably not running.
259
+ if (/ECONNREFUSED|net::ERR_CONNECTION_REFUSED/.test(msg)) {
260
+ throw new Error(
261
+ `Could not reach "${url}".\n` +
262
+ ` ${msg.split('\n')[0]}\n` +
263
+ ` Hint: is your dev server running? Check LAUNCH_URL env var.`
264
+ );
265
+ }
266
+ // DNS failure.
267
+ if (/ERR_NAME_NOT_RESOLVED|NS_ERROR_UNKNOWN_HOST/.test(msg)) {
268
+ throw new Error(
269
+ `Could not resolve host for "${url}".\n` +
270
+ ` ${msg.split('\n')[0]}\n` +
271
+ ` Hint: double-check the hostname in LAUNCH_URL or your "Given I am on" path.`
272
+ );
273
+ }
274
+ // Anything else — preserve original stack but prepend context.
275
+ e.message = `Failed to navigate to "${url}":\n ${e.message}`;
276
+ throw e;
129
277
  }
130
278
  }
131
279
 
132
- // ---------------------------------------------------------------------------
133
- // Helper: fill a field located by label, placeholder, or name
134
- // ---------------------------------------------------------------------------
280
+ /**
281
+ * Fill a form field located by label, placeholder, or `[name]`. Resolution
282
+ * order: label → placeholder → name. Throws a friendly error when none
283
+ * match, suggesting the by-attr variant.
284
+ *
285
+ * @param {import('playwright').Page} page
286
+ * @param {string} field - Label / placeholder / name.
287
+ * @param {string} value - Value to type.
288
+ * @returns {Promise<void>}
289
+ */
135
290
  async function fillField(page, field, value) {
136
291
  const byLabel = page.getByLabel(field, { exact: true });
137
292
  if (await byLabel.count() > 0) {
@@ -143,12 +298,26 @@ async function fillField(page, field, value) {
143
298
  await byPlaceholder.fill(value);
144
299
  return;
145
300
  }
146
- await page.locator(`[name="${field}"]`).first().fill(value);
301
+ const byName = page.locator(`[name="${field}"]`).first();
302
+ if (await byName.count() > 0) {
303
+ await byName.fill(value);
304
+ return;
305
+ }
306
+ throw new Error(
307
+ `Could not find a field for "${field}".\n` +
308
+ ` Tried: getByLabel(exact), getByPlaceholder(exact), [name="${field}"].\n` +
309
+ ` Hints: check the label/placeholder text matches exactly (case-sensitive),\n` +
310
+ ` or use the attribute variant: 'I fill in "${field}" with "${value}" by attr'.`
311
+ );
147
312
  }
148
313
 
149
- // ---------------------------------------------------------------------------
150
- // Helper: get text from a locator — input value or text content
151
- // ---------------------------------------------------------------------------
314
+ /**
315
+ * Read text from a locator. Falls back to `textContent` when the element
316
+ * is not an `<input>` / `<textarea>`.
317
+ *
318
+ * @param {import('playwright').Locator} locator
319
+ * @returns {Promise<string>}
320
+ */
152
321
  async function getLocatorText(locator) {
153
322
  try {
154
323
  return await locator.inputValue();
@@ -157,1477 +326,353 @@ async function getLocatorText(locator) {
157
326
  }
158
327
  }
159
328
 
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
329
  /**
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
330
+ * Left-pad a number with zeros to the requested width.
238
331
  *
332
+ * @param {number} n
333
+ * @param {number} width
334
+ * @returns {string}
239
335
  */
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
- });
336
+ function pad(n, width) {
337
+ const s = String(n);
338
+ return s.length >= width ? s : '0'.repeat(width - s.length) + s;
339
+ }
246
340
 
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
- });
341
+ // ---------------------------------------------------------------------------
342
+ // Relative-date token resolver
343
+ //
344
+ // Replaces [relative:OFFSET] and [relative:OFFSET#FORMAT] tokens in step
345
+ // arguments before pattern matching. Resolution happens automatically via
346
+ // the BeforeStep hook registered below.
347
+ //
348
+ // OFFSET any expression understood by parseRelativeOffset()
349
+ // examples: "now", "-1 day", "+2 hours", "+1 week", "next monday"
350
+ // FORMAT subset of date-fns-style tokens: YYYY, MM, DD, HH, mm, ss
351
+ // examples: "YYYY-MM-DD", "DD/MM/YYYY HH:mm"
352
+ //
353
+ // Without FORMAT the resolved value is the Unix timestamp in seconds.
354
+ //
355
+ // Examples:
356
+ // [relative:-1 day] -> "1714867200"
357
+ // [relative:-1 day#YYYY-MM-DD] -> "2026-05-06"
358
+ // ---------------------------------------------------------------------------
264
359
 
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
- });
360
+ const RELATIVE_TOKEN_RE = /\[relative:([^\]#]+)(?:#([^\]]+))?\]/g;
284
361
 
285
362
  /**
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"
363
+ * Format a Date with a tiny token vocabulary (`YYYY`, `MM`, `DD`, `HH`,
364
+ * `mm`, `ss`). Sufficient for typical step-arg date formats.
294
365
  *
366
+ * @param {Date} date
367
+ * @param {string} fmt
368
+ * @returns {string}
295
369
  */
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
- });
370
+ function formatRelativeDate(date, fmt) {
371
+ return fmt
372
+ .replace(/YYYY/g, date.getFullYear())
373
+ .replace(/MM/g, pad(date.getMonth() + 1, 2))
374
+ .replace(/DD/g, pad(date.getDate(), 2))
375
+ .replace(/HH/g, pad(date.getHours(), 2))
376
+ .replace(/mm/g, pad(date.getMinutes(), 2))
377
+ .replace(/ss/g, pad(date.getSeconds(), 2));
378
+ }
302
379
 
303
380
  /**
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 });
381
+ * Parse a relative-date offset expression and return absolute ms.
382
+ * Accepts `"now"`, `"+1 day"`, `"-2 hours"`, `"next monday"`, etc.
383
+ *
384
+ * @param {string} offset
385
+ * @param {number} baseMs - Reference epoch in ms.
386
+ * @returns {number} Resolved epoch in ms.
387
+ */
388
+ function parseRelativeOffset(offset, baseMs) {
389
+ const trimmed = offset.trim().toLowerCase();
390
+ if (trimmed === 'now') return baseMs;
391
+
392
+ const weekdayMatch = trimmed.match(/^(next|last)\s+(sunday|monday|tuesday|wednesday|thursday|friday|saturday)$/);
393
+ if (weekdayMatch) {
394
+ const direction = weekdayMatch[1] === 'next' ? 1 : -1;
395
+ const target = ['sunday', 'monday', 'tuesday', 'wednesday', 'thursday', 'friday', 'saturday'].indexOf(weekdayMatch[2]);
396
+ const d = new Date(baseMs);
397
+ let diff = (target - d.getDay()) * direction;
398
+ if (diff <= 0) diff += 7;
399
+ d.setDate(d.getDate() + diff * direction);
400
+ return d.getTime();
401
+ }
402
+
403
+ const m = trimmed.match(/^([+-]?\d+)\s*(second|minute|hour|day|week|month|year)s?$/);
404
+ if (m) {
405
+ const n = parseInt(m[1], 10);
406
+ const unit = m[2];
407
+ const d = new Date(baseMs);
408
+ switch (unit) {
409
+ case 'second': d.setSeconds(d.getSeconds() + n); break;
410
+ case 'minute': d.setMinutes(d.getMinutes() + n); break;
411
+ case 'hour': d.setHours(d.getHours() + n); break;
412
+ case 'day': d.setDate(d.getDate() + n); break;
413
+ case 'week': d.setDate(d.getDate() + n * 7); break;
414
+ case 'month': d.setMonth(d.getMonth() + n); break;
415
+ case 'year': d.setFullYear(d.getFullYear() + n); break;
416
+ }
417
+ return d.getTime();
318
418
  }
319
- });
320
419
 
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
- });
420
+ const parsed = Date.parse(offset);
421
+ if (!Number.isNaN(parsed)) return parsed;
332
422
 
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
- });
423
+ throw new Error(`Cannot evaluate relative date offset: "${offset}"`);
424
+ }
344
425
 
345
426
  /**
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"
427
+ * Resolve `[relative:OFFSET]` / `[relative:OFFSET#FORMAT]` tokens in any
428
+ * string. Without `#FORMAT` the token expands to a Unix timestamp in
429
+ * seconds; with it, to the formatted string.
353
430
  *
431
+ * @param {string} value - Step argument that may contain tokens.
432
+ * @param {number} [nowMs=Date.now()] - Reference epoch for resolution.
433
+ * @returns {string} Value with tokens replaced.
354
434
  */
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
- });
435
+ function resolveRelativeDate(value, nowMs) {
436
+ if (typeof value !== 'string' || !value.includes('[relative:')) return value;
437
+ const base = nowMs || Date.now();
438
+ return value.replace(RELATIVE_TOKEN_RE, (_, offset, fmt) => {
439
+ const ms = parseRelativeOffset(offset, base);
440
+ if (fmt) return formatRelativeDate(new Date(ms), fmt);
441
+ return String(Math.floor(ms / 1000));
442
+ });
443
+ }
362
444
 
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
- });
445
+ // BeforeStep hook — transform every string argument (and DataTable cells)
446
+ // in the current pickle step before the step definition runs.
447
+ BeforeStep(function (scope) {
448
+ const step = scope && scope.pickleStep;
449
+ if (!step) return;
376
450
 
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
- });
451
+ if (typeof step.text === 'string' && step.text.includes('[relative:')) {
452
+ step.text = resolveRelativeDate(step.text);
453
+ }
393
454
 
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
- });
455
+ if (!step.argument) return;
406
456
 
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();
457
+ if (step.argument.docString && typeof step.argument.docString.content === 'string') {
458
+ step.argument.docString.content = resolveRelativeDate(step.argument.docString.content);
425
459
  }
426
- });
427
460
 
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.`);
461
+ if (step.argument.dataTable && Array.isArray(step.argument.dataTable.rows)) {
462
+ for (const row of step.argument.dataTable.rows) {
463
+ if (!row || !Array.isArray(row.cells)) continue;
464
+ for (const cell of row.cells) {
465
+ if (cell && typeof cell.value === 'string') {
466
+ cell.value = resolveRelativeDate(cell.value);
467
+ }
468
+ }
469
+ }
449
470
  }
450
471
  });
451
472
 
452
- /**
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
- });
464
-
465
- /**
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"
472
- *
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.
480
- *
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
485
- *
486
- */
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();
668
- }
669
- }
670
- });
671
-
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
- });
693
-
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();
712
- }
713
- }
714
- });
715
-
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
- });
741
-
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}`);
763
- }
764
- });
765
-
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
- });
795
-
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
- });
811
-
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
- });
831
-
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.`);
849
- }
850
- });
851
-
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 });
871
- }
872
- }
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();
473
+ module.exports = {
474
+ smartSettle,
475
+ waitForPageLoad,
476
+ getModalSelector,
477
+ getModalLocator,
478
+ waitForModalState,
479
+ findVisibleModal,
480
+ isAnyModalVisible,
481
+ buildSelector,
482
+ gotoUrl,
483
+ fillField,
484
+ getLocatorText,
485
+ pad,
486
+ resolveRelativeDate,
487
+ parseRelativeOffset,
488
+ formatRelativeDate,
489
+ };
907
490
 
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;
491
+ // ---------------------------------------------------------------------------
492
+ // Auto HTML report on cucumber-js process exit.
493
+ // Disable: WEBSHIP_REPORT_DISABLE=1. Extra flags: WEBSHIP_REPORT_ARGS="--theme hierarchy --layout 2".
494
+ // Registered once per process.
495
+ // ---------------------------------------------------------------------------
496
+ if (!global.__WEBSHIP_AUTO_REPORT__) {
497
+ global.__WEBSHIP_AUTO_REPORT__ = true;
498
+ process.on('exit', () => {
499
+ if (process.env.WEBSHIP_REPORT_DISABLE) return;
500
+ try {
501
+ const { run } = require(path.join(__dirname, '..', '..', 'bin', 'generate-reports'));
502
+ const extra = (process.env.WEBSHIP_REPORT_ARGS || '').split(/\s+/).filter(Boolean);
503
+ run(extra);
504
+ } catch (err) {
505
+ console.error('[webship-js] Report generation failed:', err.message);
931
506
  }
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 });
936
-
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
- });
943
-
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
- });
967
-
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
- });
507
+ });
508
+ }
983
509
 
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
- });
510
+ // ---------------------------------------------------------------------------
511
+ // World
512
+ // ---------------------------------------------------------------------------
513
+ setDefaultTimeout(30 * 1000);
999
514
 
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.`);
515
+ class PlaywrightWorld extends World {
516
+ constructor(options) {
517
+ super(options);
518
+ this.launchUrl = this.parameters.launchUrl;
519
+ this.minWaitTime = this.parameters.minWaitTime;
520
+ this.playwrightBrowser = null;
521
+ this.context = null;
522
+ this.page = null;
523
+ this.assetsFolder = path.join(__dirname, '../assets/');
1013
524
  }
1014
- });
1015
525
 
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
- });
526
+ async openBrowser() {
527
+ const { browser: browserName, launchOptions, contextOptions } = playwrightConfig;
528
+ this.playwrightBrowser = await playwright[browserName].launch(launchOptions);
529
+ this.context = await this.playwrightBrowser.newContext(contextOptions);
530
+ // BBR: install in-flight fetch/XHR counter on every page (init script runs
531
+ // before any document script). The counter lets smartSettle() detect the
532
+ // edge of background activity rather than guessing a fixed delay.
533
+ await this.context.addInitScript(() => {
534
+ if (window.__webshipAjaxInstalled) return;
535
+ window.__webshipAjaxInstalled = true;
536
+ window.__webshipAjaxCount = 0;
537
+ window.__webshipPendingTimers = 0;
538
+ window.__webshipLastMutation = Date.now();
539
+
540
+ // Track in-flight fetch requests.
541
+ const origFetch = window.fetch;
542
+ if (typeof origFetch === 'function') {
543
+ window.fetch = function (...args) {
544
+ window.__webshipAjaxCount++;
545
+ const p = origFetch.apply(this, args);
546
+ const settle = () => { window.__webshipAjaxCount--; };
547
+ p.then(settle, settle);
548
+ return p;
549
+ };
550
+ }
1031
551
 
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
- });
552
+ // Track in-flight XMLHttpRequests.
553
+ const XHR = window.XMLHttpRequest;
554
+ if (XHR && XHR.prototype) {
555
+ const origSend = XHR.prototype.send;
556
+ XHR.prototype.send = function (...args) {
557
+ window.__webshipAjaxCount++;
558
+ const settle = () => { window.__webshipAjaxCount--; };
559
+ this.addEventListener('loadend', settle, { once: true });
560
+ return origSend.apply(this, args);
561
+ };
562
+ }
1048
563
 
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
- });
564
+ // Track pending setTimeout callbacks. Many client-side frameworks use
565
+ // setTimeout to schedule UI updates (animation frames, throttled
566
+ // re-renders, fade-out → display:none). BBR demands we wait for those
567
+ // timers to drain rather than guess a fixed delay.
568
+ const origSetTimeout = window.setTimeout;
569
+ const origClearTimeout = window.clearTimeout;
570
+ const liveTimers = new Set();
571
+ if (typeof origSetTimeout === 'function') {
572
+ window.setTimeout = function (cb, delay, ...args) {
573
+ window.__webshipPendingTimers++;
574
+ let id;
575
+ const wrapped = function () {
576
+ try {
577
+ if (typeof cb === 'function') return cb.apply(this, args);
578
+ } finally {
579
+ if (liveTimers.delete(id)) window.__webshipPendingTimers--;
580
+ }
581
+ };
582
+ id = origSetTimeout(wrapped, delay);
583
+ liveTimers.add(id);
584
+ return id;
585
+ };
586
+ if (typeof origClearTimeout === 'function') {
587
+ window.clearTimeout = function (id) {
588
+ if (liveTimers.delete(id)) window.__webshipPendingTimers--;
589
+ return origClearTimeout(id);
590
+ };
591
+ }
592
+ }
1064
593
 
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.`);
594
+ // Track last DOM mutation so smartSettle can wait for the *edge* of
595
+ // client-side rendering (animations, async hydration, transitions).
596
+ const startObserver = () => {
597
+ if (!document || !document.documentElement) return false;
598
+ try {
599
+ new MutationObserver(() => { window.__webshipLastMutation = Date.now(); })
600
+ .observe(document.documentElement, { childList: true, subtree: true, attributes: true, characterData: true });
601
+ return true;
602
+ } catch (e) { return false; }
603
+ };
604
+ if (!startObserver()) {
605
+ document.addEventListener('DOMContentLoaded', startObserver, { once: true });
606
+ }
607
+ });
608
+ this.page = await this.context.newPage();
1078
609
  }
1079
- });
1080
610
 
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}`);
611
+ async closeBrowser() {
612
+ if (this.playwrightBrowser) {
613
+ await this.playwrightBrowser.close();
614
+ this.playwrightBrowser = null;
615
+ this.context = null;
616
+ this.page = null;
1105
617
  }
1106
618
  }
1107
- });
1108
-
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.`);
1124
- }
1125
- });
1126
-
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.`);
1143
- }
1144
- });
1145
-
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.`);
1161
- }
1162
- });
1163
-
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 }));
1318
- }
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
- });
619
+ }
1426
620
 
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
- });
621
+ setWorldConstructor(PlaywrightWorld);
1445
622
 
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.`);
623
+ Before(async function () {
624
+ await this.openBrowser();
625
+ if (this.minWaitTime.before_scenario > 0) {
626
+ await this.page.waitForTimeout(this.minWaitTime.before_scenario);
1465
627
  }
1466
628
  });
1467
629
 
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.`);
630
+ After(async function () {
631
+ if (this.minWaitTime.after_scenario > 0) {
632
+ await this.page.waitForTimeout(this.minWaitTime.after_scenario);
1487
633
  }
634
+ await this.closeBrowser();
1488
635
  });
1489
636
 
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.`);
637
+ BeforeStep(async function () {
638
+ if (this.page && this.minWaitTime.before_step > 0) {
639
+ await this.page.waitForTimeout(this.minWaitTime.before_step);
1505
640
  }
1506
641
  });
1507
642
 
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
- });
643
+ // BBR: regex matches steps that mutate page state (click/press/fill/check/etc.).
644
+ // After such a step, run a short smartSettle so assertions in the next step
645
+ // observe the post-action edge instead of mid-transition state.
646
+ 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
647
 
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');
648
+ AfterStep(async function (scope) {
649
+ if (!this.page) return;
650
+ if (this.minWaitTime.after_step > 0) {
651
+ await this.page.waitForTimeout(this.minWaitTime.after_step);
1543
652
  }
653
+ // Auto-settle only after state-changing steps. Skip if disabled via env var.
654
+ if (process.env.WEBSHIP_AUTO_SETTLE === 'off') return;
655
+ const text = scope && scope.pickleStep && scope.pickleStep.text;
656
+ if (typeof text !== 'string') return;
657
+ if (!STATE_MUTATING_STEP.test(text)) return;
658
+ try { await smartSettle(this.page, 1500); } catch { /* best effort */ }
1544
659
  });
1545
660
 
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
661
 
1560
662
  // ===========================================================================
1561
- // STEP DEFINITIONS — Follow link, count elements, debug helpers.
663
+ // All step definitions previously defined in this file have been split out
664
+ // by topic. Cucumber-js auto-loads every *.steps.js in tests/step-definitions/,
665
+ // so feature files keep working unchanged.
666
+ //
667
+ // Topical homes:
668
+ // navigation.steps.js Given/When/Then for sessions, homepage, paths, history
669
+ // action.steps.js press, click (text/attr/row), follow, attach file
670
+ // form.steps.js fill, select, additionally select, check, uncheck, radio
671
+ // assertion.steps.js should see / not see, in row, in element, response,
672
+ // text matching, link href, count, status code
673
+ // field.steps.js field/checkbox/radio state assertions
674
+ // modal.steps.js modal visibility, content, button click, close
675
+ // wait.steps.js every BBR wait phrasing
676
+ // scroll.steps.js page + scoped element scrolling
677
+ // debug.steps.js print URL / response (debug only)
1562
678
  // ===========================================================================
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
- });