webship-js 2.0.1 → 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 (194) hide show
  1. package/AGENTS.md +109 -0
  2. package/CLAUDE.md +317 -0
  3. package/bin/generate-reports.js +363 -0
  4. package/bin/init-webship.js +343 -0
  5. package/bin/postinstall.js +8 -74
  6. package/cucumber.js +66 -2
  7. package/docs/00-quick-start.md +102 -0
  8. package/docs/01-getting-started.md +102 -0
  9. package/docs/02-bbr-smart-waits.md +77 -0
  10. package/docs/03-selector-registry.md +95 -0
  11. package/docs/04-step-reference.md +728 -0
  12. package/docs/05-web-first-assertions.md +91 -0
  13. package/docs/06-network-and-dialogs.md +83 -0
  14. package/docs/07-auth-state.md +75 -0
  15. package/docs/08-clock-mocking.md +59 -0
  16. package/docs/09-api-testing.md +114 -0
  17. package/docs/10-accessibility.md +167 -0
  18. package/docs/11-debugging.md +129 -0
  19. package/docs/12-ai-agent-guide.md +338 -0
  20. package/docs/13-faq.md +236 -0
  21. package/docs/14-recipes-cookbook.md +255 -0
  22. package/docs/15-tag-conventions.md +76 -0
  23. package/docs/advanced-screenshots/then-i-save-fullscreen-screenshot.md +36 -0
  24. package/docs/advanced-screenshots/then-i-save-width-x-height-screenshot.md +34 -0
  25. package/docs/advanced-screenshots/when-i-save-screenshot-name-filename.md +45 -0
  26. package/docs/advanced-screenshots.md +52 -0
  27. package/docs/advanced-selectors.md +18 -0
  28. package/docs/api-step-definitions.md +45 -0
  29. package/docs/diffy-step-definitions/then-compare-diffy-env1-env2.md +30 -0
  30. package/docs/diffy-step-definitions/then-create-diffy-comparison-name-value.md +21 -0
  31. package/docs/diffy-step-definitions/then-create-diffy-comparison.md +25 -0
  32. package/docs/diffy-step-definitions/then-create-diffy-screenshot-environment-name.md +35 -0
  33. package/docs/diffy-step-definitions/then-i-take-screenshot.md +21 -0
  34. package/docs/diffy-step-definitions/then-i-take-screenshots-all-breakpoints.md +27 -0
  35. package/docs/diffy-step-definitions/then-send-screenshots-diffy-name-value.md +27 -0
  36. package/docs/diffy-step-definitions/then-upload-folder-url-diffy-snapshotname.md +28 -0
  37. package/docs/diffy-step-definitions/then-wait-diffy-comparison-complete.md +21 -0
  38. package/docs/diffy-step-definitions/when-i-resize-window-number.md +29 -0
  39. package/docs/diffy-step-definitions.md +21 -0
  40. package/docs/global-settings.md +244 -0
  41. package/docs/index.md +104 -0
  42. package/docs/install-webship-js/ddev-webship-js.md +52 -0
  43. package/docs/install-webship-js.md +35 -0
  44. package/docs/overview.md +41 -0
  45. package/docs/step-definitions/given-i-am-anonymous-user.md +67 -0
  46. package/docs/step-definitions/given-i-am-homepage.md +68 -0
  47. package/docs/step-definitions/given-i-am-specific-page.md +72 -0
  48. package/docs/step-definitions/then-i-should-be.md +56 -0
  49. package/docs/step-definitions/then-i-should-see.md +62 -0
  50. package/docs/step-definitions/then-item-checkbox.md +54 -0
  51. package/docs/step-definitions/then-item-link-should-contain-url.md +84 -0
  52. package/docs/step-definitions/then-item-should-contain.md +67 -0
  53. package/docs/step-definitions/then-radio-button-value-should-be-selected.md +68 -0
  54. package/docs/step-definitions/then-response-status-code-should-be-number.md +69 -0
  55. package/docs/step-definitions/then-value-radio-button-selected.md +62 -0
  56. package/docs/step-definitions/when-i-attach-file-file-name-element.md +71 -0
  57. package/docs/step-definitions/when-i-check-checkbox.md +60 -0
  58. package/docs/step-definitions/when-i-click-link.md +51 -0
  59. package/docs/step-definitions/when-i-click-operation-text-row.md +71 -0
  60. package/docs/step-definitions/when-i-fill.md +59 -0
  61. package/docs/step-definitions/when-i-go-homepage.md +60 -0
  62. package/docs/step-definitions/when-i-go-specific-page.md +67 -0
  63. package/docs/step-definitions/when-i-move-backward-one-page.md +49 -0
  64. package/docs/step-definitions/when-i-move-forward-one-page.md +58 -0
  65. package/docs/step-definitions/when-i-press-button.md +58 -0
  66. package/docs/step-definitions/when-i-reload-page.md +51 -0
  67. package/docs/step-definitions/when-i-scroll.md +73 -0
  68. package/docs/step-definitions/when-i-select-option-select-list.md +53 -0
  69. package/docs/step-definitions/when-i-select-radio-button-value.md +62 -0
  70. package/docs/step-definitions/when-i-uncheck-checkbox.md +57 -0
  71. package/docs/step-definitions/when-i-wait-ajax-finish.md +64 -0
  72. package/docs/step-definitions/when-i-wait.md +62 -0
  73. package/docs/step-definitions.md +50 -0
  74. package/examples/a11y.html +31 -0
  75. package/examples/cookies.html +10 -0
  76. package/examples/date.html +12 -0
  77. package/examples/diffy/baseline.html +54 -0
  78. package/examples/diffy/changed.html +63 -0
  79. package/examples/diffy/index.html +52 -0
  80. package/examples/element.html +11 -0
  81. package/examples/field.html +24 -0
  82. package/examples/index.html +6 -0
  83. package/examples/keyboard.html +11 -0
  84. package/examples/links.html +9 -0
  85. package/examples/modal.html +14 -0
  86. package/examples/path.html +3 -0
  87. package/examples/table.html +13 -0
  88. package/examples/test--when--i-additionally-select.html +27 -0
  89. package/package.json +19 -6
  90. package/playwright.config.ts +3 -2
  91. package/tests/features/a11y.feature +39 -0
  92. package/tests/features/cookie.feature +13 -0
  93. package/tests/features/date.feature +11 -0
  94. package/tests/features/diffy/test--diffy-01-example-demo.feature +22 -0
  95. package/tests/features/diffy/test--diffy-02-all-steps.feature +52 -0
  96. package/tests/features/diffy/test--diffy-03-real-api.feature +21 -0
  97. package/tests/features/element.feature +16 -0
  98. package/tests/features/field.feature +25 -0
  99. package/tests/features/keyboard.feature +10 -0
  100. package/tests/features/link.feature +11 -0
  101. package/tests/features/modal-advanced-example.feature +1 -1
  102. package/tests/features/modal.feature +11 -0
  103. package/tests/features/path.feature +16 -0
  104. package/tests/features/response.feature +8 -0
  105. package/tests/features/responsive.feature +10 -0
  106. package/tests/features/table.feature +18 -0
  107. package/tests/features/test--then--i-save-screenshot.feature +33 -0
  108. package/tests/features/test--then--i-see-locator.feature +320 -0
  109. package/tests/features/test--then--i-should-see-n-elements.feature +24 -0
  110. package/tests/features/test--then--print-current-url-and-response.feature +21 -0
  111. package/tests/features/test--when--i-additionally-select.feature +30 -0
  112. package/tests/features/test--when--i-follow.feature +22 -0
  113. package/tests/features/wait.feature +7 -0
  114. package/tests/features/yaml.feature +102 -0
  115. package/tests/reports/README.md +55 -0
  116. package/tests/selectors/_canonical-keys.json +113 -0
  117. package/tests/selectors/back-end-selectors.json +19 -0
  118. package/tests/selectors/cms-contentful-admin.json +35 -0
  119. package/tests/selectors/cms-craft-admin.json +39 -0
  120. package/tests/selectors/cms-drupal-cms-gin.json +56 -0
  121. package/tests/selectors/cms-drupal-core-claro.json +50 -0
  122. package/tests/selectors/cms-generic-admin.json +34 -0
  123. package/tests/selectors/cms-ghost-admin.json +34 -0
  124. package/tests/selectors/cms-joomla-admin.json +41 -0
  125. package/tests/selectors/cms-magento2-admin.json +32 -0
  126. package/tests/selectors/cms-prestashop-admin.json +38 -0
  127. package/tests/selectors/cms-shopify-admin.json +25 -0
  128. package/tests/selectors/cms-strapi-admin.json +42 -0
  129. package/tests/selectors/cms-typo3-admin.json +41 -0
  130. package/tests/selectors/cms-woocommerce-front.json +50 -0
  131. package/tests/selectors/cms-wordpress-admin.json +31 -0
  132. package/tests/selectors/framework-ant-design.json +80 -0
  133. package/tests/selectors/framework-bootstrap.json +86 -0
  134. package/tests/selectors/framework-bulma.json +74 -0
  135. package/tests/selectors/framework-chakra.json +58 -0
  136. package/tests/selectors/framework-foundation.json +51 -0
  137. package/tests/selectors/framework-material-ui.json +72 -0
  138. package/tests/selectors/framework-shadcn.json +51 -0
  139. package/tests/selectors/framework-tailwind.json +40 -0
  140. package/tests/selectors/framework-vuetify.json +61 -0
  141. package/tests/selectors/front-end-selectors.json +16 -0
  142. package/tests/selectors/homepage-selectors.json +13 -0
  143. package/tests/step-definitions/a11y.steps.js +798 -0
  144. package/tests/step-definitions/action.steps.js +167 -0
  145. package/tests/step-definitions/{webship-api.js → api.steps.js} +254 -44
  146. package/tests/step-definitions/assertion.steps.js +352 -0
  147. package/tests/step-definitions/auth.steps.js +124 -0
  148. package/tests/step-definitions/clock.steps.js +128 -0
  149. package/tests/step-definitions/cookie.steps.js +216 -0
  150. package/tests/step-definitions/debug.steps.js +31 -0
  151. package/tests/step-definitions/dialog.steps.js +193 -0
  152. package/tests/step-definitions/element.steps.js +314 -0
  153. package/tests/step-definitions/field.steps.js +653 -0
  154. package/tests/step-definitions/file-download.steps.js +193 -0
  155. package/tests/step-definitions/form.steps.js +333 -0
  156. package/tests/step-definitions/iframe.steps.js +178 -0
  157. package/tests/step-definitions/input.steps.js +163 -0
  158. package/tests/step-definitions/javascript.steps.js +71 -0
  159. package/tests/step-definitions/keyboard.steps.js +78 -0
  160. package/tests/step-definitions/link.steps.js +142 -0
  161. package/tests/step-definitions/metatag.steps.js +91 -0
  162. package/tests/step-definitions/modal.steps.js +219 -0
  163. package/tests/step-definitions/navigation.steps.js +218 -0
  164. package/tests/step-definitions/network.steps.js +238 -0
  165. package/tests/step-definitions/path.steps.js +141 -0
  166. package/tests/step-definitions/response.steps.js +98 -0
  167. package/tests/step-definitions/responsive.steps.js +123 -0
  168. package/tests/step-definitions/rest.steps.js +111 -0
  169. package/tests/step-definitions/screenshot.steps.js +423 -0
  170. package/tests/step-definitions/scroll.steps.js +189 -0
  171. package/tests/step-definitions/selectors.steps.js +996 -0
  172. package/tests/step-definitions/storage.steps.js +194 -0
  173. package/tests/step-definitions/table.steps.js +181 -0
  174. package/tests/step-definitions/wait.steps.js +400 -0
  175. package/tests/step-definitions/web-first.steps.js +296 -0
  176. package/tests/step-definitions/webship.js +567 -923
  177. package/tests/step-definitions/xml.steps.js +409 -0
  178. package/tests/step-definitions/yaml.steps.js +911 -0
  179. package/tests/step-definitions-diffy/README.md +329 -0
  180. package/tests/step-definitions-diffy/mock-diffy-api/server.js +84 -0
  181. package/tests/step-definitions-diffy/webship-diffy-mock.js +31 -0
  182. package/tests/step-definitions-diffy/webship-diffy.js +459 -0
  183. package/tsconfig.json +19 -3
  184. package/generate-reports.js +0 -22
  185. package/required/cucumber.js +0 -37
  186. package/required/generate-reports.js +0 -22
  187. package/required/package.json +0 -18
  188. package/required/playwright.config.ts +0 -37
  189. package/required/tests/features/README.md +0 -1
  190. package/required/tests/features/check-homepage.feature +0 -8
  191. package/required/tests/reports/README.md +0 -1
  192. package/required/tests/step-definitions/README.md +0 -1
  193. package/required/tests/step-definitions/custom.js +0 -4
  194. package/required/tsconfig.json +0 -12
@@ -1,79 +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
- // World
12
- // ---------------------------------------------------------------------------
13
- setDefaultTimeout(30 * 1000);
14
-
15
- class PlaywrightWorld extends World {
16
- constructor(options) {
17
- super(options);
18
- this.launchUrl = this.parameters.launchUrl;
19
- this.minWaitTime = this.parameters.minWaitTime;
20
- this.playwrightBrowser = null;
21
- this.context = null;
22
- this.page = null;
23
- this.assetsFolder = path.join(__dirname, '../assets/');
24
- }
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
+ */
27
+
28
+ // ---------------------------------------------------------------------------
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.
45
+ // ---------------------------------------------------------------------------
46
+
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());
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 */ }
78
+ }
25
79
 
26
- async openBrowser() {
27
- const { browser: browserName, launchOptions, contextOptions } = playwrightConfig;
28
- this.playwrightBrowser = await playwright[browserName].launch(launchOptions);
29
- this.context = await this.playwrightBrowser.newContext(contextOptions);
30
- this.page = await this.context.newPage();
31
- }
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
+ }
32
91
 
33
- async closeBrowser() {
34
- if (this.playwrightBrowser) {
35
- await this.playwrightBrowser.close();
36
- this.playwrightBrowser = null;
37
- this.context = null;
38
- this.page = null;
39
- }
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'];
40
106
  }
107
+ return '[role="dialog"], dialog';
41
108
  }
42
109
 
43
- setWorldConstructor(PlaywrightWorld);
44
-
45
- Before(async function () {
46
- await this.openBrowser();
47
- if (this.minWaitTime.before_scenario > 0) {
48
- await this.page.waitForTimeout(this.minWaitTime.before_scenario);
49
- }
50
- });
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
+ }
51
120
 
52
- After(async function () {
53
- if (this.minWaitTime.after_scenario > 0) {
54
- await this.page.waitForTimeout(this.minWaitTime.after_scenario);
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
+ );
55
151
  }
56
- await this.closeBrowser();
57
- });
152
+ }
58
153
 
59
- BeforeStep(async function () {
60
- if (this.page && this.minWaitTime.before_step > 0) {
61
- await this.page.waitForTimeout(this.minWaitTime.before_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);
62
167
  }
63
- });
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
+ }
64
176
 
65
- AfterStep(async function () {
66
- if (this.page && this.minWaitTime.after_step > 0) {
67
- await this.page.waitForTimeout(this.minWaitTime.after_step);
68
- }
69
- });
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
+ }
70
195
 
71
196
  // ---------------------------------------------------------------------------
72
- // Helper: build CSS selector from attrValue + optional attr argument.
73
- // ---------------------------------------------------------------------------
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.
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
+ */
74
211
  function buildSelector(attrValue, attr) {
75
212
  const hasASpace = attrValue.indexOf(' ');
76
- if ((attrValue.startsWith('#') || attrValue.startsWith('.')) && hasASpace === -1) {
213
+ if ((attrValue.startsWith('#') || attrValue.startsWith('.') || attrValue.startsWith('[')) && hasASpace === -1) {
77
214
  return attrValue;
78
215
  }
79
216
  if (!attr && hasASpace === -1) {
@@ -81,38 +218,75 @@ function buildSelector(attrValue, attr) {
81
218
  attrValue +
82
219
  ',#' + attrValue +
83
220
  ',.' + attrValue +
84
- ',[name=' + attrValue + '],' +
85
- '[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 + '"]' +
86
229
  ',[title="' + attrValue + '"]'
87
230
  );
88
231
  }
89
232
  if (!attr && hasASpace > -1) {
90
- return '[value="' + attrValue + '"],[placeholder="' + attrValue + '"]';
233
+ return '[value="' + attrValue + '"],[placeholder="' + attrValue + '"],[aria-label="' + attrValue + '"],[title="' + attrValue + '"]';
91
234
  }
92
235
  return '[' + attr + '="' + attrValue + '" i]';
93
236
  }
94
237
 
95
- // ---------------------------------------------------------------------------
96
- // Helper: wait for domcontentloaded
97
- // ---------------------------------------------------------------------------
98
- async function waitForPageLoad(page, timeout) {
99
- await page.waitForLoadState('domcontentloaded', { timeout: timeout || 10000 });
100
- }
101
-
102
- // ---------------------------------------------------------------------------
103
- // Helper: navigate to a URL, tolerating empty-response errors (Firefox)
104
- // ---------------------------------------------------------------------------
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
+ */
105
251
  async function gotoUrl(page, url) {
106
252
  try {
107
253
  await page.goto(url, { waitUntil: 'domcontentloaded' });
108
254
  } catch (e) {
109
- 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;
110
277
  }
111
278
  }
112
279
 
113
- // ---------------------------------------------------------------------------
114
- // Helper: fill a field located by label, placeholder, or name
115
- // ---------------------------------------------------------------------------
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
+ */
116
290
  async function fillField(page, field, value) {
117
291
  const byLabel = page.getByLabel(field, { exact: true });
118
292
  if (await byLabel.count() > 0) {
@@ -124,12 +298,26 @@ async function fillField(page, field, value) {
124
298
  await byPlaceholder.fill(value);
125
299
  return;
126
300
  }
127
- 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
+ );
128
312
  }
129
313
 
130
- // ---------------------------------------------------------------------------
131
- // Helper: get text from a locator — input value or text content
132
- // ---------------------------------------------------------------------------
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
+ */
133
321
  async function getLocatorText(locator) {
134
322
  try {
135
323
  return await locator.inputValue();
@@ -138,897 +326,353 @@ async function getLocatorText(locator) {
138
326
  }
139
327
  }
140
328
 
141
- const MODAL_SELECTOR = '.modal, .modal.show, .modal.in, [role="dialog"], .dialog, .popup';
142
-
143
- // ---------------------------------------------------------------------------
144
- // Helper: wait for any matching modal element to reach a state
145
- // ---------------------------------------------------------------------------
146
- async function waitForModalState(page, state, timeout) {
147
- const sel = MODAL_SELECTOR;
148
- if (state === 'visible') {
149
- await page.waitForFunction(
150
- (s) => Array.from(document.querySelectorAll(s)).some(el => {
151
- const cs = window.getComputedStyle(el);
152
- return cs.display !== 'none' && cs.visibility !== 'hidden' && el.offsetParent !== null;
153
- }),
154
- sel, { timeout }
155
- );
156
- } else {
157
- await page.waitForFunction(
158
- (s) => !Array.from(document.querySelectorAll(s)).some(el => {
159
- const cs = window.getComputedStyle(el);
160
- return cs.display !== 'none' && cs.visibility !== 'hidden' && el.offsetParent !== null;
161
- }),
162
- sel, { timeout }
163
- );
164
- }
165
- }
166
-
167
- // ---------------------------------------------------------------------------
168
- // Helper: find the first visible modal locator
169
- // ---------------------------------------------------------------------------
170
- async function findVisibleModal(page) {
171
- const all = page.locator(MODAL_SELECTOR);
172
- const count = await all.count();
173
- for (let i = 0; i < count; i++) {
174
- if (await all.nth(i).isVisible()) return all.nth(i);
175
- }
176
- throw new Error('No visible modal found');
329
+ /**
330
+ * Left-pad a number with zeros to the requested width.
331
+ *
332
+ * @param {number} n
333
+ * @param {number} width
334
+ * @returns {string}
335
+ */
336
+ function pad(n, width) {
337
+ const s = String(n);
338
+ return s.length >= width ? s : '0'.repeat(width - s.length) + s;
177
339
  }
178
340
 
179
341
  // ---------------------------------------------------------------------------
180
- // Helper: check if any modal is currently visible
181
- // ---------------------------------------------------------------------------
182
- async function isAnyModalVisible(page) {
183
- return page.evaluate((sel) =>
184
- Array.from(document.querySelectorAll(sel)).some(el => {
185
- const cs = window.getComputedStyle(el);
186
- return cs.display !== 'none' && cs.visibility !== 'hidden' && el.offsetParent !== null;
187
- }),
188
- MODAL_SELECTOR
189
- );
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
+ // ---------------------------------------------------------------------------
359
+
360
+ const RELATIVE_TOKEN_RE = /\[relative:([^\]#]+)(?:#([^\]]+))?\]/g;
361
+
362
+ /**
363
+ * Format a Date with a tiny token vocabulary (`YYYY`, `MM`, `DD`, `HH`,
364
+ * `mm`, `ss`). Sufficient for typical step-arg date formats.
365
+ *
366
+ * @param {Date} date
367
+ * @param {string} fmt
368
+ * @returns {string}
369
+ */
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));
190
378
  }
191
379
 
192
- // ---------------------------------------------------------------------------
193
- // Given I am an anonymous user
194
- // Captures: (pronounCase) = 1
195
- // ---------------------------------------------------------------------------
196
- Given(/^(I am |we are )?an anonymous user$/, async function (pronounCase) {
197
- await this.context.clearCookies();
198
- await gotoUrl(this.page, this.launchUrl);
199
- await waitForPageLoad(this.page, this.minWaitTime.page || 3000);
200
- });
201
-
202
- // ---------------------------------------------------------------------------
203
- // Given I am on homepage / frontpage
204
- // Captures: (pronounCase, theCase, pageCase) = 3
205
- // ---------------------------------------------------------------------------
206
- Given(/^(I am |we are )?on( the)* (homepage|frontpage)$/, async function (pronounCase, theCase, pageCase) {
207
- const defaultTime = this.minWaitTime.page || 3000;
208
- await gotoUrl(this.page, this.launchUrl);
209
- await this.page.waitForSelector('body', { state: 'attached', timeout: defaultTime });
210
- await waitForPageLoad(this.page, defaultTime);
211
- });
212
-
213
- // ---------------------------------------------------------------------------
214
- // Given I am on "/about-us.html"
215
- // Captures: (pronounCase, theCase, url, pageCase) = 4
216
- // ---------------------------------------------------------------------------
217
- Given(/^(I am |we are )*on( the)* "([^"]*)?"( page)*$/, async function (pronounCase, theCase, url, pageCase) {
218
- await gotoUrl(this.page, this.launchUrl + url);
219
- await this.page.waitForSelector('body', { state: 'attached', timeout: 10000 });
220
- await waitForPageLoad(this.page);
221
- });
222
-
223
- // ---------------------------------------------------------------------------
224
- // When I go to homepage / frontpage
225
- // Captures: (pronounCase, theCase, pageCase) = 3
226
- // ---------------------------------------------------------------------------
227
- When(/^(I go |I navigate |we go |we navigate |navigating )?to( the)* (homepage|frontpage)$/, async function (pronounCase, theCase, pageCase) {
228
- const defaultTime = this.minWaitTime.page || 3000;
229
- await gotoUrl(this.page, this.launchUrl);
230
- await this.page.waitForSelector('body', { state: 'attached', timeout: defaultTime });
231
- await waitForPageLoad(this.page, defaultTime);
232
- });
233
-
234
- // ---------------------------------------------------------------------------
235
- // When I go to "/contact-us.html"
236
- // Captures: (pronounCase, url) = 2
237
- // ---------------------------------------------------------------------------
238
- When(/^(I go |I navigate |we go |we navigate |navigating )?to "([^"]*)?"$/, async function (pronounCase, url) {
239
- const defaultTime = this.minWaitTime.page || 3000;
240
- await gotoUrl(this.page, this.launchUrl + url);
241
- await this.page.waitForSelector('body', { state: 'attached', timeout: defaultTime });
242
- await waitForPageLoad(this.page, defaultTime);
243
- });
244
-
245
- // ---------------------------------------------------------------------------
246
- // Then I should see "text" / Then I should not see "text"
247
- // Captures: (pronounCase, notCase, expectedText) = 3
248
- // ---------------------------------------------------------------------------
249
- Then(/^(I |we )*should( not)* see "([^"]*)?"$/, async function (pronounCase, notCase, expectedText) {
250
- if (notCase) {
251
- const text = await this.page.locator('body').textContent() || '';
252
- assert.ok(!text.includes(expectedText), `Page should NOT contain "${expectedText}" but it does.`);
253
- } else {
254
- await this.page.locator('body').filter({ hasText: expectedText }).waitFor({ timeout: 5000 });
255
- }
256
- });
257
-
258
- // ---------------------------------------------------------------------------
259
- // When I move forward one page
260
- // Captures: (pronounCase) = 1
261
- // ---------------------------------------------------------------------------
262
- When(/^(I |we )*move forward one page$/, async function (pronounCase) {
263
- await this.page.goForward();
264
- });
265
-
266
- // ---------------------------------------------------------------------------
267
- // When I move backward one page
268
- // Captures: (pronounCase) = 1
269
- // ---------------------------------------------------------------------------
270
- When(/^(I |we )*move backward one page$/, async function (pronounCase) {
271
- await this.page.goBack();
272
- });
273
-
274
- // ---------------------------------------------------------------------------
275
- // When I press "Log In" button
276
- // Captures: (pronounCase, theCase, element, buttonCase) = 4
277
- // ---------------------------------------------------------------------------
278
- When(/^(I |we )*press( the)* "([^"]*)?"( button)*$/, async function (pronounCase, theCase, element, buttonCase) {
279
- const esc = element.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
280
- await this.page.locator('button, input[type="button"], input[type="submit"], [role="button"], .btn, a')
281
- .filter({ hasText: new RegExp('^' + esc + '$') })
282
- .first()
283
- .click();
284
- });
285
-
286
- // ---------------------------------------------------------------------------
287
- // When I press "btn-pressid" by attr / attribute
288
- // Captures: (pronounCase, attrValue, itsCase, attr, attrWord) = 5
289
- // ---------------------------------------------------------------------------
290
- When(/^(I |we )*press "([^"]*)?" by( its)*(?: "([^"]*)?")* (attribute|attr)$/, async function (pronounCase, attrValue, itsCase, attr, attrWord) {
291
- await this.page.locator(buildSelector(attrValue, attr)).first().click();
292
- });
293
-
294
- // ---------------------------------------------------------------------------
295
- // When I click "Contact Us"
296
- // Captures: (pronounCase, item) = 2
297
- // ---------------------------------------------------------------------------
298
- When(/^(I |we )*click "([^"]*)?"$/, async function (pronounCase, item) {
299
- const esc = item.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
300
- await this.page.locator('a, button, [role="button"], .btn, input[type="button"], input[type="submit"]')
301
- .filter({ hasText: new RegExp('^' + esc + '$') })
302
- .first()
303
- .click();
304
- });
305
-
306
- // ---------------------------------------------------------------------------
307
- // When I click "#about-us-id" by attr / attribute
308
- // Captures: (pronounCase, attrValue, itsCase, attr, attrWord) = 5
309
- // ---------------------------------------------------------------------------
310
- When(/^(I |we )*click "([^"]*)?" by( its)*(?: "([^"]*)?")* (attribute|attr)$/, async function (pronounCase, attrValue, itsCase, attr, attrWord) {
311
- await this.page.locator(buildSelector(attrValue, attr)).first().click();
312
- });
313
-
314
- // ---------------------------------------------------------------------------
315
- // When I click "Edit" in the "John Smith" row
316
- // Captures: (pronounCase, clickText, theCase, rowIdentifier) = 4
317
- // ---------------------------------------------------------------------------
318
- When(/^(I |we )*click "([^"]*)?" in( the)* "([^"]*)?" row$/, async function (pronounCase, clickText, theCase, rowIdentifier) {
319
- const esc = clickText.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
320
- const row = this.page.locator('tr').filter({ hasText: rowIdentifier }).first();
321
- const clickable = row.locator('a, button, [role="button"], .btn, input[type="submit"], input[type="button"]')
322
- .filter({ hasText: new RegExp('^' + esc + '$') });
323
- if (await clickable.count() > 0) {
324
- await clickable.first().click();
325
- } else {
326
- await row.getByText(clickText, { exact: true }).first().click();
327
- }
328
- });
329
-
330
- // ---------------------------------------------------------------------------
331
- // Then I should see "Active" in the "John Smith" row
332
- // Captures: (pronounCase, notCase, expectedText, theCase, rowIdentifier) = 5
333
- // ---------------------------------------------------------------------------
334
- Then(/^(I |we )*should( not)* see "([^"]*)?" in( the)* "([^"]*)?" row$/, async function (pronounCase, notCase, expectedText, theCase, rowIdentifier) {
335
- const found = await this.page.evaluate(({ id, text }) => {
336
- const rows = Array.from(document.querySelectorAll('tr'));
337
- return rows.filter(r => r.textContent.includes(id)).some(r => r.textContent.includes(text));
338
- }, { id: rowIdentifier, text: expectedText });
339
- if (notCase) {
340
- assert.ok(!found, `Found "${expectedText}" in the "${rowIdentifier}" row, but it should not be there.`);
341
- } else {
342
- assert.ok(found, `Could not find "${expectedText}" in the "${rowIdentifier}" row.`);
343
- }
344
- });
345
-
346
- // ---------------------------------------------------------------------------
347
- // When I reload the page
348
- // Captures: (pronounCase, theCase, pageCase) = 3
349
- // ---------------------------------------------------------------------------
350
- When(/^(I |we )*reload( the)*( page)*$/, async function (pronounCase, theCase, pageCase) {
351
- await this.page.reload();
352
- });
353
-
354
- // ---------------------------------------------------------------------------
355
- // When I fill in "Username" with "John Smith"
356
- // Captures: (pronounCase, field, value) = 3
357
- // ---------------------------------------------------------------------------
358
- When(/^(I |we )*fill in "([^"]*)?" with "([^"]*)?"$/, async function (pronounCase, field, value) {
359
- await fillField(this.page, field, value);
360
- });
361
-
362
- // ---------------------------------------------------------------------------
363
- // When I fill in "uname" with "John Smith" by attr
364
- // Captures: (pronounCase, attrValue, txtValue, itsCase, attr, attrWord) = 6
365
- // ---------------------------------------------------------------------------
366
- When(/^(I |we )*fill in "([^"]*)?" with "([^"]*)?" by( its)*(?: "([^"]*)?")* (attribute|attr)$/, async function (pronounCase, attrValue, txtValue, itsCase, attr, attrWord) {
367
- await this.page.locator(buildSelector(attrValue, attr)).first().fill(txtValue);
368
- });
369
-
370
- // ---------------------------------------------------------------------------
371
- // When I fill in "Username" with: (empty)
372
- // Captures: (pronounCase, field) = 2
373
- // ---------------------------------------------------------------------------
374
- When(/^(I |we )*fill in "([^"]*)?" with:$/, async function (pronounCase, field) {
375
- await fillField(this.page, field, '');
376
- });
377
-
378
- // ---------------------------------------------------------------------------
379
- // When I fill in "uname" with: by attr (empty by attr)
380
- // Captures: (pronounCase, attrValue, itsCase, attr, attrWord) = 5
381
- // ---------------------------------------------------------------------------
382
- When(/^(I |we )*fill in "([^"]*)?" with: by( its)*(?: "([^"]*)?")* (attribute|attr)$/, async function (pronounCase, attrValue, itsCase, attr, attrWord) {
383
- await this.page.locator(buildSelector(attrValue, attr)).first().fill('');
384
- });
385
-
386
- // ---------------------------------------------------------------------------
387
- // When I fill in "John Smith" for "Username"
388
- // Captures: (pronounCase, value, field) = 3
389
- // ---------------------------------------------------------------------------
390
- When(/^(I |we )*fill in "([^"]*)?" for "([^"]*)?"$/, async function (pronounCase, value, field) {
391
- await fillField(this.page, field, value);
392
- });
393
-
394
- // ---------------------------------------------------------------------------
395
- // When I fill in "John Smith" for "uname" by attr
396
- // Captures: (pronounCase, txtValue, attrValue, itsCase, attr, attrWord) = 6
397
- // ---------------------------------------------------------------------------
398
- When(/^(I |we )*fill in "([^"]*)?" for "([^"]*)?" by( its)*(?: "([^"]*)?")* (attribute|attr)$/, async function (pronounCase, txtValue, attrValue, itsCase, attr, attrWord) {
399
- await this.page.locator(buildSelector(attrValue, attr)).first().fill(txtValue);
400
- });
401
-
402
- // ---------------------------------------------------------------------------
403
- // When I fill in the following: (table by label)
404
- // Captures: (pronounCase, theCase) = 2
405
- // ---------------------------------------------------------------------------
406
- When(/^(I |we )*fill in( the)* following:$/, async function (pronounCase, theCase, table) {
407
- for (const [field, value] of table.raw()) {
408
- await fillField(this.page, field, value);
409
- }
410
- });
411
-
412
- // ---------------------------------------------------------------------------
413
- // When I fill in the following: by attr (table by attribute)
414
- // Captures: (pronounCase, theCase, itsCase, attr, attrWord) = 5
415
- // ---------------------------------------------------------------------------
416
- When(/^(I |we )*fill in( the)* following: by( its)*(?: "([^"]*)?")* (attribute|attr)$/, async function (pronounCase, theCase, itsCase, attr, attrWord, table) {
417
- for (const [attrValue, value] of table.raw()) {
418
- await this.page.locator(buildSelector(attrValue, attr)).first().fill(value);
419
- }
420
- });
421
-
422
- // ---------------------------------------------------------------------------
423
- // When I select "Mercedes" from "Cars"
424
- // Captures: (pronounCase, option, selectList) = 3
425
- // ---------------------------------------------------------------------------
426
- When(/^(I |we )*select "([^"]*)?" from "([^"]*)?"$/, async function (pronounCase, option, selectList) {
427
- let loc;
428
- if (selectList.startsWith('#') || selectList.startsWith('.')) {
429
- loc = this.page.locator(selectList);
430
- } else if (!selectList.includes(' ')) {
431
- loc = this.page.locator(`[name="${selectList}"], #${selectList}`).first();
432
- } else {
433
- loc = this.page.getByLabel(selectList, { exact: true });
434
- }
435
- try {
436
- await loc.selectOption({ label: option }, { timeout: 3000 });
437
- } catch {
438
- await loc.selectOption(option);
439
- }
440
- });
441
-
442
- // ---------------------------------------------------------------------------
443
- // When I check "Remember me"
444
- // Captures: (pronounCase, item) = 2
445
- // ---------------------------------------------------------------------------
446
- When(/^(I |we )*check "([^"]*)?"$/, async function (pronounCase, item) {
447
- if (item.startsWith('#') || item.startsWith('.')) {
448
- await this.page.locator(item).check();
449
- } else {
450
- const byLabel = this.page.getByLabel(item, { exact: true });
451
- if (await byLabel.count() > 0) {
452
- await byLabel.check();
453
- } else {
454
- await this.page.locator(`input[type="checkbox"][id="${item}"], input[type="checkbox"][name="${item}"], input[type="checkbox"][value="${item}"]`).first().check();
380
+ /**
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;
455
416
  }
417
+ return d.getTime();
456
418
  }
457
- });
458
419
 
459
- // ---------------------------------------------------------------------------
460
- // When I uncheck "Remember me"
461
- // Captures: (pronounCase, item) = 2
462
- // ---------------------------------------------------------------------------
463
- When(/^(I |we )*uncheck "([^"]*)?"$/, async function (pronounCase, item) {
464
- if (item.startsWith('#') || item.startsWith('.')) {
465
- await this.page.locator(item).uncheck();
466
- } else {
467
- const byLabel = this.page.getByLabel(item, { exact: true });
468
- if (await byLabel.count() > 0) {
469
- await byLabel.uncheck();
470
- } else {
471
- await this.page.locator(`input[type="checkbox"][id="${item}"], input[type="checkbox"][name="${item}"], input[type="checkbox"][value="${item}"]`).first().uncheck();
472
- }
473
- }
474
- });
475
-
476
- // ---------------------------------------------------------------------------
477
- // When I select radio button "Male"
478
- // Captures: (pronounCase, item) = 2
479
- // ---------------------------------------------------------------------------
480
- When(/^(I |we )*select radio button "([^"]*)?"$/, async function (pronounCase, item) {
481
- if (item.startsWith('#') || item.startsWith('.')) {
482
- await this.page.locator(item).check();
483
- } else {
484
- const byValue = this.page.locator(`input[type="radio"][value="${item}"]`);
485
- if (await byValue.count() > 0) {
486
- await byValue.first().check();
487
- } else {
488
- await this.page.getByLabel(item, { exact: true }).check();
489
- }
490
- }
491
- });
420
+ const parsed = Date.parse(offset);
421
+ if (!Number.isNaN(parsed)) return parsed;
492
422
 
493
- // ---------------------------------------------------------------------------
494
- // Then I should be on homepage / frontpage
495
- // Captures: (pronounCase, notCase, theCase, pageCase) = 4
496
- // ---------------------------------------------------------------------------
497
- Then(/^(I |we )*should( not)* be on( the)* (homepage|frontpage)$/, async function (pronounCase, notCase, theCase, pageCase) {
498
- const currentUrl = this.page.url();
499
- if (notCase) {
500
- assert.ok(currentUrl !== this.launchUrl && !currentUrl.startsWith(this.launchUrl + '/'),
501
- `Should NOT be on homepage but current URL is: ${currentUrl}`);
502
- } else {
503
- assert.ok(currentUrl.startsWith(this.launchUrl),
504
- `Should be on homepage but current URL is: ${currentUrl}`);
505
- }
506
- });
507
-
508
- // ---------------------------------------------------------------------------
509
- // Then I should be on "/user/login"
510
- // Captures: (pronounCase, notCase, theCase, url, pageCase) = 5
511
- // ---------------------------------------------------------------------------
512
- Then(/^(I |we )*should( not)* be on( the)* "([^"]*)?"( page)*$/, async function (pronounCase, notCase, theCase, url, pageCase) {
513
- const currentUrl = this.page.url();
514
- if (notCase) {
515
- assert.ok(!currentUrl.includes(url), `URL should NOT contain "${url}" but it is: ${currentUrl}`);
516
- } else {
517
- assert.ok(currentUrl.includes(url), `URL should contain "${url}" but it is: ${currentUrl}`);
518
- }
519
- });
423
+ throw new Error(`Cannot evaluate relative date offset: "${offset}"`);
424
+ }
520
425
 
521
- // ---------------------------------------------------------------------------
522
- // Then the "Login" link should contain "/log-in"
523
- // Captures: (theCase, element, url) = 3
524
- // ---------------------------------------------------------------------------
525
- Then(/^(the )*"([^"]*)?" link should contain "([^"]*)?"$/, async function (theCase, element, url) {
526
- const loc = this.page.getByText(element, { exact: true }).first();
527
- await loc.waitFor({ timeout: 5000 });
528
- const href = await loc.evaluate(el => el.href || el.getAttribute('href') || '');
529
- assert.ok(href.includes(url), `Expected link "${element}" href to contain "${url}" but got "${href}"`);
530
- });
426
+ /**
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.
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.
434
+ */
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
+ }
531
444
 
532
- // ---------------------------------------------------------------------------
533
- // Then the "#about-us-id" link should contain "about" by attr
534
- // Captures: (theCase, attrValue, url, itsCase, attr, attrWord) = 6
535
- // ---------------------------------------------------------------------------
536
- Then(/^(the )*"([^"]*)?" link should contain "([^"]*)?" by( its)*(?: "([^"]*)?")* (attribute|attr)$/, async function (theCase, attrValue, url, itsCase, attr, attrWord) {
537
- const loc = this.page.locator(buildSelector(attrValue, attr)).first();
538
- await loc.waitFor({ timeout: 5000 });
539
- const href = await loc.evaluate(el => el.href || el.getAttribute('href') || '');
540
- assert.ok(href.includes(url), `Expected element href to contain "${url}" but got "${href}"`);
541
- });
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;
542
450
 
543
- // ---------------------------------------------------------------------------
544
- // Then the response should contain "text"
545
- // Captures: (theCase, notCase, expectedText) = 3
546
- // ---------------------------------------------------------------------------
547
- Then(/^(the )*response should( not)* contain "([^"]*)?"$/, async function (theCase, notCase, expectedText) {
548
- const text = await this.page.locator('html').textContent() || '';
549
- if (notCase) {
550
- assert.ok(!text.includes(expectedText), `Response should NOT contain "${expectedText}" but it does.`);
551
- } else {
552
- assert.ok(text.includes(expectedText), `Response should contain "${expectedText}" but it does not.`);
451
+ if (typeof step.text === 'string' && step.text.includes('[relative:')) {
452
+ step.text = resolveRelativeDate(step.text);
553
453
  }
554
- });
555
454
 
556
- // ---------------------------------------------------------------------------
557
- // Then I should see "John Smith" in the "Username" element
558
- // Captures: (pronounCase, notCase, expectedText, theCase, element) = 5
559
- // ---------------------------------------------------------------------------
560
- Then(/^(I |we )*should( not)* see "([^"]*)?" in( the)* "([^"]*)?" element$/, async function (pronounCase, notCase, expectedText, theCase, element) {
561
- const forAttr = await this.page.getByText(element, { exact: true }).getAttribute('for').catch(() => null);
562
- const loc = this.page.locator(forAttr ? '#' + forAttr : element).first();
563
- await loc.waitFor({ timeout: 5000 });
564
- const content = await getLocatorText(loc);
565
- if (notCase) {
566
- assert.ok(!content.includes(expectedText), `Element should NOT contain "${expectedText}" but it does.`);
567
- } else {
568
- assert.ok(content.includes(expectedText), `Element should contain "${expectedText}" but it does not.`);
569
- }
570
- });
455
+ if (!step.argument) return;
571
456
 
572
- // ---------------------------------------------------------------------------
573
- // Then I should see "John Smith" in the "uname" element by attr
574
- // Captures: (pronounCase, notCase, expectedText, theCase, attrValue, itsCase, attr, attrWord) = 8
575
- // ---------------------------------------------------------------------------
576
- Then(/^(I |we )*should( not)* see "([^"]*)?" in( the)* "([^"]*)?" element by( its)*(?: "([^"]*)?")* (attribute|attr)$/, async function (pronounCase, notCase, expectedText, theCase, attrValue, itsCase, attr, attrWord) {
577
- const loc = this.page.locator(buildSelector(attrValue, attr)).first();
578
- await loc.waitFor({ timeout: 10000 });
579
- const content = await getLocatorText(loc);
580
- if (notCase) {
581
- assert.ok(!content.includes(expectedText), `Element should NOT contain "${expectedText}" but it does.`);
582
- } else {
583
- assert.ok(content.includes(expectedText), `Element should contain "${expectedText}" but it does not.`);
457
+ if (step.argument.docString && typeof step.argument.docString.content === 'string') {
458
+ step.argument.docString.content = resolveRelativeDate(step.argument.docString.content);
584
459
  }
585
- });
586
460
 
587
- // ---------------------------------------------------------------------------
588
- // Then I should see a "Username" element
589
- // Captures: (pronounCase, notCase, aAnCase, element) = 4
590
- // ---------------------------------------------------------------------------
591
- Then(/^(I |we )*should( not)* see (a|an) "([^"]*)?" element$/, async function (pronounCase, notCase, aAnCase, element) {
592
- if (notCase) {
593
- const text = await this.page.locator('body').textContent() || '';
594
- assert.ok(!text.includes(element), `Page should NOT contain element text "${element}" but it does.`);
595
- } else {
596
- const loc = this.page.getByText(element, { exact: true }).first();
597
- const forAttr = await loc.getAttribute('for').catch(() => null);
598
- if (forAttr) {
599
- await this.page.locator('#' + forAttr).waitFor({ state: 'visible', timeout: 3000 });
600
- } else {
601
- await loc.waitFor({ state: 'visible', timeout: 3000 });
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
+ }
602
469
  }
603
470
  }
604
471
  });
605
472
 
606
- // ---------------------------------------------------------------------------
607
- // Then I should see a "uname" element by attr
608
- // Captures: (pronounCase, notCase, aAnCase, attrValue, itsCase, attr, attrWord) = 7
609
- // ---------------------------------------------------------------------------
610
- Then(/^(I |we )*should( not)* see (a|an) "([^"]*)?" element by( its)*(?: "([^"]*)?")* (attribute|attr)$/, async function (pronounCase, notCase, aAnCase, attrValue, itsCase, attr, attrWord) {
611
- const loc = this.page.locator(buildSelector(attrValue, attr));
612
- if (notCase) {
613
- assert.strictEqual(await loc.count(), 0, `Element should NOT be present but it is.`);
614
- } else {
615
- await loc.first().waitFor({ state: 'visible', timeout: 3000 });
616
- }
617
- });
618
-
619
- // ---------------------------------------------------------------------------
620
- // Then the "body" element should contain "color:white;"
621
- // Captures: (theCase, selectorRaw, notCase, elementCss) = 4
622
- // ---------------------------------------------------------------------------
623
- Then(/^(the )*"([^"]*)?" element should( not)* contain "([^"]*)?"$/, async function (theCase, selectorRaw, notCase, elementCss) {
624
- const cssClean = elementCss.replace(/;$/, '');
625
- const colonIdx = cssClean.indexOf(':');
626
- const cssProperty = cssClean.substring(0, colonIdx).trim();
627
- const expectedValue = cssClean.substring(colonIdx + 1).trim();
628
-
629
- const loc = this.page.locator(buildSelector(selectorRaw)).first();
630
- await loc.waitFor({ timeout: 10000 });
631
- const matches = await loc.evaluate((el, { prop, expectedVal }) => {
632
- function colorToRgb(color) {
633
- const canvas = document.createElement('canvas');
634
- canvas.width = canvas.height = 1;
635
- const ctx = canvas.getContext('2d');
636
- ctx.fillStyle = 'rgb(1, 2, 3)';
637
- ctx.fillStyle = color.trim();
638
- ctx.fillRect(0, 0, 1, 1);
639
- const d = ctx.getImageData(0, 0, 1, 1).data;
640
- return 'rgb(' + d[0] + ', ' + d[1] + ', ' + d[2] + ')';
641
- }
642
- function isValidColor(value) { return colorToRgb(value) !== 'rgb(1, 2, 3)'; }
643
- function normalizeColorTokens(value) {
644
- return value.replace(/rgb\([^)]+\)|rgba\([^)]+\)|#[0-9a-fA-F]+|\b[a-zA-Z]+\b/g,
645
- (token) => isValidColor(token) ? colorToRgb(token) : token);
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
+ };
490
+
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);
646
506
  }
647
- function tokenize(value) {
648
- const tokens = [], regex = /rgb\([^)]+\)|rgba\([^)]+\)|[^\s]+/g;
649
- let m;
650
- while ((m = regex.exec(value)) !== null) tokens.push(m[0]);
651
- return tokens;
652
- }
653
- const computed = window.getComputedStyle(el).getPropertyValue(prop).trim();
654
- return tokenize(normalizeColorTokens(expectedVal.toLowerCase()))
655
- .every(token => normalizeColorTokens(computed.toLowerCase()).includes(token));
656
- }, { prop: cssProperty, expectedVal: expectedValue });
657
-
658
- if (notCase) {
659
- assert.ok(!matches, `Element should NOT have CSS "${cssProperty}: ${expectedValue}" but it does.`);
660
- } else {
661
- assert.ok(matches, `Element should have CSS "${cssProperty}: ${expectedValue}".`);
662
- }
663
- });
664
-
665
- // ---------------------------------------------------------------------------
666
- // Then the "Username" field should contain "John Smith"
667
- // Captures: (theCase, field, notCase, expectedText) = 4
668
- // ---------------------------------------------------------------------------
669
- Then(/^(the )*"([^"]*)?" field should( not)* contain "([^"]*)?"$/, async function (theCase, field, notCase, expectedText) {
670
- let selector = field;
671
- if (!field.startsWith('#') && !field.startsWith('.')) {
672
- const forAttr = await this.page.getByText(field, { exact: true }).getAttribute('for').catch(() => null);
673
- if (forAttr) selector = '#' + forAttr;
674
- }
675
- const loc = this.page.locator(selector).first();
676
- await loc.waitFor({ timeout: 5000 });
677
- const content = await getLocatorText(loc);
678
- if (notCase) {
679
- assert.ok(!content.includes(expectedText), `Field should NOT contain "${expectedText}" but it does.`);
680
- } else {
681
- assert.ok(content.includes(expectedText), `Field should contain "${expectedText}" but it does not.`);
682
- }
683
- });
684
-
685
- // ---------------------------------------------------------------------------
686
- // Then the "#PrivacyPolicy" checkbox should be checked
687
- // Captures: (theCase, checkbox, notCase) = 3
688
- // ---------------------------------------------------------------------------
689
- Then(/^(the )*"([^"]*)?" checkbox should( not)* be checked$/, async function (theCase, checkbox, notCase) {
690
- const isChecked = await this.page.locator(checkbox).isChecked();
691
- if (notCase) {
692
- assert.ok(!isChecked, `Checkbox "${checkbox}" should NOT be checked but it is.`);
693
- } else {
694
- assert.ok(isChecked, `Checkbox "${checkbox}" should be checked but it is not.`);
695
- }
696
- });
507
+ });
508
+ }
697
509
 
698
510
  // ---------------------------------------------------------------------------
699
- // Then the "#rememberMe" checkbox is checked
700
- // Captures: (theCase, checkbox, notCase) = 3
511
+ // World
701
512
  // ---------------------------------------------------------------------------
702
- Then(/^(the )*"([^"]*)?" checkbox is( not)* checked$/, async function (theCase, checkbox, notCase) {
703
- const isChecked = await this.page.locator(checkbox).isChecked();
704
- if (notCase) {
705
- assert.ok(!isChecked, `Checkbox "${checkbox}" should NOT be checked but it is.`);
706
- } else {
707
- assert.ok(isChecked, `Checkbox "${checkbox}" should be checked but it is not.`);
708
- }
709
- });
513
+ setDefaultTimeout(30 * 1000);
710
514
 
711
- // ---------------------------------------------------------------------------
712
- // Then the checkbox "#PrivacyPolicy" should be checked
713
- // Captures: (theCase, checkbox, notCase) = 3
714
- // ---------------------------------------------------------------------------
715
- Then(/^(the )*checkbox "([^"]*)?" should( not)* be checked$/, async function (theCase, checkbox, notCase) {
716
- const isChecked = await this.page.locator(checkbox).isChecked();
717
- if (notCase) {
718
- assert.ok(!isChecked, `Checkbox "${checkbox}" should NOT be checked but it is.`);
719
- } else {
720
- 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/');
721
524
  }
722
- });
723
525
 
724
- // ---------------------------------------------------------------------------
725
- // Then the checkbox "#rememberMe" is checked
726
- // Captures: (theCase, checkbox, notCase) = 3
727
- // ---------------------------------------------------------------------------
728
- Then(/^(the )*checkbox "([^"]*)?" is( not)* checked$/, async function (theCase, checkbox, notCase) {
729
- const isChecked = await this.page.locator(checkbox).isChecked();
730
- if (notCase) {
731
- assert.ok(!isChecked, `Checkbox "${checkbox}" should NOT be checked but it is.`);
732
- } else {
733
- assert.ok(isChecked, `Checkbox "${checkbox}" should be checked but it is not.`);
734
- }
735
- });
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
+ }
736
551
 
737
- // ---------------------------------------------------------------------------
738
- // Then the radio button "#gender-male" should be selected
739
- // Captures: (theCase, radioButton, notCase) = 3
740
- // ---------------------------------------------------------------------------
741
- Then(/^(the )*radio button "([^"]*)?" should( not)* be selected$/, async function (theCase, radioButton, notCase) {
742
- const isChecked = await this.page.locator(radioButton).isChecked();
743
- if (notCase) {
744
- assert.ok(!isChecked, `Radio button "${radioButton}" should NOT be selected but it is.`);
745
- } else {
746
- assert.ok(isChecked, `Radio button "${radioButton}" should be selected but it is not.`);
747
- }
748
- });
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
+ }
749
563
 
750
- // ---------------------------------------------------------------------------
751
- // Then the radio button with value "male" should be selected
752
- // Captures: (theCase, radioValue, notCase) = 3
753
- // ---------------------------------------------------------------------------
754
- Then(/^(the )*radio button with value "([^"]*)?" should( not)* be selected$/, async function (theCase, radioValue, notCase) {
755
- const isChecked = await this.page.locator(`input[type="radio"][value="${radioValue}"]`).first().isChecked();
756
- if (notCase) {
757
- assert.ok(!isChecked, `Radio button with value "${radioValue}" should NOT be selected but it is.`);
758
- } else {
759
- assert.ok(isChecked, `Radio button with value "${radioValue}" should be selected but it is not.`);
760
- }
761
- });
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
+ }
762
593
 
763
- // ---------------------------------------------------------------------------
764
- // Then the "#gender-male" radio button is selected
765
- // Captures: (theCase, radioButton, notCase) = 3
766
- // ---------------------------------------------------------------------------
767
- Then(/^(the )*"([^"]*)?" radio button is( not)* selected$/, async function (theCase, radioButton, notCase) {
768
- const isChecked = await this.page.locator(radioButton).isChecked();
769
- if (notCase) {
770
- assert.ok(!isChecked, `Radio button "${radioButton}" should NOT be selected but it is.`);
771
- } else {
772
- 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();
773
609
  }
774
- });
775
610
 
776
- // ---------------------------------------------------------------------------
777
- // Then the response status code should be 200
778
- // Captures: (theCase, notCase, expectedStatusCode) = 3
779
- // ---------------------------------------------------------------------------
780
- Then(/^(the )*response status code should( not)* be (\d+)$/, async function (theCase, notCase, expectedStatusCode) {
781
- const currentURL = this.page.url();
782
- try {
783
- const response = await axios.get(currentURL);
784
- const status = response.status;
785
- if (notCase) {
786
- assert.notStrictEqual(status, parseInt(expectedStatusCode), `Status code should NOT be ${expectedStatusCode}`);
787
- } else {
788
- assert.strictEqual(status, parseInt(expectedStatusCode), `Expected status ${expectedStatusCode} but got ${status}`);
789
- }
790
- } catch (error) {
791
- const status = error.response ? error.response.status : null;
792
- if (notCase) {
793
- if (status !== null) assert.notStrictEqual(status, parseInt(expectedStatusCode));
794
- } else {
795
- 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;
796
617
  }
797
618
  }
798
- });
799
-
800
- // ---------------------------------------------------------------------------
801
- // Then I should see text matching "^T\w+"
802
- // Captures: (pronounCase, notCase, textPattern) = 3
803
- // ---------------------------------------------------------------------------
804
- Then(/^(I |we )*should( not)* see text matching "([^"]*)?"$/, async function (pronounCase, notCase, textPattern) {
805
- const bodyText = await this.page.evaluate(() => document.body.innerText || '');
806
- const regex = new RegExp(textPattern);
807
- if (notCase) {
808
- assert.ok(!regex.test(bodyText), `Page text should NOT match "${textPattern}" but it does.`);
809
- } else {
810
- assert.ok(regex.test(bodyText), `Page text should match "${textPattern}" but it does not.`);
811
- }
812
- });
813
-
814
- // ---------------------------------------------------------------------------
815
- // Then I should see text matching "..." in the "#date" element
816
- // Captures: (pronounCase, notCase, textPattern, theCase, element) = 5
817
- // ---------------------------------------------------------------------------
818
- Then(/^(I |we )*should( not)* see text matching "([^"]*)?" in( the)* "([^"]*)?" element$/, async function (pronounCase, notCase, textPattern, theCase, element) {
819
- const loc = this.page.locator(element).first();
820
- await loc.waitFor({ timeout: 5000 });
821
- const text = await getLocatorText(loc);
822
- const regex = new RegExp(textPattern);
823
- if (notCase) {
824
- assert.ok(!regex.test(text), `Element "${element}" text should NOT match "${textPattern}" but it does.`);
825
- } else {
826
- assert.ok(regex.test(text), `Element "${element}" text should match "${textPattern}" but it does not.`);
827
- }
828
- });
829
-
830
- // ---------------------------------------------------------------------------
831
- // Then the url should match "/contact-us.html"
832
- // Captures: (theCase, notCase, pattern) = 3
833
- // ---------------------------------------------------------------------------
834
- Then(/^(the )*url should( not)* match "([^"]*)?"$/, async function (theCase, notCase, pattern) {
835
- const currentUrl = this.page.url();
836
- const regex = new RegExp(pattern);
837
- if (notCase) {
838
- assert.ok(!regex.test(currentUrl), `URL "${currentUrl}" should NOT match "${pattern}" but it does.`);
839
- } else {
840
- assert.ok(regex.test(currentUrl), `URL "${currentUrl}" should match "${pattern}" but it does not.`);
841
- }
842
- });
843
-
844
- // ---------------------------------------------------------------------------
845
- // When I attach the file "profileIcon.jpg" to "#profile-icon-upload"
846
- // Captures: (pronounCase, theCase, fileName, element) = 4
847
- // ---------------------------------------------------------------------------
848
- When(/^(I |we )*attach( the)* file "([^"]*)?" to "([^"]*)?"$/, async function (pronounCase, theCase, fileName, element) {
849
- await this.page.locator(element).setInputFiles(path.resolve(this.assetsFolder, fileName));
850
- });
851
-
852
- // ---------------------------------------------------------------------------
853
- // When I wait 1 second / 5 seconds
854
- // Captures: (pronounCase, number, withSecondWord) = 3
855
- // ---------------------------------------------------------------------------
856
- When(/^(I |we )*wait (\d*)( second| seconds|s)?$/, async function (pronounCase, number, withSecondWord) {
857
- await this.page.waitForTimeout(parseInt(number) * 1000);
858
- });
859
-
860
- // ---------------------------------------------------------------------------
861
- // When I wait max of 5 seconds
862
- // Captures: (pronounCase, number, withSecondWord) = 3
863
- // ---------------------------------------------------------------------------
864
- When(/^(I |we )*wait max of (\d*)( second| seconds|s)?$/, async function (pronounCase, number, withSecondWord) {
865
- await this.page.waitForTimeout(parseInt(number) * 1000);
866
- });
867
-
868
- // ---------------------------------------------------------------------------
869
- // When I wait 1 minute
870
- // Captures: (pronounCase, number, withMinuteWord) = 3
871
- // ---------------------------------------------------------------------------
872
- When(/^(I |we )*wait (\d*)( minute| minutes|m)?$/, async function (pronounCase, number, withMinuteWord) {
873
- await this.page.waitForTimeout(parseInt(number) * 1000 * 60);
874
- });
875
-
876
- // ---------------------------------------------------------------------------
877
- // When I wait max of 1 minute
878
- // Captures: (pronounCase, number, withMinuteWord) = 3
879
- // ---------------------------------------------------------------------------
880
- When(/^(I |we )*wait max of (\d*)( minute| minutes|m)?$/, async function (pronounCase, number, withMinuteWord) {
881
- await this.page.waitForTimeout(parseInt(number) * 1000 * 60);
882
- });
883
-
884
- // ---------------------------------------------------------------------------
885
- // When I wait until the page is loaded
886
- // Captures: (pronounCase, theCase, withIs) = 3
887
- // ---------------------------------------------------------------------------
888
- When(/^(I |we )*wait until( the)* page( is)* loaded*$/, async function (pronounCase, theCase, withIs) {
889
- await waitForPageLoad(this.page, 10000);
890
- });
891
-
892
- // ---------------------------------------------------------------------------
893
- // When I wait for AJAX to finish
894
- // Captures: (pronounCase) = 1
895
- // ---------------------------------------------------------------------------
896
- When(/^(I |we )*wait for AJAX to finish$/, async function (pronounCase) {
897
- await this.page.waitForLoadState('networkidle', { timeout: 10000 }).catch(() => {});
898
- });
899
-
900
- // ---------------------------------------------------------------------------
901
- // Scroll steps
902
- // ---------------------------------------------------------------------------
903
- When(/^(I scroll|we scroll|scrolling)? down(?: (\d+))?$/, async function (pronounCase, numValue) {
904
- await this.page.evaluate((v) => window.scrollBy(0, v), numValue ? parseInt(numValue, 10) : 350);
905
- });
906
-
907
- When(/^(I scroll|we scroll|scrolling)? up(?: (\d+))?$/, async function (pronounCase, numValue) {
908
- await this.page.evaluate((v) => window.scrollBy(0, -v), numValue ? parseInt(numValue, 10) : 350);
909
- });
910
-
911
- When(/^(I scroll|we scroll|scrolling)? to( the)* top( of the page)*$/, async function (pronounCase, theCase, pageCase) {
912
- await this.page.evaluate(() => window.scrollTo(0, 0));
913
- });
914
-
915
- When(/^(I scroll|we scroll|scrolling)? to( the)* bottom( of the page)*$/, async function (pronounCase, theCase, pageCase) {
916
- await this.page.evaluate(() => {
917
- window.scrollTo(0, document.body.scrollHeight);
918
- document.querySelectorAll('*').forEach(el => {
919
- const s = window.getComputedStyle(el);
920
- if ((s.overflowY === 'scroll' || s.overflowY === 'auto') && el.scrollHeight > el.clientHeight) {
921
- el.scrollTop = el.scrollHeight;
922
- el.dispatchEvent(new Event('scroll', { bubbles: true }));
923
- }
924
- });
925
- });
926
- });
927
-
928
- When(/^(I scroll|we scroll|scrolling)? to top of "([^"]*)"$/, async function (pronounCase, selector) {
929
- await this.page.locator(selector).evaluate(el => {
930
- el.scrollTop = 0;
931
- el.dispatchEvent(new Event('scroll', { bubbles: true }));
932
- });
933
- });
934
-
935
- When(/^(I scroll|we scroll|scrolling)? to bottom of "([^"]*)"$/, async function (pronounCase, selector) {
936
- await this.page.locator(selector).evaluate(el => {
937
- el.scrollTop = el.scrollHeight;
938
- el.dispatchEvent(new Event('scroll', { bubbles: true }));
939
- });
940
- });
941
-
942
- When(/^(I scroll|we scroll|scrolling)? right(?: (\d+))?$/, async function (pronounCase, numValue) {
943
- await this.page.evaluate((v) => window.scrollBy(v, 0), numValue ? parseInt(numValue, 10) : 350);
944
- });
945
-
946
- When(/^(I scroll|we scroll|scrolling)? left(?: (\d+))?$/, async function (pronounCase, numValue) {
947
- await this.page.evaluate((v) => window.scrollBy(-v, 0), numValue ? parseInt(numValue, 10) : 350);
948
- });
949
-
950
- When(/^(I scroll|we scroll|scrolling)? to( the)* start( of the page)*$/, async function (pronounCase, theCase, pageCase) {
951
- await this.page.evaluate(() => window.scrollTo(0, window.scrollY));
952
- });
953
-
954
- When(/^(I scroll|we scroll|scrolling)? to( the)* end( of the page)*$/, async function (pronounCase, theCase, pageCase) {
955
- await this.page.evaluate(() => window.scrollTo(document.body.scrollWidth, window.scrollY));
956
- });
957
-
958
- When(/^(I scroll|we scroll|scrolling)? to start of "([^"]*)"$/, async function (pronounCase, selector) {
959
- await this.page.locator(selector).evaluate(el => { el.scrollLeft = 0; });
960
- });
961
-
962
- When(/^(I scroll|we scroll|scrolling)? to end of "([^"]*)"$/, async function (pronounCase, selector) {
963
- await this.page.locator(selector).evaluate(el => { el.scrollLeft = el.scrollWidth; });
964
- });
619
+ }
965
620
 
966
- // ---------------------------------------------------------------------------
967
- // Modal steps
968
- // ---------------------------------------------------------------------------
969
- Then(/^(I |we )*should( not)* see (a |the )*modal( dialog)*$/, async function (pronounCase, notCase, aTheCase, dialogCase) {
970
- const visible = await isAnyModalVisible(this.page);
971
- if (notCase) {
972
- assert.ok(!visible, 'Modal dialog is visible, but it should not be.');
973
- } else {
974
- assert.ok(visible, 'Modal dialog is not visible, but it should be.');
975
- }
976
- });
621
+ setWorldConstructor(PlaywrightWorld);
977
622
 
978
- Then(/^(I |we )*should( not)* see (a |the )*modal with title "([^"]*)?"$/, async function (pronounCase, notCase, aTheCase, title) {
979
- const modal = this.page.locator(MODAL_SELECTOR);
980
- const byHeading = modal.locator('.modal-title, .dialog-title, h1, h2, h3').filter({ hasText: title });
981
- const byAttr = modal.locator(`[title*="${title}"], [aria-label*="${title}"]`);
982
- const found = await byHeading.count() > 0 || await byAttr.count() > 0;
983
- if (notCase) {
984
- assert.ok(!found, `Modal with title "${title}" is visible, but it should not be.`);
985
- } else {
986
- 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);
987
627
  }
988
628
  });
989
629
 
990
- Then(/^(I |we )*should( not)* see (a |the )*"([^"]*)?" modal$/, async function (pronounCase, notCase, aTheCase, identifier) {
991
- const selector = (identifier.startsWith('#') || identifier.startsWith('.'))
992
- ? identifier
993
- : `#${identifier}, .${identifier}, [data-modal="${identifier}"]`;
994
- const visible = await this.page.locator(selector).first().isVisible();
995
- if (notCase) {
996
- assert.ok(!visible, `Modal "${identifier}" is visible, but it should not be.`);
997
- } else {
998
- 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);
999
633
  }
634
+ await this.closeBrowser();
1000
635
  });
1001
636
 
1002
- Then(/^(I |we )*should( not)* see "([^"]*)?" in( the)* modal( dialog)*$/, async function (pronounCase, notCase, expectedText, theCase, dialogCase) {
1003
- const found = await this.page.locator(MODAL_SELECTOR).filter({ hasText: expectedText }).count() > 0;
1004
- if (notCase) {
1005
- assert.ok(!found, `Found "${expectedText}" in modal, but it should not be there.`);
1006
- } else {
1007
- 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);
1008
640
  }
1009
641
  });
1010
642
 
1011
- When(/^(I |we )*click "([^"]*)?"( button)* in( the)* modal( dialog)*$/, async function (pronounCase, buttonText, buttonCase, theCase, dialogCase) {
1012
- await waitForModalState(this.page, 'visible', 10000);
1013
- const modal = await findVisibleModal(this.page);
1014
- await modal.locator('button, a, [role="button"], input[type="button"], input[type="submit"], .btn')
1015
- .filter({ hasText: buttonText })
1016
- .first()
1017
- .click();
1018
- });
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;
1019
647
 
1020
- When(/^(I |we )*(close|dismiss)( the)* modal( dialog)*$/, async function (pronounCase, closeOrDismiss, theCase, dialogCase) {
1021
- await waitForModalState(this.page, 'visible', 10000);
1022
- const modal = await findVisibleModal(this.page);
1023
- const closeBtn = modal.locator('.close, .modal-close, [data-dismiss="modal"], [aria-label="Close"], .btn-close, button[class*="close"]').first();
1024
- if (await closeBtn.isVisible()) {
1025
- await closeBtn.click();
1026
- } else {
1027
- 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);
1028
652
  }
1029
- });
1030
-
1031
- When(/^(I |we )*wait for( the)* modal( dialog)* to (appear|disappear)$/, async function (pronounCase, theCase, dialogCase, appearOrDisappear) {
1032
- const state = appearOrDisappear === 'appear' ? 'visible' : 'hidden';
1033
- await waitForModalState(this.page, state, 10000);
1034
- });
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 */ }
659
+ });
660
+
661
+
662
+ // ===========================================================================
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)
678
+ // ===========================================================================