webship-js 2.0.11 → 2.0.13

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 (175) hide show
  1. package/.circleci/config.yml +10 -1
  2. package/.drone.yml +7 -7
  3. package/.github/workflows/github-actions.yml +48 -0
  4. package/.gitlab-ci.yml +9 -4
  5. package/.harness/webship-js-pipeline.yml +5 -6
  6. package/.semaphore/semaphore.yml +6 -9
  7. package/.teamcity/settings.kts +7 -6
  8. package/.travis.yml +6 -1
  9. package/AGENTS.md +1 -1
  10. package/CLAUDE.md +65 -23
  11. package/Jenkinsfile +5 -3
  12. package/azure-pipelines.yml +17 -8
  13. package/bamboo-specs/bamboo.yml +9 -15
  14. package/bin/init-webship.js +53 -10
  15. package/bitbucket-pipelines.yml +5 -1
  16. package/buildspec.yml +6 -7
  17. package/cloudbuild.yaml +28 -12
  18. package/codefresh.yml +6 -6
  19. package/cucumber.js +17 -10
  20. package/docs/00-quick-start.md +8 -0
  21. package/docs/02-bbr-smart-waits.md +15 -10
  22. package/docs/03-selector-registry.md +24 -0
  23. package/docs/04-step-reference.md +51 -25
  24. package/docs/05-web-first-assertions.md +6 -0
  25. package/docs/07-auth-state.md +1 -1
  26. package/docs/08-clock-mocking.md +21 -2
  27. package/docs/09-api-testing.md +40 -2
  28. package/docs/10-accessibility.md +2 -0
  29. package/docs/11-debugging.md +3 -1
  30. package/docs/12-ai-agent-guide.md +5 -0
  31. package/docs/13-faq.md +72 -1
  32. package/docs/14-recipes-cookbook.md +2 -0
  33. package/docs/15-tag-conventions.md +2 -1
  34. package/docs/16-ci-cd.md +140 -119
  35. package/docs/README.md +5 -5
  36. package/docs/advanced-screenshots.md +3 -1
  37. package/docs/api-step-definitions.md +16 -2
  38. package/docs/global-settings.md +69 -17
  39. package/docs/install-webship-js.md +2 -0
  40. package/docs/step-definitions/then-i-should-see.md +14 -1
  41. package/docs/step-definitions/then-item-checkbox.md +2 -0
  42. package/docs/step-definitions/when-i-fill.md +4 -0
  43. package/docs/step-definitions/when-i-select-option-select-list.md +2 -0
  44. package/examples/check-switch.html +37 -0
  45. package/examples/choice-controls.html +29 -0
  46. package/examples/click-whitespace.html +37 -0
  47. package/examples/datetime-fields.html +52 -0
  48. package/examples/element-selector-hint.html +16 -0
  49. package/examples/field-states.html +27 -0
  50. package/examples/fill-in-empty.html +26 -0
  51. package/examples/fill-unreachable.html +27 -0
  52. package/examples/follow-hidden-first.html +29 -0
  53. package/examples/iframe-inner.html +20 -0
  54. package/examples/iframe-nested.html +16 -0
  55. package/examples/iframe-outer.html +15 -0
  56. package/examples/multi-value-fields.html +54 -0
  57. package/examples/registered-names.html +15 -0
  58. package/examples/select-by-label.html +33 -0
  59. package/examples/settle-budget.html +21 -0
  60. package/examples/sorted-tables.html +38 -0
  61. package/examples/text-matching.html +48 -0
  62. package/examples/text-order.html +25 -0
  63. package/examples/touch.html +22 -0
  64. package/examples/viewport-top.html +36 -0
  65. package/package.json +17 -1
  66. package/playwright.config.ts +3 -1
  67. package/tests/check-api-launch-url.js +106 -0
  68. package/tests/check-assets.js +103 -0
  69. package/tests/check-attachments.js +105 -0
  70. package/tests/check-breakpoints.js +117 -0
  71. package/tests/check-clock.js +143 -0
  72. package/tests/check-config.js +90 -0
  73. package/tests/check-context.js +215 -0
  74. package/tests/check-dry-run.js +104 -0
  75. package/tests/check-examples.js +10 -4
  76. package/tests/check-exit-report.js +141 -0
  77. package/tests/check-javascript-errors.js +105 -0
  78. package/tests/check-must-fail.js +5 -4
  79. package/tests/check-network-changed.js +137 -0
  80. package/tests/check-scaffold.js +54 -2
  81. package/tests/check-screenshots.js +117 -0
  82. package/tests/check-settle-verbs.js +137 -0
  83. package/tests/check-time-limit.js +104 -0
  84. package/tests/check-video.js +156 -0
  85. package/tests/check-world.js +167 -0
  86. package/tests/features/api-base-url.feature +25 -0
  87. package/tests/features/api-form-data.feature +18 -0
  88. package/tests/features/api-json-paths.feature +24 -0
  89. package/tests/features/api-response-contains.feature +21 -0
  90. package/tests/features/api-response-header-presence.feature +17 -0
  91. package/tests/features/api-response-header.feature +17 -0
  92. package/tests/features/api-saved-placeholders.feature +37 -0
  93. package/tests/features/api-step-definitions-individual.feature +1 -1
  94. package/tests/features/api-tables.feature +40 -0
  95. package/tests/features/breakpoints.feature +25 -0
  96. package/tests/features/check-switch.feature +28 -0
  97. package/tests/features/choice-controls.feature +35 -0
  98. package/tests/features/click-whitespace.feature +29 -0
  99. package/tests/features/complete-api-testing-examples.feature +1 -1
  100. package/tests/features/datetime-field-lookup.feature +29 -0
  101. package/tests/features/element-selector-hint.feature +14 -0
  102. package/tests/features/field-state.feature +21 -0
  103. package/tests/features/fill-in-empty-value.feature +41 -0
  104. package/tests/features/fill-reachable.feature +13 -0
  105. package/tests/features/follow-hidden-first.feature +9 -0
  106. package/tests/features/iframe-nested.feature +43 -0
  107. package/tests/features/javascript-tolerated-errors.feature +20 -0
  108. package/tests/features/modal-open.feature +13 -0
  109. package/tests/features/multi-value-field-lookup.feature +30 -0
  110. package/tests/features/registered-names.feature +14 -0
  111. package/tests/features/select-by-label.feature +31 -0
  112. package/tests/features/selector-files.feature +14 -0
  113. package/tests/features/selectors-table-header.feature +35 -0
  114. package/tests/features/settle-budget.feature +11 -0
  115. package/tests/features/sorted-tables.feature +19 -0
  116. package/tests/features/storage-quoted-values.feature +26 -0
  117. package/tests/features/text-matching.feature +38 -0
  118. package/tests/features/text-order.feature +14 -0
  119. package/tests/features/touch.feature +21 -0
  120. package/tests/features/viewport-top.feature +13 -0
  121. package/tests/features/xml-namespaces.feature +34 -0
  122. package/tests/must-fail/api-json-paths.feature +21 -0
  123. package/tests/must-fail/api-response-contains.feature +23 -0
  124. package/tests/must-fail/api-response-header-presence.feature +17 -0
  125. package/tests/must-fail/api-response-header.feature +21 -0
  126. package/tests/must-fail/api-without-base-url.feature +11 -0
  127. package/tests/must-fail/breakpoints.feature +15 -0
  128. package/tests/must-fail/choice-controls.feature +25 -0
  129. package/tests/must-fail/clock.feature +11 -0
  130. package/tests/must-fail/datetime-field.feature +10 -0
  131. package/tests/must-fail/element-selector-hint.feature +17 -0
  132. package/tests/must-fail/field-state.feature +20 -0
  133. package/tests/must-fail/fill-field.feature +30 -0
  134. package/tests/must-fail/iframe-text.feature +17 -0
  135. package/tests/must-fail/modal-open.feature +26 -0
  136. package/tests/must-fail/multi-value-field.feature +18 -0
  137. package/tests/must-fail/registered-names.feature +25 -0
  138. package/tests/must-fail/select-list.feature +15 -0
  139. package/tests/must-fail/selector-files.feature +10 -0
  140. package/tests/must-fail/sorted-tables.feature +20 -0
  141. package/tests/must-fail/storage-before-a-page.feature +13 -0
  142. package/tests/must-fail/text-matching.feature +16 -0
  143. package/tests/must-fail/text-order.feature +15 -0
  144. package/tests/must-fail/viewport-top.feature +20 -0
  145. package/tests/must-fail/yaml-numbers.feature +48 -0
  146. package/tests/step-definitions/a11y.steps.js +24 -15
  147. package/tests/step-definitions/action.steps.js +53 -20
  148. package/tests/step-definitions/api.steps.js +349 -67
  149. package/tests/step-definitions/assertion.steps.js +100 -10
  150. package/tests/step-definitions/auth.steps.js +15 -18
  151. package/tests/step-definitions/clock.steps.js +22 -0
  152. package/tests/step-definitions/debug.steps.js +8 -0
  153. package/tests/step-definitions/dialog.steps.js +7 -0
  154. package/tests/step-definitions/element.steps.js +132 -17
  155. package/tests/step-definitions/field.steps.js +412 -96
  156. package/tests/step-definitions/form.steps.js +88 -37
  157. package/tests/step-definitions/iframe.steps.js +89 -29
  158. package/tests/step-definitions/input.steps.js +26 -7
  159. package/tests/step-definitions/javascript.steps.js +64 -22
  160. package/tests/step-definitions/modal.steps.js +79 -13
  161. package/tests/step-definitions/navigation.steps.js +14 -0
  162. package/tests/step-definitions/network.steps.js +15 -5
  163. package/tests/step-definitions/response.steps.js +6 -4
  164. package/tests/step-definitions/responsive.steps.js +26 -33
  165. package/tests/step-definitions/screenshot.steps.js +25 -8
  166. package/tests/step-definitions/scroll.steps.js +20 -0
  167. package/tests/step-definitions/selectors.steps.js +95 -48
  168. package/tests/step-definitions/storage.steps.js +38 -13
  169. package/tests/step-definitions/table.steps.js +81 -6
  170. package/tests/step-definitions/video.steps.js +52 -55
  171. package/tests/step-definitions/wait.steps.js +88 -23
  172. package/tests/step-definitions/web-first.steps.js +69 -35
  173. package/tests/step-definitions/webship.js +741 -145
  174. package/tests/step-definitions/xml.steps.js +49 -15
  175. package/tests/step-definitions/yaml.steps.js +45 -20
@@ -9,7 +9,7 @@
9
9
  // Modal assertions live in modal.steps.js.
10
10
 
11
11
  const { Then } = require('@cucumber/cucumber');
12
- const { buildSelector, getLocatorText, locateByLabelOrSelector, failure, excerpt, isTimeout } = require('./webship');
12
+ const { buildSelector, getLocatorText, locateByLabelOrSelector, failure, excerpt, isTimeout, pageTextLocator } = require('./webship');
13
13
  const { getLastResponse } = require('./response.steps');
14
14
 
15
15
  // ---------------------------------------------------------------------------
@@ -17,29 +17,75 @@ const { getLastResponse } = require('./response.steps');
17
17
  // ---------------------------------------------------------------------------
18
18
 
19
19
  /**
20
- * Assert that text is or is not present on the page.
20
+ * Where a text is on the page, for a failure message: the excerpt of the
21
+ * element that holds it, the element, and whether a visitor can see it.
22
+ *
23
+ * @param {import('playwright').Page} page
24
+ * @param {string} text
25
+ * @returns {Promise<string|undefined>} undefined when it cannot be told.
26
+ */
27
+ async function whereTextIs(page, text) {
28
+ try {
29
+ const match = page.locator('body').getByText(text).first();
30
+ if (!(await match.count())) return undefined;
31
+ const info = await match.evaluate((el) => ({
32
+ tag: el.tagName.toLowerCase(),
33
+ id: el.id || '',
34
+ cls: typeof el.className === 'string' ? el.className.trim().split(/\s+/)[0] : '',
35
+ text: el.textContent || el.value || '',
36
+ }), null, { timeout: 1000 });
37
+ const visible = await match.isVisible().catch(() => true);
38
+ const attr = info.id ? ` id="${info.id}"` : info.cls ? ` class="${info.cls}"` : '';
39
+ return `"${excerpt(info.text, 80)}" in ${visible ? '' : 'a hidden '}<${info.tag}${attr}>`;
40
+ } catch {
41
+ return undefined;
42
+ }
43
+ }
44
+
45
+ /**
46
+ * Assert that a text is, or is not, on the page.
47
+ *
48
+ * Both polarities read the page the same way, as `eventually I should see`
49
+ * does: the text of the page as Playwright's text matching reads it, letter
50
+ * case ignored, runs of white space collapsed, the text of hidden elements
51
+ * included, the text of `<script>` and `<style>` left out. On a page that
52
+ * reads "Next page", `I should see "next page"` passes and `I should not see
53
+ * "next page"` fails. "should see" waits up to 5 seconds for the text to
54
+ * come, "should not see" up to 5 seconds for it to go.
55
+ *
56
+ * For the text a visitor can see, with its letter case, use `I wait for the
57
+ * text "..." to appear` or `... to disappear`; for an element,
58
+ * `"<selector>" should be visible`.
21
59
  *
22
60
  * Example #1: Then I should see "Welcome"
23
61
  * Example #2: Then we should see "Your accounts for the group is public"
24
62
  * Example #3: Then I should not see "Access denied"
25
63
  * Example #4: Then we should not see "Edit layout"
64
+ * Example #5: When I press "Save"
65
+ * Then I should see "Saved"
66
+ * And I should not see "Saving"
26
67
  *
27
68
  */
28
69
  Then(/^(I |we )*should( not)* see "([^"]*)?"$/, async function (pronounCase, notCase, expectedText) {
70
+ const text = expectedText === undefined || expectedText === null ? '' : expectedText;
71
+ const onPage = pageTextLocator(this.page, text);
29
72
  if (notCase) {
30
- const text = await this.page.locator('body').textContent() || '';
31
- if (text.includes(expectedText)) {
32
- throw failure(this.page, `The text "${expectedText}" is on the page, but it should not be.`, {
33
- hint: 'this step reads all the text of the page, the text that is hidden included.',
73
+ try {
74
+ await onPage.waitFor({ state: 'detached', timeout: 5000 });
75
+ } catch (e) {
76
+ if (!isTimeout(e)) throw e;
77
+ throw failure(this.page, `The text "${text}" is on the page, but it should not be.`, {
78
+ found: await whereTextIs(this.page, text),
79
+ hint: `the step ignores letter case and reads all the text of the page, the text of hidden elements included (not the text of <script> or <style>); it waited 5 seconds for the text to go. To check only the text a visitor can see, with its letter case, use: I wait for the text "${text}" to disappear`,
34
80
  });
35
81
  }
36
82
  } else {
37
83
  try {
38
- await this.page.locator('body').filter({ hasText: expectedText }).waitFor({ timeout: 5000 });
84
+ await onPage.waitFor({ state: 'attached', timeout: 5000 });
39
85
  } catch (e) {
40
86
  if (!isTimeout(e)) throw e;
41
- throw failure(this.page, `The text "${expectedText}" was not found on the page after 5 seconds.`, {
42
- hint: `check the spelling and the letter case. The value of a field, an image and the content of an iframe are not page text. For text that arrives late, use: I wait for the text "${expectedText}" to appear`,
87
+ throw failure(this.page, `The text "${text}" was not found on the page after 5 seconds.`, {
88
+ hint: `check the spelling; letter case is ignored and the text of hidden elements counts. The value of a field, an image and the content of an iframe are not page text. For a text that arrives late, use: eventually I should see "${text}" within 30 seconds`,
43
89
  });
44
90
  }
45
91
  }
@@ -51,6 +97,8 @@ Then(/^(I |we )*should( not)* see "([^"]*)?"$/, async function (pronounCase, not
51
97
  * Example #1: Then I should see text matching "^T\w+"
52
98
  * Example #2: Then I should not see text matching "^O\w+"
53
99
  * Example #3: And we should see text matching "\d{4}"
100
+ * Example #4: Then I should see text matching "[0-9]+ items?"
101
+ * Example #5: Then we should not see text matching "Error [0-9]{3}"
54
102
  *
55
103
  */
56
104
  Then(/^(I |we )*should( not)* see text matching "([^"]*)?"$/, async function (pronounCase, notCase, textPattern) {
@@ -118,6 +166,32 @@ Then(/^(I |we )*should( not)* see "([^"]*)?" in( the)* "([^"]*)?" row$/, async f
118
166
  // Element existence + content
119
167
  // ---------------------------------------------------------------------------
120
168
 
169
+ // Tag names a tester may write where a step reads a text.
170
+ const TAG_NAMES = new Set([
171
+ 'a', 'article', 'aside', 'body', 'button', 'dialog', 'div', 'footer', 'form',
172
+ 'h1', 'h2', 'h3', 'h4', 'h5', 'h6', 'header', 'iframe', 'img', 'input',
173
+ 'label', 'li', 'main', 'nav', 'ol', 'p', 'section', 'select', 'span', 'table',
174
+ 'tbody', 'td', 'textarea', 'th', 'thead', 'tr', 'ul', 'video',
175
+ ]);
176
+
177
+ /**
178
+ * True when a step argument reads like a CSS selector rather than a text: it
179
+ * starts with `.`, `#` or `[`, holds selector syntax (`div.card`,
180
+ * `input[name=q]`, `li:first-child`, `ul > li`), is an XPath, or is a bare tag
181
+ * name such as `header`. Used for hints only.
182
+ *
183
+ * @param {string} value
184
+ * @returns {boolean}
185
+ */
186
+ function looksLikeSelector(value) {
187
+ const v = String(value === undefined || value === null ? '' : value).trim();
188
+ if (!v) return false;
189
+ if (/^(?:\/\/|xpath=|css=)/.test(v)) return true;
190
+ const parts = v.split(/\s*[>+~]\s*|\s+/).filter(Boolean);
191
+ const simple = /^(?:[a-z][a-z0-9-]*)?(?:[.#][A-Za-z_-][\w-]*|\[[^\]]+\]|::?[a-z-]+(?:\([^)]*\))?)*$/;
192
+ return parts.every((part) => simple.test(part) && (/[.#[:]/.test(part) || TAG_NAMES.has(part)));
193
+ }
194
+
121
195
  /**
122
196
  * Assert that an element is, or is not, visible on the page. The element is
123
197
  * named by its exact visible text; a `<label for="...">` stands for the
@@ -127,6 +201,10 @@ Then(/^(I |we )*should( not)* see "([^"]*)?" in( the)* "([^"]*)?" row$/, async f
127
201
  * "should not see" is the opposite of "should see": it passes when no element
128
202
  * named that way is visible, so an element that is hidden does not fail it.
129
203
  *
204
+ * An argument that looks like a selector (`.news-item`, `#main`, `header`) is
205
+ * still read as a text: a failure says so, and the negative prints a warning
206
+ * when it passes while that selector matches a visible element.
207
+ *
130
208
  * Example #1: Then I should see a "Username" element
131
209
  * Example #2: Then I should not see a "Username" element
132
210
  * Example #3: And we should see an "Email" element
@@ -149,8 +227,13 @@ Then(/^(I |we )*should( not)* see (a|an) "([^"]*)?" element$/, async function (p
149
227
  });
150
228
  }
151
229
  }
230
+ if (looksLikeSelector(element) && await this.page.locator(element).first().isVisible().catch(() => false)) {
231
+ console.warn(`\x1b[33m[webship-js] I should not see a "${element}" element: passed, because no element reads "${element}". It looks like a CSS selector, and that selector matches a visible element; this step reads a text. For a selector, use: "${element}" should not be visible\x1b[0m`);
232
+ }
152
233
  } else {
153
- const hint = `this step finds an element by its exact visible text or by its label. To find it by its id, class, name or another attribute, use: I should see a "${element}" element by attr`;
234
+ const hint = looksLikeSelector(element)
235
+ ? `"${element}" looks like a CSS selector, but this step reads it as the exact text of an element or of a label. For a selector, use: "${element}" should be visible`
236
+ : `this step finds an element by its exact visible text or by its label. To find it by its id, class, name or another attribute, use: I should see a "${element}" element by attr`;
154
237
  const loc = this.page.getByText(element, { exact: true }).first();
155
238
  try {
156
239
  await loc.waitFor({ state: 'attached', timeout: 3000 });
@@ -181,6 +264,7 @@ Then(/^(I |we )*should( not)* see (a|an) "([^"]*)?" element$/, async function (p
181
264
  * Example #2: Then I should see a "pwordcss" element by attr
182
265
  * Example #3: Then I should not see an "emailId" element by its "id" attr
183
266
  * Example #4: And I should not see a "countryCss" element by attr
267
+ * Example #5: Then we should see a "search-box" element by its "data-testid" attribute
184
268
  *
185
269
  */
186
270
  Then(/^(I |we )*should( not)* see (a|an) "([^"]*)?" element by( its)*(?: "([^"]*)?")* (attribute|attr)$/, async function (pronounCase, notCase, aAnCase, attrValue, itsCase, attr, attrWord) {
@@ -252,6 +336,7 @@ Then(/^(I |we )*should( not)* see "([^"]*)?" in( the)* "([^"]*)?" element$/, asy
252
336
  * Example #2: Then I should see "1234" in the "pwordcss" element by attr
253
337
  * Example #3: Then I should not see "John Smith" in the "uname" element by its "id" attr
254
338
  * Example #4: Then I should not see "1234" in the "pwordcss" element by attr
339
+ * Example #5: Then we should see "Welcome" in the "greeting" element by its "class" attribute
255
340
  *
256
341
  */
257
342
  Then(/^(I |we )*should( not)* see "([^"]*)?" in( the)* "([^"]*)?" element by( its)*(?: "([^"]*)?")* (attribute|attr)$/, async function (pronounCase, notCase, expectedText, theCase, attrValue, itsCase, attr, attrWord) {
@@ -329,6 +414,7 @@ Then(/^(I |we )*should( not)* see text matching "([^"]*)?" in( the)* "([^"]*)?"
329
414
  * Example #2: Then the "body" element should not contain "color:white;"
330
415
  * Example #3: Then the "#uname" element should not contain "border:solid 5px red;"
331
416
  * Example #4: Then the "pword" element should not contain "font-size: 26px;"
417
+ * Example #5: Then the "h1" element should contain "font-weight: 700"
332
418
  *
333
419
  */
334
420
  Then(/^(the )*"([^"]*)?" element should( not)* contain "([^"]*)?"$/, async function (theCase, selectorRaw, notCase, elementCss) {
@@ -423,6 +509,8 @@ Then(/^(I |we )*should see (\d+) "([^"]*)" elements?$/, async function (pronounC
423
509
  * Example #1: Then the "Login" link should contain "/log-in"
424
510
  * Example #2: And the "About Us" link should contain "/about"
425
511
  * Example #3: Then "Home" link should contain "/"
512
+ * Example #4: Then the "Contact Us" link should contain "/contact"
513
+ * Example #5: And "Privacy policy" link should contain "privacy"
426
514
  *
427
515
  */
428
516
  Then(/^(the )*"([^"]*)?" link should contain "([^"]*)?"$/, async function (theCase, element, url) {
@@ -450,6 +538,8 @@ Then(/^(the )*"([^"]*)?" link should contain "([^"]*)?"$/, async function (theCa
450
538
  * Example #1: Then the "#about-us-id" link should contain "about" by attr
451
539
  * Example #2: And the "aboutUs" link should contain "about" by its "class" attribute
452
540
  * Example #3: And the ".contactUs" link should contain "/contact-" by attr
541
+ * Example #4: Then the "nav-home" link should contain "/" by its "id" attribute
542
+ * Example #5: And the "footer-link" link should contain "https://" by attr
453
543
  *
454
544
  */
455
545
  Then(/^(the )*"([^"]*)?" link should contain "([^"]*)?" by( its)*(?: "([^"]*)?")* (attribute|attr)$/, async function (theCase, attrValue, url, itsCase, attr, attrWord) {
@@ -57,9 +57,12 @@ When(/^(I |we )*save the auth state to "([^"]*)"$/, async function (pronoun, tar
57
57
  * Restore cookies + localStorage from a previously saved JSON file.
58
58
  *
59
59
  * The current browser context is closed and a fresh one is opened with the
60
- * saved state. The webship-js init script (AJAX/timer/mutation tracker) is
61
- * re-installed automatically so smart waits keep working. Subsequent steps
62
- * proceed against the restored, authenticated session.
60
+ * saved state, through the same path as the first one of the scenario: the
61
+ * smart waits (the AJAX / timer / mutation tracker), the viewport of an
62
+ * @mobile / @desktop tag, video recording while it is on, JavaScript-error
63
+ * capture, the response tracker and a running request log all go on with
64
+ * the new page. The page starts blank: open the page you need next. Routes
65
+ * stubbed before this step belong to the closed context: stub them after it.
63
66
  *
64
67
  * Example #1: Given I restore the auth state from "tests/auth/admin.json"
65
68
  * Example #2: Given I restore the auth state from "tests/auth/editor.json"
@@ -77,21 +80,15 @@ Given(/^(I |we )*restore the auth state from "([^"]*)"$/, async function (pronou
77
80
  if (!fs.existsSync(file)) {
78
81
  throw friendly(`Auth state file not found: ${file}`);
79
82
  }
80
- const playwrightConfig = require(path.join(process.cwd(), 'playwright.config'));
81
- const newContext = await this.playwrightBrowser.newContext({
82
- ...playwrightConfig.contextOptions,
83
- storageState: file,
84
- });
85
- await newContext.addInitScript(() => {
86
- if (window.__webshipAjaxInstalled) return;
87
- window.__webshipAjaxInstalled = true;
88
- window.__webshipAjaxCount = 0;
89
- window.__webshipPendingTimers = 0;
90
- window.__webshipLastMutation = Date.now();
91
- });
92
- if (this.context) await this.context.close();
93
- this.context = newContext;
94
- this.page = await this.context.newPage();
83
+ try {
84
+ await this.replaceContext({ storageState: file });
85
+ } catch (e) {
86
+ throw friendly({
87
+ action: `restore the auth state from "${source}"`,
88
+ cause: e,
89
+ hint: 'the file must be one written by "I save the auth state to", and the browser must still be open.',
90
+ });
91
+ }
95
92
  });
96
93
 
97
94
  /**
@@ -8,6 +8,22 @@ const { Given, When } = require('@cucumber/cucumber');
8
8
 
9
9
  const ISO_HINT = 'install the fake clock first via "Given the system time is \\"YYYY-MM-DDTHH:MM:SSZ\\"".';
10
10
 
11
+ /**
12
+ * Playwright installs a fake clock on the first clock call when none is
13
+ * installed, at the current time; the timers the page set before that call
14
+ * keep running on real time. Say so once per scenario when a step moves a
15
+ * clock that "Given the system time is" did not install.
16
+ */
17
+ async function noteClockInstalledNow(world, what) {
18
+ let installed = true;
19
+ try { installed = await world.page.evaluate(() => !!(window.Date && window.Date.isFake)); } catch { /* no page yet */ }
20
+ if (installed || world.__clockNoteShown) return;
21
+ world.__clockNoteShown = true;
22
+ const note = `[webship-js] The clock was not installed with "Given the system time is …": "${what}" installed a fake clock now, at the current time. Timers the page set before this step run on real time and do not move with it.`;
23
+ process.stderr.write(`\n${note}\n`);
24
+ try { await world.attach(note, 'text/plain'); } catch { /* attach is optional */ }
25
+ }
26
+
11
27
  /**
12
28
  * Install a fake clock anchored at an ISO 8601 instant.
13
29
  *
@@ -41,6 +57,7 @@ Given(/^the system time is "([^"]*)"$/, async function (iso) {
41
57
  *
42
58
  */
43
59
  When(/^(I |we )*advance the clock by (\d+) ?ms$/, async function (pronoun, ms) {
60
+ await noteClockInstalledNow(this, `advance the clock by ${ms} ms`);
44
61
  try { await this.page.clock.runFor(parseInt(ms, 10)); }
45
62
  catch (e) { throw friendly({ action: `advance the clock by ${ms} ms`, cause: e, hint: ISO_HINT }); }
46
63
  });
@@ -56,6 +73,7 @@ When(/^(I |we )*advance the clock by (\d+) ?ms$/, async function (pronoun, ms) {
56
73
  *
57
74
  */
58
75
  When(/^(I |we )*advance the clock by (\d+) seconds?$/, async function (pronoun, seconds) {
76
+ await noteClockInstalledNow(this, `advance the clock by ${seconds} second(s)`);
59
77
  try { await this.page.clock.runFor(parseInt(seconds, 10) * 1000); }
60
78
  catch (e) { throw friendly({ action: `advance the clock by ${seconds} second(s)`, cause: e, hint: ISO_HINT }); }
61
79
  });
@@ -71,6 +89,7 @@ When(/^(I |we )*advance the clock by (\d+) seconds?$/, async function (pronoun,
71
89
  *
72
90
  */
73
91
  When(/^(I |we )*advance the clock by (\d+) minutes?$/, async function (pronoun, minutes) {
92
+ await noteClockInstalledNow(this, `advance the clock by ${minutes} minute(s)`);
74
93
  try { await this.page.clock.runFor(parseInt(minutes, 10) * 60 * 1000); }
75
94
  catch (e) { throw friendly({ action: `advance the clock by ${minutes} minute(s)`, cause: e, hint: ISO_HINT }); }
76
95
  });
@@ -86,6 +105,7 @@ When(/^(I |we )*advance the clock by (\d+) minutes?$/, async function (pronoun,
86
105
  *
87
106
  */
88
107
  When(/^(I |we )*pause the clock$/, async function (pronoun) {
108
+ await noteClockInstalledNow(this, 'pause the clock');
89
109
  try { await this.page.clock.pauseAt(await this.page.evaluate(() => Date.now())); }
90
110
  catch (e) { throw friendly({ action: 'pause the clock', cause: e, hint: ISO_HINT }); }
91
111
  });
@@ -101,6 +121,7 @@ When(/^(I |we )*pause the clock$/, async function (pronoun) {
101
121
  *
102
122
  */
103
123
  When(/^(I |we )*resume the clock$/, async function (pronoun) {
124
+ await noteClockInstalledNow(this, 'resume the clock');
104
125
  try { await this.page.clock.resume(); }
105
126
  catch (e) { throw friendly({ action: 'resume the clock', cause: e, hint: 'pause the clock first via "When I pause the clock".' }); }
106
127
  });
@@ -123,6 +144,7 @@ When(/^(I |we )*set the system time to "([^"]*)"$/, async function (pronoun, iso
123
144
  hint: 'use an ISO 8601 date like "2026-05-08T12:30:00Z".',
124
145
  });
125
146
  }
147
+ await noteClockInstalledNow(this, `set the system time to "${iso}"`);
126
148
  try { await this.page.clock.setSystemTime(d); }
127
149
  catch (e) { throw friendly({ action: `set the system time to "${iso}"`, cause: e, hint: ISO_HINT }); }
128
150
  });
@@ -11,6 +11,10 @@ const { Then } = require('@cucumber/cucumber');
11
11
  * Example #1: Then print current URL
12
12
  * Example #2: When print current URL
13
13
  * Example #3: And print current URL
14
+ * Example #4: Given I am on "/about-us.html"
15
+ * Then print current URL
16
+ * Example #5: When I press "Search"
17
+ * Then print current URL
14
18
  */
15
19
  Then(/^print current URL$/, function () {
16
20
  try {
@@ -27,6 +31,10 @@ Then(/^print current URL$/, function () {
27
31
  * Example #1: Then print last response
28
32
  * Example #2: When print last response
29
33
  * Example #3: And print last response
34
+ * Example #4: Given I am on "/about-us.html"
35
+ * Then print last response
36
+ * Example #5: When I follow "Contact"
37
+ * Then print last response
30
38
  */
31
39
  Then(/^print last response$/, async function () {
32
40
  try {
@@ -9,6 +9,13 @@
9
9
 
10
10
  const { Given, Then } = require('@cucumber/cucumber');
11
11
  const assert = require('assert');
12
+ const { onNewPage } = require('./webship');
13
+
14
+ // A handler waiting for a dialog goes over to the page of a browser context
15
+ // that a step replaces (restoring an auth state, a video recording).
16
+ onNewPage((world, page) => {
17
+ if (world._dialogHandler) page.on('dialog', world._dialogHandler);
18
+ });
12
19
 
13
20
  // Single shared attach() — handles single-shot ("next") and persistent
14
21
  // ("all") variants via the `once` flag.
@@ -1,12 +1,18 @@
1
1
  'use strict';
2
2
 
3
- const { friendly } = require('./webship');
3
+ const { friendly, failure, registeredNameHint } = require('./webship');
4
4
 
5
5
  // Element interactions and visual / positional assertions using Playwright.
6
6
 
7
7
  const { Given, When, Then } = require('@cucumber/cucumber');
8
8
  const assert = require('assert');
9
9
 
10
+ // The hint for an element step given a name of the selector registry: the same
11
+ // step with the selector the name stands for.
12
+ function elementRegistryHint(world, sel, step) {
13
+ return registeredNameHint(world, sel, { withSelector: (selector) => step.replace('{selector}', selector) });
14
+ }
15
+
10
16
  /**
11
17
  * Assert element A is positioned vertically below element B (greater Y).
12
18
  *
@@ -27,7 +33,69 @@ Then('the element {string} should appear after the element {string}', async func
27
33
  });
28
34
 
29
35
  /**
30
- * Assert text A appears after text B in the document body's text order.
36
+ * A short excerpt of `text` around the place `index`, for a failure message.
37
+ *
38
+ * @param {string} text
39
+ * @param {number} index
40
+ * @param {number} length
41
+ * @returns {string}
42
+ */
43
+ function around(text, index, length) {
44
+ const start = Math.max(0, index - 30);
45
+ const end = Math.min(text.length, index + length + 30);
46
+ return `${start > 0 ? '…' : ''}${text.slice(start, end).replace(/\s+/g, ' ').trim()}${end < text.length ? '…' : ''}`;
47
+ }
48
+
49
+ /**
50
+ * Check that the first place `after` appears comes later than the first place
51
+ * `before` appears, in the visible text of the page or of one element.
52
+ *
53
+ * @param {Object} world
54
+ * @param {string} after
55
+ * @param {string} before
56
+ * @param {string} [scope] - CSS selector of the element to read; the page when absent.
57
+ */
58
+ async function assertTextAfter(world, after, before, scope) {
59
+ let text;
60
+ if (scope) {
61
+ const element = world.page.locator(scope).first();
62
+ try {
63
+ await element.waitFor({ state: 'attached', timeout: 5000 });
64
+ } catch {
65
+ throw failure(world.page, `No element matches "${scope}" after 5 seconds.`, {
66
+ hint: 'the last argument is a CSS selector of the element whose text is read, such as "nav.breadcrumb".',
67
+ });
68
+ }
69
+ text = await element.innerText();
70
+ } else {
71
+ text = await world.page.locator('body').innerText();
72
+ }
73
+ const where = scope ? `in the element "${scope}"` : 'on the page';
74
+ const scopedForm = `the text "${after}" should appear after the text "${before}" in the "<selector>" element`;
75
+ const iAfter = text.indexOf(after);
76
+ const iBefore = text.indexOf(before);
77
+ if (iAfter === -1 || iBefore === -1) {
78
+ const missing = [iAfter === -1 ? after : null, iBefore === -1 ? before : null].filter((t) => t !== null);
79
+ throw failure(world.page, `The text ${missing.map((t) => `"${t}"`).join(' and the text ')} ${missing.length > 1 ? 'are' : 'is'} not ${where}.`, {
80
+ hint: 'the step reads the visible text, with its letter case.',
81
+ });
82
+ }
83
+ if (iAfter <= iBefore) {
84
+ throw failure(world.page, `The text "${after}" does not appear after the text "${before}" ${where}.`, {
85
+ found: `"${after}" first at "${around(text, iAfter, after.length)}"; "${before}" first at "${around(text, iBefore, before.length)}"`,
86
+ hint: scope
87
+ ? 'the step compares the first place each text appears in the visible text of the element, with its letter case.'
88
+ : `the step compares the first place each text appears in the visible text of the whole page, with its letter case, so a menu or a header can decide it. To compare them inside one part of the page, use: ${scopedForm}`,
89
+ });
90
+ }
91
+ }
92
+
93
+ /**
94
+ * Assert text A appears after text B in the visible text of the page.
95
+ *
96
+ * The first place each text appears on the whole page is compared, so a text
97
+ * that a menu or a header also holds is found there first. To compare two
98
+ * texts inside one part of the page, add `in the "<selector>" element`.
31
99
  *
32
100
  * Example #1: Then the text "Sign in" should appear after the text "Welcome"
33
101
  * Example #2: Then the text "Total" should appear after the text "Subtotal"
@@ -37,12 +105,22 @@ Then('the element {string} should appear after the element {string}', async func
37
105
  *
38
106
  */
39
107
  Then('the text {string} should appear after the text {string}', async function (t1, t2) {
40
- const body = await this.page.locator('body').innerText();
41
- const i1 = body.indexOf(t1);
42
- const i2 = body.indexOf(t2);
43
- assert.ok(i1 !== -1, `Text "${t1}" not found.`);
44
- assert.ok(i2 !== -1, `Text "${t2}" not found.`);
45
- assert.ok(i1 > i2, `Text "${t1}" should appear after "${t2}".`);
108
+ await assertTextAfter(this, t1, t2);
109
+ });
110
+
111
+ /**
112
+ * Assert text A appears after text B inside one element: the first place each
113
+ * text appears in the visible text of the first element the selector matches.
114
+ *
115
+ * Example #1: Then the text "Products" should appear after the text "Home" in the "nav.breadcrumb" element
116
+ * Example #2: Then the text "Total" should appear after the text "Subtotal" in the "#cart" element
117
+ * Example #3: And the text "Step 3" should appear after the text "Step 2" in the ".wizard" element
118
+ * Example #4: Then the text "Privacy" should appear after the text "Terms" in the "footer" element
119
+ * Example #5: Then the text "Reply" should appear after the text "Comment" in the "article" element
120
+ *
121
+ */
122
+ Then('the text {string} should appear after the text {string} in the {string} element', async function (t1, t2, scope) {
123
+ await assertTextAfter(this, t1, t2, scope);
46
124
  });
47
125
 
48
126
  /**
@@ -106,7 +184,10 @@ Then('the element {string} with the attribute {string} and the value containing
106
184
  });
107
185
 
108
186
  /**
109
- * Assert an element is positioned within the top 100 px of the viewport.
187
+ * Assert an element is at the top of the viewport: the top of its box is
188
+ * between 0 and 100 pixels from the top of the viewport. The step looks
189
+ * again for up to 5 seconds, so an element still on its way after a smooth
190
+ * scroll gets there.
110
191
  *
111
192
  * Example #1: Then the element "#header" should be at the top of the viewport
112
193
  * Example #2: Then the element "h1" should be at the top of the viewport
@@ -114,12 +195,46 @@ Then('the element {string} with the attribute {string} and the value containing
114
195
  * Example #4: When I scroll to the top
115
196
  * Then the element "#hero" should be at the top of the viewport
116
197
  * Example #5: Then the element "[role=banner]" should be at the top of the viewport
198
+ * Example #6: When I click "Go to section 3"
199
+ * Then the element "#section-3" should be at the top of the viewport
117
200
  *
118
201
  */
119
202
  Then('the element {string} should be at the top of the viewport', async function (sel) {
120
- const box = await this.page.locator(sel).first().boundingBox();
121
- assert.ok(box, `Element "${sel}" not found or not visible.`);
122
- assert.ok(box.y >= 0 && box.y <= 100, `Element "${sel}" is not at top of viewport (y=${box.y}).`);
203
+ const element = this.page.locator(sel).first();
204
+ const deadline = Date.now() + 5000;
205
+ let state = 'missing';
206
+ let top = null;
207
+ for (;;) {
208
+ if (await element.count().catch(() => 0)) {
209
+ const box = await element.boundingBox().catch(() => null);
210
+ if (box) {
211
+ top = box.y;
212
+ state = 'placed';
213
+ if (top >= 0 && top <= 100) return;
214
+ } else {
215
+ state = 'hidden';
216
+ }
217
+ } else {
218
+ state = 'missing';
219
+ }
220
+ if (Date.now() >= deadline) break;
221
+ await this.page.waitForTimeout(100);
222
+ }
223
+ if (state === 'missing') {
224
+ throw failure(this.page, `No element matches "${sel}" after 5 seconds.`, {
225
+ hint: elementRegistryHint(this, sel, 'the element "{selector}" should be at the top of the viewport') ||
226
+ 'the argument is a CSS selector, such as "#hero" or "header.site-header".',
227
+ });
228
+ }
229
+ if (state === 'hidden') {
230
+ throw failure(this.page, `The element "${sel}" is on the page but not visible after 5 seconds.`, {
231
+ hint: 'a hidden element has no place in the viewport.',
232
+ });
233
+ }
234
+ throw failure(this.page, `The element "${sel}" is not at the top of the viewport after 5 seconds.`, {
235
+ found: `its top is ${Math.round(top)} px from the top of the viewport`,
236
+ hint: `the step passes when the top of the element is between 0 and 100 pixels from the top of the viewport. To bring it there, use: When I scroll to the element "${sel}"`,
237
+ });
123
238
  });
124
239
 
125
240
  /**
@@ -163,7 +278,7 @@ When(/^(I |we )*click on the element "([^"]*)"$/, async function (pronoun, sel)
163
278
  throw friendly({
164
279
  action: `click on the element "${sel}"`,
165
280
  cause: e,
166
- hint: `check that the element exists on the page, is visible, and is clickable.`,
281
+ hint: elementRegistryHint(this, sel, 'I click on the element "{selector}"') || `check that the element exists on the page, is visible, and is clickable.`,
167
282
  });
168
283
  }
169
284
  });
@@ -188,7 +303,7 @@ When(/^(I |we )*trigger the JS event "([^"]*)" on the element "([^"]*)"$/, async
188
303
  throw friendly({
189
304
  action: `trigger the "${event}" event on "${sel}"`,
190
305
  cause: e,
191
- hint: `use a standard event name like click, change, input, focus, or blur.`,
306
+ hint: elementRegistryHint(this, sel, `I trigger the JS event "${event}" on the element "{selector}"`) || `use a standard event name like click, change, input, focus, or blur.`,
192
307
  });
193
308
  }
194
309
  });
@@ -210,7 +325,7 @@ When(/^(I |we )*scroll to the element "([^"]*)"$/, async function (pronoun, sel)
210
325
  throw friendly({
211
326
  action: `scroll to "${sel}"`,
212
327
  cause: e,
213
- hint: `check the element exists on the page and was not removed before scrolling.`,
328
+ hint: elementRegistryHint(this, sel, 'I scroll to the element "{selector}"') || `check the element exists on the page and was not removed before scrolling.`,
214
329
  });
215
330
  }
216
331
  });
@@ -232,7 +347,7 @@ When(/^(I |we )*hover over the element "([^"]*)"$/, async function (pronoun, sel
232
347
  throw friendly({
233
348
  action: `hover over "${sel}"`,
234
349
  cause: e,
235
- hint: `check the element exists, is visible, and is not covered by another element.`,
350
+ hint: elementRegistryHint(this, sel, 'I hover over the element "{selector}"') || `check the element exists, is visible, and is not covered by another element.`,
236
351
  });
237
352
  }
238
353
  });
@@ -254,7 +369,7 @@ When(/^(I |we )*focus on the element "([^"]*)"$/, async function (pronoun, sel)
254
369
  throw friendly({
255
370
  action: `focus on "${sel}"`,
256
371
  cause: e,
257
- hint: `the element must be focusable — an input, button, link, or have a tabindex.`,
372
+ hint: elementRegistryHint(this, sel, 'I focus on the element "{selector}"') || `the element must be focusable — an input, button, link, or have a tabindex.`,
258
373
  });
259
374
  }
260
375
  });