webship-js 2.0.2 → 2.0.4

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (181) hide show
  1. package/.circleci/config.yml +7 -31
  2. package/.drone.yml +68 -0
  3. package/.harness/webship-js-pipeline.yml +101 -0
  4. package/.semaphore/semaphore.yml +58 -0
  5. package/.teamcity/pom.xml +52 -0
  6. package/.teamcity/settings.kts +92 -0
  7. package/.travis.yml +24 -3
  8. package/AGENTS.md +109 -0
  9. package/CLAUDE.md +317 -0
  10. package/Jenkinsfile +54 -0
  11. package/azure-pipelines.yml +82 -0
  12. package/bamboo-specs/bamboo.yml +131 -0
  13. package/bin/generate-reports.js +181 -9
  14. package/buildspec.yml +56 -0
  15. package/cloudbuild.yaml +49 -0
  16. package/codefresh.yml +77 -0
  17. package/cucumber.js +48 -5
  18. package/docs/00-quick-start.md +102 -0
  19. package/docs/01-getting-started.md +102 -0
  20. package/docs/02-bbr-smart-waits.md +77 -0
  21. package/docs/03-selector-registry.md +95 -0
  22. package/docs/04-step-reference.md +799 -0
  23. package/docs/05-web-first-assertions.md +91 -0
  24. package/docs/06-network-and-dialogs.md +83 -0
  25. package/docs/07-auth-state.md +75 -0
  26. package/docs/08-clock-mocking.md +59 -0
  27. package/docs/09-api-testing.md +114 -0
  28. package/docs/10-accessibility.md +167 -0
  29. package/docs/11-debugging.md +129 -0
  30. package/docs/12-ai-agent-guide.md +338 -0
  31. package/docs/13-faq.md +236 -0
  32. package/docs/14-recipes-cookbook.md +255 -0
  33. package/docs/15-tag-conventions.md +76 -0
  34. package/docs/16-ci-cd.md +879 -0
  35. package/docs/README.md +113 -0
  36. package/docs/advanced-screenshots/then-i-save-fullscreen-screenshot.md +36 -0
  37. package/docs/advanced-screenshots/then-i-save-width-x-height-screenshot.md +34 -0
  38. package/docs/advanced-screenshots/when-i-save-screenshot-name-filename.md +45 -0
  39. package/docs/advanced-screenshots.md +52 -0
  40. package/docs/advanced-selectors.md +18 -0
  41. package/docs/api-step-definitions.md +45 -0
  42. package/docs/diffy-step-definitions/then-compare-diffy-env1-env2.md +30 -0
  43. package/docs/diffy-step-definitions/then-create-diffy-comparison-name-value.md +21 -0
  44. package/docs/diffy-step-definitions/then-create-diffy-comparison.md +25 -0
  45. package/docs/diffy-step-definitions/then-create-diffy-screenshot-environment-name.md +35 -0
  46. package/docs/diffy-step-definitions/then-i-take-screenshot.md +21 -0
  47. package/docs/diffy-step-definitions/then-i-take-screenshots-all-breakpoints.md +27 -0
  48. package/docs/diffy-step-definitions/then-send-screenshots-diffy-name-value.md +27 -0
  49. package/docs/diffy-step-definitions/then-upload-folder-url-diffy-snapshotname.md +28 -0
  50. package/docs/diffy-step-definitions/then-wait-diffy-comparison-complete.md +21 -0
  51. package/docs/diffy-step-definitions/when-i-resize-window-number.md +29 -0
  52. package/docs/diffy-step-definitions.md +21 -0
  53. package/docs/global-settings.md +295 -0
  54. package/docs/install-webship-js/ddev-webship-js.md +52 -0
  55. package/docs/install-webship-js.md +35 -0
  56. package/docs/overview.md +41 -0
  57. package/docs/step-definitions/given-i-am-anonymous-user.md +67 -0
  58. package/docs/step-definitions/given-i-am-homepage.md +68 -0
  59. package/docs/step-definitions/given-i-am-specific-page.md +72 -0
  60. package/docs/step-definitions/then-i-should-be.md +56 -0
  61. package/docs/step-definitions/then-i-should-see.md +62 -0
  62. package/docs/step-definitions/then-item-checkbox.md +54 -0
  63. package/docs/step-definitions/then-item-link-should-contain-url.md +84 -0
  64. package/docs/step-definitions/then-item-should-contain.md +67 -0
  65. package/docs/step-definitions/then-radio-button-value-should-be-selected.md +68 -0
  66. package/docs/step-definitions/then-response-status-code-should-be-number.md +69 -0
  67. package/docs/step-definitions/then-value-radio-button-selected.md +62 -0
  68. package/docs/step-definitions/when-i-attach-file-file-name-element.md +71 -0
  69. package/docs/step-definitions/when-i-check-checkbox.md +60 -0
  70. package/docs/step-definitions/when-i-click-link.md +51 -0
  71. package/docs/step-definitions/when-i-click-operation-text-row.md +71 -0
  72. package/docs/step-definitions/when-i-fill.md +59 -0
  73. package/docs/step-definitions/when-i-go-homepage.md +60 -0
  74. package/docs/step-definitions/when-i-go-specific-page.md +67 -0
  75. package/docs/step-definitions/when-i-move-backward-one-page.md +49 -0
  76. package/docs/step-definitions/when-i-move-forward-one-page.md +58 -0
  77. package/docs/step-definitions/when-i-press-button.md +58 -0
  78. package/docs/step-definitions/when-i-reload-page.md +51 -0
  79. package/docs/step-definitions/when-i-scroll.md +73 -0
  80. package/docs/step-definitions/when-i-select-option-select-list.md +53 -0
  81. package/docs/step-definitions/when-i-select-radio-button-value.md +62 -0
  82. package/docs/step-definitions/when-i-uncheck-checkbox.md +57 -0
  83. package/docs/step-definitions/when-i-wait-ajax-finish.md +64 -0
  84. package/docs/step-definitions/when-i-wait.md +62 -0
  85. package/docs/step-definitions.md +50 -0
  86. package/examples/a11y.html +31 -0
  87. package/examples/cookies.html +10 -0
  88. package/examples/date.html +12 -0
  89. package/examples/element.html +11 -0
  90. package/examples/field.html +24 -0
  91. package/examples/keyboard.html +11 -0
  92. package/examples/links.html +9 -0
  93. package/examples/modal.html +14 -0
  94. package/examples/path.html +3 -0
  95. package/examples/table.html +13 -0
  96. package/examples/video-demo.html +43 -0
  97. package/package.json +10 -3
  98. package/playwright.config.ts +3 -2
  99. package/tests/features/a11y.feature +39 -0
  100. package/tests/features/cookie.feature +13 -0
  101. package/tests/features/date.feature +11 -0
  102. package/tests/features/element.feature +16 -0
  103. package/tests/features/field.feature +25 -0
  104. package/tests/features/keyboard.feature +10 -0
  105. package/tests/features/link.feature +11 -0
  106. package/tests/features/modal-advanced-example.feature +1 -1
  107. package/tests/features/modal.feature +11 -0
  108. package/tests/features/path.feature +16 -0
  109. package/tests/features/response.feature +8 -0
  110. package/tests/features/responsive.feature +10 -0
  111. package/tests/features/table.feature +18 -0
  112. package/tests/features/video.feature +18 -0
  113. package/tests/features/wait.feature +7 -0
  114. package/tests/features/yaml.feature +102 -0
  115. package/tests/reports/README.md +55 -0
  116. package/tests/selectors/_canonical-keys.json +113 -0
  117. package/tests/selectors/back-end-selectors.json +7 -1
  118. package/tests/selectors/cms-contentful-admin.json +35 -0
  119. package/tests/selectors/cms-craft-admin.json +39 -0
  120. package/tests/selectors/cms-drupal-cms-gin.json +56 -0
  121. package/tests/selectors/cms-drupal-core-claro.json +50 -0
  122. package/tests/selectors/cms-generic-admin.json +34 -0
  123. package/tests/selectors/cms-ghost-admin.json +34 -0
  124. package/tests/selectors/cms-joomla-admin.json +41 -0
  125. package/tests/selectors/cms-magento2-admin.json +32 -0
  126. package/tests/selectors/cms-prestashop-admin.json +38 -0
  127. package/tests/selectors/cms-shopify-admin.json +25 -0
  128. package/tests/selectors/cms-strapi-admin.json +42 -0
  129. package/tests/selectors/cms-typo3-admin.json +41 -0
  130. package/tests/selectors/cms-woocommerce-front.json +50 -0
  131. package/tests/selectors/cms-wordpress-admin.json +31 -0
  132. package/tests/selectors/framework-ant-design.json +80 -0
  133. package/tests/selectors/framework-bootstrap.json +86 -0
  134. package/tests/selectors/framework-bulma.json +74 -0
  135. package/tests/selectors/framework-chakra.json +58 -0
  136. package/tests/selectors/framework-foundation.json +51 -0
  137. package/tests/selectors/framework-material-ui.json +72 -0
  138. package/tests/selectors/framework-shadcn.json +51 -0
  139. package/tests/selectors/framework-tailwind.json +40 -0
  140. package/tests/selectors/framework-vuetify.json +61 -0
  141. package/tests/step-definitions/a11y.steps.js +800 -0
  142. package/tests/step-definitions/action.steps.js +167 -0
  143. package/tests/step-definitions/{webship-api.js → api.steps.js} +41 -23
  144. package/tests/step-definitions/assertion.steps.js +352 -0
  145. package/tests/step-definitions/auth.steps.js +126 -0
  146. package/tests/step-definitions/clock.steps.js +128 -0
  147. package/tests/step-definitions/cookie.steps.js +216 -0
  148. package/tests/step-definitions/debug.steps.js +39 -0
  149. package/tests/step-definitions/dialog.steps.js +193 -0
  150. package/tests/step-definitions/element.steps.js +356 -0
  151. package/tests/step-definitions/field.steps.js +653 -0
  152. package/tests/step-definitions/file-download.steps.js +211 -0
  153. package/tests/step-definitions/form.steps.js +333 -0
  154. package/tests/step-definitions/iframe.steps.js +228 -0
  155. package/tests/step-definitions/input.steps.js +202 -0
  156. package/tests/step-definitions/javascript.steps.js +232 -0
  157. package/tests/step-definitions/keyboard.steps.js +112 -0
  158. package/tests/step-definitions/link.steps.js +142 -0
  159. package/tests/step-definitions/metatag.steps.js +91 -0
  160. package/tests/step-definitions/modal.steps.js +244 -0
  161. package/tests/step-definitions/navigation.steps.js +218 -0
  162. package/tests/step-definitions/network.steps.js +280 -0
  163. package/tests/step-definitions/path.steps.js +141 -0
  164. package/tests/step-definitions/response.steps.js +98 -0
  165. package/tests/step-definitions/responsive.steps.js +125 -0
  166. package/tests/step-definitions/rest.steps.js +111 -0
  167. package/tests/step-definitions/{webship-screenshot.js → screenshot.steps.js} +1 -5
  168. package/tests/step-definitions/scroll.steps.js +189 -0
  169. package/tests/step-definitions/{webship-selectors.js → selectors.steps.js} +64 -27
  170. package/tests/step-definitions/storage.steps.js +194 -0
  171. package/tests/step-definitions/table.steps.js +181 -0
  172. package/tests/step-definitions/video.steps.js +178 -0
  173. package/tests/step-definitions/wait.steps.js +400 -0
  174. package/tests/step-definitions/web-first.steps.js +298 -0
  175. package/tests/step-definitions/webship.js +741 -1477
  176. package/tests/step-definitions/xml.steps.js +411 -0
  177. package/tests/step-definitions/yaml.steps.js +913 -0
  178. package/tests/step-definitions-diffy/webship-diffy.js +0 -13
  179. package/tsconfig.json +19 -3
  180. package/videos/README.md +32 -0
  181. package/.travis-ci.yml +0 -16
@@ -1,5 +1,7 @@
1
1
  'use strict';
2
2
 
3
+ const { friendly } = require('./webship');
4
+
3
5
  // ---------------------------------------------------------------------------
4
6
  // Webship-JS — Selectors step definitions
5
7
  //
@@ -62,7 +64,7 @@ const path = require('path');
62
64
  function parseFile(filePath) {
63
65
  const ext = path.extname(filePath).toLowerCase();
64
66
  if (ext !== '.json') {
65
- throw new Error(`Selector files must be JSON (got "${ext}" for "${filePath}").`);
67
+ throw friendly(`Selector files must be JSON (got "${ext}" for "${filePath}").`);
66
68
  }
67
69
  return JSON.parse(fs.readFileSync(filePath, 'utf8'));
68
70
  }
@@ -120,7 +122,7 @@ Before(function () {
120
122
  if (parsed && parsed.css) Object.assign(this.__selectorsCss, parsed.css);
121
123
  if (parsed && parsed.xpath) Object.assign(this.__selectorsXpath, parsed.xpath);
122
124
  } catch (e) {
123
- throw new Error(`Selectors: failed to load selector file "${filePath}": ${e.message}`);
125
+ throw friendly(`Selectors: failed to load selector file "${filePath}": ${e.message}`);
124
126
  }
125
127
  }
126
128
  });
@@ -145,7 +147,42 @@ function resolveSelector(world, name) {
145
147
  return xp.startsWith('xpath=') ? xp : `xpath=${xp}`;
146
148
  }
147
149
 
148
- throw new Error(`Selectors: unknown selector "${trimmed}". Register it with "Given I define css selectors:", "When I add ... css selector", "When I add ... xpath selector", or worldParameters.selectors.`);
150
+ // Suggest the closest registered name when one exists. Cheap Levenshtein
151
+ // by character — good enough for short selector names.
152
+ const known = [
153
+ ...Object.keys(world.__selectorsCss || {}),
154
+ ...Object.keys(world.__selectorsXpath || {}),
155
+ ];
156
+ let best = null; let bestDist = Infinity;
157
+ for (const k of known) {
158
+ const dist = (function lev(a, b) {
159
+ const m = a.length, n = b.length;
160
+ if (!m) return n; if (!n) return m;
161
+ const d = Array.from({ length: m + 1 }, () => new Array(n + 1).fill(0));
162
+ for (let i = 0; i <= m; i++) d[i][0] = i;
163
+ for (let j = 0; j <= n; j++) d[0][j] = j;
164
+ for (let i = 1; i <= m; i++) for (let j = 1; j <= n; j++) {
165
+ d[i][j] = a[i - 1] === b[j - 1] ? d[i - 1][j - 1] : 1 + Math.min(d[i - 1][j], d[i][j - 1], d[i - 1][j - 1]);
166
+ }
167
+ return d[m][n];
168
+ })(trimmed.toLowerCase(), k.toLowerCase());
169
+ if (dist < bestDist) { bestDist = dist; best = k; }
170
+ }
171
+ const suggestion = best && bestDist <= Math.max(2, Math.floor(trimmed.length / 3))
172
+ ? `\n Did you mean "${best}"?`
173
+ : '';
174
+ const examples = known.length
175
+ ? `\n Registered names: ${known.slice(0, 8).join(', ')}${known.length > 8 ? ', ...' : ''}`
176
+ : '\n No selectors registered yet.';
177
+
178
+ throw friendly(
179
+ `Unknown selector "${trimmed}".${suggestion}${examples}\n` +
180
+ ` Register one with:\n` +
181
+ ` Given I define css selectors:\n` +
182
+ ` | name | css |\n` +
183
+ ` When I add "${trimmed}" selector for "<css>" css selector\n` +
184
+ ` or load a JSON preset via worldParameters.selectors.files.`
185
+ );
149
186
  }
150
187
 
151
188
  function parseNames(text) {
@@ -184,9 +221,9 @@ async function getGeometry(page, selector) {
184
221
 
185
222
  async function assertPosition(page, position, c1Name, c1Sel, c2Name, c2Sel) {
186
223
  const g1 = await getGeometry(page, c1Sel);
187
- if (!g1) throw new Error(`Cannot get bounding box for "${c1Name}" (${c1Sel}) — element not visible`);
224
+ if (!g1) throw friendly(`Cannot get bounding box for "${c1Name}" (${c1Sel}) — element not visible`);
188
225
  const g2 = await getGeometry(page, c2Sel);
189
- if (!g2) throw new Error(`Cannot get bounding box for "${c2Name}" (${c2Sel}) — element not visible`);
226
+ if (!g2) throw friendly(`Cannot get bounding box for "${c2Name}" (${c2Sel}) — element not visible`);
190
227
 
191
228
  let pass = false;
192
229
  switch (position) {
@@ -227,7 +264,7 @@ async function dispatcher(world, position, subjectText, othersText, negate = fal
227
264
  } catch (e) { errors.push(e.message); }
228
265
  }
229
266
  }
230
- if (errors.length > 0) throw new Error(errors.join('\n'));
267
+ if (errors.length > 0) throw friendly(errors.join('\n'));
231
268
  }
232
269
 
233
270
  // ===========================================================================
@@ -261,7 +298,7 @@ async function dispatcher(world, position, subjectText, othersText, negate = fal
261
298
  * And I add "cta link" selector for "//a[contains(@class,'cta')]" xpath selector
262
299
  */
263
300
  When(/^(I |we )*add "([^"]*)" selector for "([^"]*)" css selector$/, function (pronounCase, selectorName, cssSelector) {
264
- if (!selectorName || !cssSelector) throw new Error('Selectors: selector name and CSS selector must not be empty.');
301
+ if (!selectorName || !cssSelector) throw friendly('Selectors: selector name and CSS selector must not be empty.');
265
302
  this.__selectorsCss[selectorName.trim()] = cssSelector.trim();
266
303
  });
267
304
 
@@ -288,7 +325,7 @@ When(/^(I |we )*add "([^"]*)" selector for "([^"]*)" css selector$/, function (p
288
325
  * When I add "last nav item" selector for "//nav[@role='navigation']//a[last()]" xpath selector
289
326
  */
290
327
  When(/^(I |we )*add "([^"]*)" selector for "([^"]*)" xpath selector$/, function (pronounCase, selectorName, xpathSelector) {
291
- if (!selectorName || !xpathSelector) throw new Error('Selectors: selector name and XPath selector must not be empty.');
328
+ if (!selectorName || !xpathSelector) throw friendly('Selectors: selector name and XPath selector must not be empty.');
292
329
  this.__selectorsXpath[selectorName.trim()] = xpathSelector.trim();
293
330
  });
294
331
 
@@ -322,12 +359,12 @@ When(/^(I |we )*add "([^"]*)" selector for "([^"]*)" xpath selector$/, function
322
359
  */
323
360
  When(/^(I |we )*add selectors from "([^"]*)" file$/, function (pronounCase, fileName) {
324
361
  const cfg = this.__selectorsConfig;
325
- if (!fileName) throw new Error('Selectors: file name must not be empty.');
326
- if (!cfg.filesPath) throw new Error('Selectors: worldParameters.selectors.filesPath must be set to load selector files.');
362
+ if (!fileName) throw friendly('Selectors: file name must not be empty.');
363
+ if (!cfg.filesPath) throw friendly('Selectors: worldParameters.selectors.filesPath must be set to load selector files.');
327
364
  const filePath = path.join(cfg.filesPath, fileName);
328
365
  let parsed;
329
366
  try { parsed = parseFile(filePath); } catch (e) {
330
- throw new Error(`Selectors: failed to load selector file "${filePath}": ${e.message}`);
367
+ throw friendly(`Selectors: failed to load selector file "${filePath}": ${e.message}`);
331
368
  }
332
369
  if (parsed && parsed.css) Object.assign(this.__selectorsCss, parsed.css);
333
370
  if (parsed && parsed.xpath) Object.assign(this.__selectorsXpath, parsed.xpath);
@@ -534,7 +571,7 @@ Given(/^(I |we )*define xpath selectors:$/, function (pronounCase, dataTable) {
534
571
  Given(/^(I am |we are )?viewing the site on a (?:"([^"]+)"|([a-zA-Z0-9 _,]+)) (?:screen|device)$/, async function (pronounCase, quoted, bare) {
535
572
  const name = (quoted || bare || '').trim();
536
573
  const cfg = this.__selectorsConfig;
537
- if (!cfg.breakpoints[name]) throw new Error(`Selectors: breakpoint "${name}" not defined in worldParameters.selectors.breakpoints.`);
574
+ if (!cfg.breakpoints[name]) throw friendly(`Selectors: breakpoint "${name}" not defined in worldParameters.selectors.breakpoints.`);
538
575
  const { width, height } = cfg.breakpoints[name];
539
576
  await this.page.setViewportSize({ width, height });
540
577
  });
@@ -737,7 +774,7 @@ Then(/^(I |we )*see visible ([a-zA-Z0-9 ,\-]+)$/, async function (pronounCase, s
737
774
  try { await this.page.locator(sel).first().waitFor({ state: 'visible', timeout: 5000 }); }
738
775
  catch { errors.push(`"${name}" (${sel}) is not visible`); }
739
776
  }
740
- if (errors.length > 0) throw new Error(errors.join('\n'));
777
+ if (errors.length > 0) throw friendly(errors.join('\n'));
741
778
  });
742
779
 
743
780
  /**
@@ -763,22 +800,22 @@ Then(/^(I |we )*(don't|do not) see ([a-zA-Z0-9 ,\-]+)$/, async function (pronoun
763
800
  try { await this.page.locator(sel).first().waitFor({ state: 'hidden', timeout: 5000 }); }
764
801
  catch { errors.push(`"${name}" (${sel}) is visible (expected hidden)`); }
765
802
  }
766
- if (errors.length > 0) throw new Error(errors.join('\n'));
803
+ if (errors.length > 0) throw friendly(errors.join('\n'));
767
804
  });
768
805
 
769
806
  /**
770
807
  * Assert a named locator has keyboard focus.
771
808
  *
772
- * Example #1: Then search has focus
773
- * Example #2: Then email input has focus
774
- * Example #3: Then submit button has focus
775
- * Example #4: Then username has focus
776
- * Example #5: Then password has focus
777
- * Example #6: Then search button has focus
778
- * Example #7: Then first link has focus
779
- * Example #8: Then skip link has focus
780
- * Example #9: Then close button has focus
781
- * Example #10: Then modal heading has focus
809
+ * Example #1: Then I see search has focus
810
+ * Example #2: Then I see email input has focus
811
+ * Example #3: Then we see submit button has focus
812
+ * Example #4: Then I see username has focus
813
+ * Example #5: Then I see password has focus
814
+ * Example #6: Then we see search button has focus
815
+ * Example #7: Then I see first link has focus
816
+ * Example #8: Then I see skip link has focus
817
+ * Example #9: Then I see close button has focus
818
+ * Example #10: Then I see modal heading has focus
782
819
  */
783
820
  Then(/^(I |we )*see ([a-zA-Z0-9 ,\-]+) has focus$/, async function (pronounCase, subjectText) {
784
821
  const name = subjectText.trim();
@@ -790,7 +827,7 @@ Then(/^(I |we )*see ([a-zA-Z0-9 ,\-]+) has focus$/, async function (pronounCase,
790
827
  const handle = await loc.elementHandle();
791
828
  await this.page.waitForFunction((el) => el === document.activeElement, handle, { timeout: 5000 });
792
829
  } catch {
793
- throw new Error(`"${name}" (${sel}) does not have focus`);
830
+ throw friendly(`"${name}" (${sel}) does not have focus`);
794
831
  }
795
832
  });
796
833
 
@@ -909,7 +946,7 @@ When(/^(I |we )*select "([^"]*)" text in "([^"]*)" field$/, async function (pron
909
946
 
910
947
  const value = await loc.inputValue();
911
948
  const start = value.indexOf(selectedText);
912
- if (start === -1) throw new Error(`Text "${selectedText}" not found in field "${fieldLabel}"`);
949
+ if (start === -1) throw friendly(`Text "${selectedText}" not found in field "${fieldLabel}"`);
913
950
  const end = start + selectedText.length;
914
951
 
915
952
  await loc.focus();
@@ -957,5 +994,5 @@ When(/^(I |we )*click (?:on |a )?([a-zA-Z0-9 ,\-]+)$/, async function (pronounCa
957
994
  try { await this.page.locator(sel).first().click(); }
958
995
  catch (e) { errors.push(`Cannot click "${name}" (${sel}): ${e.message}`); }
959
996
  }
960
- if (errors.length > 0) throw new Error(errors.join('\n'));
997
+ if (errors.length > 0) throw friendly(errors.join('\n'));
961
998
  });
@@ -0,0 +1,194 @@
1
+ 'use strict';
2
+
3
+ // Cookie / local storage / session storage manipulation steps.
4
+ //
5
+ // Pre-seed per-scenario state without going through the UI. Useful for
6
+ // onboarding flags, A/B-test bucket assignments, feature toggles, language
7
+ // preferences, and any cookie-driven server behaviour.
8
+ //
9
+ // Cookies are scoped to the current page's domain (or `localhost` if no page
10
+ // is loaded yet). Local storage and session storage are scoped to the current
11
+ // page's origin and require a navigated page first.
12
+
13
+ const { Given } = require('@cucumber/cucumber');
14
+
15
+ // ---------------------------------------------------------------------------
16
+ // Cookies — context-level
17
+ // ---------------------------------------------------------------------------
18
+
19
+ /**
20
+ * Set a cookie on the current browser context.
21
+ *
22
+ * Example #1: Given the cookie "session" is set to "abc123"
23
+ * Example #2: Given the cookie "lang" is set to "en"
24
+ * Example #3: Given cookie "ab_bucket" is set to "variant-b"
25
+ * Example #4: Given the cookie "consent" is set to "accepted"
26
+ * And I am on the homepage
27
+ * Example #5: Given the cookie "feature_flag" is set to "enabled"
28
+ * And I am on "/dashboard"
29
+ *
30
+ */
31
+ Given(/^(?:the cookie|cookie) "([^"]*)" is set to "([^"]*)"$/, async function (name, value) {
32
+ const url = this.page.url() && this.page.url() !== 'about:blank' ? this.page.url() : (this.launchUrl || 'http://localhost');
33
+ const u = new URL(url);
34
+ await this.context.addCookies([{
35
+ name,
36
+ value,
37
+ domain: u.hostname,
38
+ path: '/',
39
+ }]);
40
+ });
41
+
42
+ /**
43
+ * Remove a single cookie by name (other cookies preserved).
44
+ *
45
+ * Example #1: Given the cookie "session" is removed
46
+ * Example #2: Given the cookie "consent" is removed
47
+ * When I reload the page
48
+ * Then I should see "Accept cookies"
49
+ * Example #3: Given the cookie "ab_bucket" is removed
50
+ * Example #4: Given the cookie "lang" is removed
51
+ * And I am on the homepage
52
+ * Example #5: Given the cookie "feature_flag" is removed
53
+ * When I follow "Pricing"
54
+ *
55
+ */
56
+ Given(/^the cookie "([^"]*)" is removed$/, async function (name) {
57
+ const cookies = await this.context.cookies();
58
+ const remaining = cookies.filter((c) => c.name !== name);
59
+ await this.context.clearCookies();
60
+ if (remaining.length) await this.context.addCookies(remaining);
61
+ });
62
+
63
+ /**
64
+ * Wipe every cookie on the browser context.
65
+ *
66
+ * Example #1: Given all cookies are cleared
67
+ * Example #2: Given all cookies are cleared
68
+ * When I am on the homepage
69
+ * Then I should see "Sign in"
70
+ * Example #3: Given all cookies are cleared
71
+ * And I am an anonymous user
72
+ * Example #4: Given all cookies are cleared
73
+ * And localStorage is cleared
74
+ * And sessionStorage is cleared
75
+ * Example #5: Given all cookies are cleared
76
+ * When I follow "Login"
77
+ *
78
+ */
79
+ Given(/^all cookies are cleared$/, async function () {
80
+ await this.context.clearCookies();
81
+ });
82
+
83
+ // ---------------------------------------------------------------------------
84
+ // localStorage / sessionStorage — page-level
85
+ // ---------------------------------------------------------------------------
86
+
87
+ /**
88
+ * Set a local storage entry on the current page.
89
+ *
90
+ * The page must be loaded first (local storage is per-origin). Stored value
91
+ * is always a string — JSON-encode complex objects manually.
92
+ *
93
+ * Example #1: Given the local storage "user" is set to "Alice"
94
+ * Example #2: Given I am on the homepage
95
+ * And the local storage "theme" is set to "dark"
96
+ * When I reload the page
97
+ * Then "<body>" should have class "theme-dark"
98
+ * Example #3: Given local storage "lang" is set to "fr"
99
+ * Example #4: Given the local storage "onboarding_complete" is set to "true"
100
+ * And I am on "/dashboard"
101
+ * Then I should not see "Welcome tour"
102
+ * Example #5: Given the local storage "feature_flag" is set to "enabled"
103
+ *
104
+ */
105
+ Given(/^(?:the )?local storage "([^"]*)" is set to "([^"]*)"$/, async function (key, value) {
106
+ await this.page.evaluate(({ k, v }) => localStorage.setItem(k, v), { k: key, v: value });
107
+ });
108
+
109
+ /**
110
+ * Remove a single local storage entry.
111
+ *
112
+ * Example #1: Given the local storage "user" is removed
113
+ * Example #2: Given local storage "theme" is removed
114
+ * When I reload the page
115
+ * Then "<body>" should not have class "theme-dark"
116
+ * Example #3: Given the local storage "onboarding_complete" is removed
117
+ * Example #4: Given the local storage "cart" is removed
118
+ * And I am on "/cart"
119
+ * Then I should see "Your cart is empty"
120
+ * Example #5: Given the local storage "auth_token" is removed
121
+ *
122
+ */
123
+ Given(/^(?:the )?local storage "([^"]*)" is removed$/, async function (key) {
124
+ await this.page.evaluate((k) => localStorage.removeItem(k), key);
125
+ });
126
+
127
+ /**
128
+ * Wipe local storage for the current origin.
129
+ *
130
+ * Example #1: Given local storage is cleared
131
+ * Example #2: Given I am on the homepage
132
+ * And local storage is cleared
133
+ * When I reload the page
134
+ * Example #3: Given local storage is cleared
135
+ * And all cookies are cleared
136
+ * Example #4: Given local storage is cleared
137
+ * And session storage is cleared
138
+ * Example #5: Given local storage is cleared
139
+ * Then I should see "First-time visitor"
140
+ *
141
+ */
142
+ Given(/^local storage is cleared$/, async function () {
143
+ await this.page.evaluate(() => localStorage.clear());
144
+ });
145
+
146
+ /**
147
+ * Set a session storage entry on the current page.
148
+ *
149
+ * Example #1: Given the session storage "checkout step" is set to "2"
150
+ * Example #2: Given the session storage "temp form" is set to "draft"
151
+ * Example #3: Given session storage "tab id" is set to "tab-1"
152
+ * Example #4: Given the session storage "wizard progress" is set to "3/5"
153
+ * And I am on "/wizard"
154
+ * Example #5: Given the session storage "from checkout" is set to "true"
155
+ * And I am on "/cart"
156
+ *
157
+ */
158
+ Given(/^(?:the )?session storage "([^"]*)" is set to "([^"]*)"$/, async function (key, value) {
159
+ await this.page.evaluate(({ k, v }) => sessionStorage.setItem(k, v), { k: key, v: value });
160
+ });
161
+
162
+ /**
163
+ * Remove a single session storage entry.
164
+ *
165
+ * Example #1: Given the session storage "checkout step" is removed
166
+ * Example #2: Given session storage "temp form" is removed
167
+ * Example #3: Given the session storage "wizard progress" is removed
168
+ * When I reload the page
169
+ * Then I should see "Step 1"
170
+ * Example #4: Given the session storage "tab id" is removed
171
+ * Example #5: Given the session storage "from checkout" is removed
172
+ *
173
+ */
174
+ Given(/^(?:the )?session storage "([^"]*)" is removed$/, async function (key) {
175
+ await this.page.evaluate((k) => sessionStorage.removeItem(k), key);
176
+ });
177
+
178
+ /**
179
+ * Wipe session storage for the current origin.
180
+ *
181
+ * Example #1: Given session storage is cleared
182
+ * Example #2: Given session storage is cleared
183
+ * And local storage is cleared
184
+ * Example #3: Given session storage is cleared
185
+ * And all cookies are cleared
186
+ * Example #4: Given session storage is cleared
187
+ * When I reload the page
188
+ * Example #5: Given session storage is cleared
189
+ * And I am an anonymous user
190
+ *
191
+ */
192
+ Given(/^session storage is cleared$/, async function () {
193
+ await this.page.evaluate(() => sessionStorage.clear());
194
+ });
@@ -0,0 +1,181 @@
1
+ 'use strict';
2
+
3
+ // Inspect and assert HTML table contents.
4
+
5
+ const { Then } = require('@cucumber/cucumber');
6
+ const assert = require('assert');
7
+
8
+ async function getTable(page, sel) {
9
+ return await page.locator(sel).first().evaluate((tbl) => {
10
+ const rows = Array.from(tbl.querySelectorAll('tr'));
11
+ const head = Array.from((tbl.querySelector('thead') || tbl).querySelectorAll('th')).map((c) => c.textContent.trim());
12
+ const body = rows
13
+ .filter((r) => r.querySelector('td'))
14
+ .map((r) => Array.from(r.querySelectorAll('td')).map((c) => c.textContent.trim()));
15
+ return { head, body, rowCount: body.length, colCount: (body[0] || head).length };
16
+ });
17
+ }
18
+
19
+ /**
20
+ * Assert a table has exactly N body rows.
21
+ *
22
+ * Example #1: Then the table "#users" should have 5 rows
23
+ * Example #2: Then the table "table.orders" should have 1 row
24
+ * Example #3: And the table "[data-testid=products]" should have 12 rows
25
+ * Example #4: Then the table "#audit-log" should have 0 rows
26
+ * Example #5: Then the table "table.responsive" should have 20 rows
27
+ *
28
+ */
29
+ Then('the table {string} should have {int} row(s)', async function (sel, count) {
30
+ const t = await getTable(this.page, sel);
31
+ assert.strictEqual(t.rowCount, count, `Table "${sel}" has ${t.rowCount} rows, expected ${count}.`);
32
+ });
33
+
34
+ /**
35
+ * Assert a table has exactly N columns.
36
+ *
37
+ * Example #1: Then the table "#users" should have 4 columns
38
+ * Example #2: Then the table "table.orders" should have 6 columns
39
+ * Example #3: And the table "[data-testid=products]" should have 5 columns
40
+ * Example #4: Then the table "#summary" should have 2 columns
41
+ * Example #5: Then the table "table.responsive" should have 8 columns
42
+ *
43
+ */
44
+ Then('the table {string} should have {int} column(s)', async function (sel, count) {
45
+ const t = await getTable(this.page, sel);
46
+ assert.strictEqual(t.colCount, count, `Table "${sel}" has ${t.colCount} columns, expected ${count}.`);
47
+ });
48
+
49
+ /**
50
+ * Assert the table header contains every column listed in the table.
51
+ *
52
+ * Example #1: Then the table "#users" should contain the following columns:
53
+ * | Name |
54
+ * | Email |
55
+ * Example #2: Then the table "table.orders" should contain the following columns:
56
+ * | Order ID | Status | Total |
57
+ * Example #3: And the table "[data-testid=products]" should contain the following columns:
58
+ * | Title | Price | Stock |
59
+ * Example #4: Then the table "#audit-log" should contain the following columns:
60
+ * | Timestamp | Actor | Action |
61
+ * Example #5: Then the table ".grid" should contain the following columns:
62
+ * | Country | Population | Capital |
63
+ *
64
+ */
65
+ Then('the table {string} should contain the following columns:', async function (sel, table) {
66
+ const t = await getTable(this.page, sel);
67
+ const want = table.raw().flat();
68
+ for (const col of want) {
69
+ assert.ok(t.head.includes(col), `Column "${col}" not found in [${t.head.join(', ')}].`);
70
+ }
71
+ });
72
+
73
+ /**
74
+ * Assert a table has zero body rows.
75
+ *
76
+ * Example #1: Then the table "#users" should be empty
77
+ * Example #2: Then the table "table.orders" should be empty
78
+ * Example #3: And the table "[data-testid=products]" should be empty
79
+ * Example #4: Then the table "#audit-log" should be empty
80
+ * Example #5: Then the table ".grid" should be empty
81
+ *
82
+ */
83
+ Then('the table {string} should be empty', async function (sel) {
84
+ const t = await getTable(this.page, sel);
85
+ assert.strictEqual(t.rowCount, 0, `Table "${sel}" should be empty.`);
86
+ });
87
+
88
+ /**
89
+ * Assert a table has at least one body row.
90
+ *
91
+ * Example #1: Then the table "#users" should not be empty
92
+ * Example #2: Then the table "table.orders" should not be empty
93
+ * Example #3: And the table "[data-testid=products]" should not be empty
94
+ * Example #4: Then the table "#audit-log" should not be empty
95
+ * Example #5: Then the table ".grid" should not be empty
96
+ *
97
+ */
98
+ Then('the table {string} should not be empty', async function (sel) {
99
+ const t = await getTable(this.page, sel);
100
+ assert.ok(t.rowCount > 0, `Table "${sel}" should not be empty.`);
101
+ });
102
+
103
+ /**
104
+ * Assert a table is sorted ascending or descending by a header.
105
+ *
106
+ * Direction accepts `ascending` / `asc` / `descending` / `desc`.
107
+ *
108
+ * Example #1: Then the table "#users" should be sorted by "Name" in "ascending" order
109
+ * Example #2: Then the table "table.orders" should be sorted by "Total" in "descending" order
110
+ * Example #3: And the table "[data-testid=products]" should be sorted by "Price" in "asc" order
111
+ * Example #4: Then the table "#audit-log" should be sorted by "Timestamp" in "desc" order
112
+ * Example #5: Then the table ".grid" should be sorted by "Country" in "ascending" order
113
+ *
114
+ */
115
+ Then('the table {string} should be sorted by {string} in {string} order', async function (sel, column, direction) {
116
+ const t = await getTable(this.page, sel);
117
+ const idx = t.head.findIndex((h) => h === column);
118
+ assert.ok(idx !== -1, `Column "${column}" not found.`);
119
+ const values = t.body.map((r) => r[idx]);
120
+ const sorted = [...values].sort();
121
+ if (direction.toLowerCase() === 'descending' || direction.toLowerCase() === 'desc') sorted.reverse();
122
+ assert.deepStrictEqual(values, sorted, `Table "${sel}" not sorted by "${column}" ${direction}.`);
123
+ });
124
+
125
+ /**
126
+ * Assert a table contains every row described by the data table (substring match per cell).
127
+ *
128
+ * Example #1: Then the table "#users" should contain the following rows:
129
+ * | Alice | Editor |
130
+ * | Bob | Admin |
131
+ * Example #2: Then the table "table.orders" should contain the following rows:
132
+ * | 1234 | Shipped |
133
+ * | 5678 | Cancelled |
134
+ * Example #3: And the table "[data-testid=products]" should contain the following rows:
135
+ * | Laptop | $999.00 |
136
+ * Example #4: Then the table "#audit-log" should contain the following rows:
137
+ * | login |
138
+ * Example #5: Then the table ".grid" should contain the following rows:
139
+ * | Jordan | Amman |
140
+ *
141
+ */
142
+ Then('the table {string} should contain the following rows:', async function (sel, table) {
143
+ const t = await getTable(this.page, sel);
144
+ for (const row of table.raw()) {
145
+ const found = t.body.some((br) => row.every((cell) => br.some((bc) => bc.indexOf(cell) !== -1)));
146
+ assert.ok(found, `Row ${JSON.stringify(row)} not found in table.`);
147
+ }
148
+ });
149
+
150
+ /**
151
+ * Assert a row containing a given text fragment also contains every listed cell value.
152
+ *
153
+ * Example #1: Then the "Alice" row should contain the following:
154
+ * | Editor |
155
+ * | Active |
156
+ * Example #2: Then the "Order #1234" row should contain the following:
157
+ * | Shipped |
158
+ * Example #3: And the "Project Alpha" row should contain the following:
159
+ * | Open |
160
+ * | High |
161
+ * Example #4: Then the "alice@example.com" row should contain the following:
162
+ * | Admin |
163
+ * Example #5: Then the "Premium" row should contain the following:
164
+ * | $99 |
165
+ *
166
+ */
167
+ Then('the {string} row should contain the following:', async function (rowText, table) {
168
+ const cells = table.raw().flat();
169
+ // Find a tr whose text contains rowText.
170
+ const trs = await this.page.locator('tr').all();
171
+ let match = null;
172
+ for (const tr of trs) {
173
+ const txt = await tr.innerText();
174
+ if (txt.indexOf(rowText) !== -1) { match = tr; break; }
175
+ }
176
+ assert.ok(match, `No row matching "${rowText}" was found.`);
177
+ const text = await match.innerText();
178
+ for (const c of cells) {
179
+ assert.ok(text.indexOf(c) !== -1, `Row "${rowText}" does not contain "${c}".`);
180
+ }
181
+ });