webship-js 2.0.11 → 2.0.12

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 (168) hide show
  1. package/.circleci/config.yml +10 -1
  2. package/.drone.yml +7 -7
  3. package/.github/workflows/github-actions.yml +45 -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 +44 -8
  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/choice-controls.html +29 -0
  45. package/examples/datetime-fields.html +52 -0
  46. package/examples/element-selector-hint.html +16 -0
  47. package/examples/field-states.html +27 -0
  48. package/examples/fill-in-empty.html +26 -0
  49. package/examples/fill-unreachable.html +27 -0
  50. package/examples/iframe-inner.html +20 -0
  51. package/examples/iframe-nested.html +16 -0
  52. package/examples/iframe-outer.html +15 -0
  53. package/examples/multi-value-fields.html +54 -0
  54. package/examples/registered-names.html +15 -0
  55. package/examples/select-by-label.html +33 -0
  56. package/examples/settle-budget.html +21 -0
  57. package/examples/sorted-tables.html +38 -0
  58. package/examples/text-matching.html +48 -0
  59. package/examples/text-order.html +25 -0
  60. package/examples/touch.html +22 -0
  61. package/examples/viewport-top.html +36 -0
  62. package/package.json +16 -1
  63. package/playwright.config.ts +3 -1
  64. package/tests/check-api-launch-url.js +106 -0
  65. package/tests/check-assets.js +103 -0
  66. package/tests/check-attachments.js +105 -0
  67. package/tests/check-breakpoints.js +117 -0
  68. package/tests/check-clock.js +143 -0
  69. package/tests/check-config.js +90 -0
  70. package/tests/check-context.js +215 -0
  71. package/tests/check-dry-run.js +104 -0
  72. package/tests/check-examples.js +10 -4
  73. package/tests/check-exit-report.js +141 -0
  74. package/tests/check-javascript-errors.js +105 -0
  75. package/tests/check-must-fail.js +5 -4
  76. package/tests/check-scaffold.js +36 -1
  77. package/tests/check-screenshots.js +117 -0
  78. package/tests/check-settle-verbs.js +137 -0
  79. package/tests/check-time-limit.js +104 -0
  80. package/tests/check-video.js +156 -0
  81. package/tests/check-world.js +167 -0
  82. package/tests/features/api-base-url.feature +25 -0
  83. package/tests/features/api-form-data.feature +18 -0
  84. package/tests/features/api-json-paths.feature +24 -0
  85. package/tests/features/api-response-contains.feature +21 -0
  86. package/tests/features/api-response-header-presence.feature +17 -0
  87. package/tests/features/api-response-header.feature +17 -0
  88. package/tests/features/api-saved-placeholders.feature +37 -0
  89. package/tests/features/api-step-definitions-individual.feature +1 -1
  90. package/tests/features/api-tables.feature +40 -0
  91. package/tests/features/breakpoints.feature +25 -0
  92. package/tests/features/choice-controls.feature +35 -0
  93. package/tests/features/complete-api-testing-examples.feature +1 -1
  94. package/tests/features/datetime-field-lookup.feature +29 -0
  95. package/tests/features/element-selector-hint.feature +14 -0
  96. package/tests/features/field-state.feature +21 -0
  97. package/tests/features/fill-in-empty-value.feature +41 -0
  98. package/tests/features/fill-reachable.feature +13 -0
  99. package/tests/features/iframe-nested.feature +43 -0
  100. package/tests/features/javascript-tolerated-errors.feature +20 -0
  101. package/tests/features/modal-open.feature +13 -0
  102. package/tests/features/multi-value-field-lookup.feature +30 -0
  103. package/tests/features/registered-names.feature +14 -0
  104. package/tests/features/select-by-label.feature +31 -0
  105. package/tests/features/selector-files.feature +14 -0
  106. package/tests/features/selectors-table-header.feature +35 -0
  107. package/tests/features/settle-budget.feature +11 -0
  108. package/tests/features/sorted-tables.feature +19 -0
  109. package/tests/features/storage-quoted-values.feature +26 -0
  110. package/tests/features/text-matching.feature +38 -0
  111. package/tests/features/text-order.feature +14 -0
  112. package/tests/features/touch.feature +21 -0
  113. package/tests/features/viewport-top.feature +13 -0
  114. package/tests/features/xml-namespaces.feature +34 -0
  115. package/tests/must-fail/api-json-paths.feature +21 -0
  116. package/tests/must-fail/api-response-contains.feature +23 -0
  117. package/tests/must-fail/api-response-header-presence.feature +17 -0
  118. package/tests/must-fail/api-response-header.feature +21 -0
  119. package/tests/must-fail/api-without-base-url.feature +11 -0
  120. package/tests/must-fail/breakpoints.feature +15 -0
  121. package/tests/must-fail/choice-controls.feature +25 -0
  122. package/tests/must-fail/clock.feature +11 -0
  123. package/tests/must-fail/datetime-field.feature +10 -0
  124. package/tests/must-fail/element-selector-hint.feature +17 -0
  125. package/tests/must-fail/field-state.feature +20 -0
  126. package/tests/must-fail/fill-field.feature +30 -0
  127. package/tests/must-fail/iframe-text.feature +17 -0
  128. package/tests/must-fail/modal-open.feature +26 -0
  129. package/tests/must-fail/multi-value-field.feature +18 -0
  130. package/tests/must-fail/registered-names.feature +25 -0
  131. package/tests/must-fail/select-list.feature +15 -0
  132. package/tests/must-fail/selector-files.feature +10 -0
  133. package/tests/must-fail/sorted-tables.feature +20 -0
  134. package/tests/must-fail/storage-before-a-page.feature +13 -0
  135. package/tests/must-fail/text-matching.feature +16 -0
  136. package/tests/must-fail/text-order.feature +15 -0
  137. package/tests/must-fail/viewport-top.feature +20 -0
  138. package/tests/must-fail/yaml-numbers.feature +48 -0
  139. package/tests/step-definitions/a11y.steps.js +24 -15
  140. package/tests/step-definitions/action.steps.js +22 -8
  141. package/tests/step-definitions/api.steps.js +349 -67
  142. package/tests/step-definitions/assertion.steps.js +100 -10
  143. package/tests/step-definitions/auth.steps.js +15 -18
  144. package/tests/step-definitions/clock.steps.js +22 -0
  145. package/tests/step-definitions/debug.steps.js +8 -0
  146. package/tests/step-definitions/dialog.steps.js +7 -0
  147. package/tests/step-definitions/element.steps.js +132 -17
  148. package/tests/step-definitions/field.steps.js +409 -96
  149. package/tests/step-definitions/form.steps.js +76 -29
  150. package/tests/step-definitions/iframe.steps.js +89 -29
  151. package/tests/step-definitions/input.steps.js +26 -7
  152. package/tests/step-definitions/javascript.steps.js +64 -22
  153. package/tests/step-definitions/modal.steps.js +79 -13
  154. package/tests/step-definitions/navigation.steps.js +14 -0
  155. package/tests/step-definitions/network.steps.js +15 -5
  156. package/tests/step-definitions/response.steps.js +6 -4
  157. package/tests/step-definitions/responsive.steps.js +26 -33
  158. package/tests/step-definitions/screenshot.steps.js +25 -8
  159. package/tests/step-definitions/scroll.steps.js +20 -0
  160. package/tests/step-definitions/selectors.steps.js +95 -48
  161. package/tests/step-definitions/storage.steps.js +38 -13
  162. package/tests/step-definitions/table.steps.js +81 -6
  163. package/tests/step-definitions/video.steps.js +52 -55
  164. package/tests/step-definitions/wait.steps.js +88 -23
  165. package/tests/step-definitions/web-first.steps.js +69 -35
  166. package/tests/step-definitions/webship.js +681 -143
  167. package/tests/step-definitions/xml.steps.js +49 -15
  168. package/tests/step-definitions/yaml.steps.js +45 -20
@@ -2,7 +2,9 @@
2
2
 
3
3
  // Auto-detect JavaScript errors during test execution.
4
4
  //
5
- // Listeners are attached on Before (order 200) once a page is open:
5
+ // Listeners are attached to every page the World opens (onNewPage of
6
+ // webship.js), so a step that replaces the browser context — restoring an
7
+ // auth state, starting or stopping a video recording — keeps the capture:
6
8
  // page.on('pageerror') → uncaught errors
7
9
  // page.on('console', level) → console messages (filtered by config)
8
10
  //
@@ -21,6 +23,7 @@
21
23
 
22
24
  const { Before, After, Then } = require('@cucumber/cucumber');
23
25
  const assert = require('assert');
26
+ const { onNewPage } = require('./webship');
24
27
 
25
28
  const VALID_MODES = new Set(['warn', 'fail', 'off']);
26
29
  const DEFAULT_CONSOLE_LEVELS = ['error'];
@@ -83,6 +86,19 @@ function filterErrors(errs, ignore) {
83
86
  return errs.filter((e) => !ignore.test(e.message));
84
87
  }
85
88
 
89
+ // The kind of a collected entry: "error" for an uncaught error or a
90
+ // console.error, else the console level it was logged at ("warning", ...).
91
+ function kindOf(entry) {
92
+ return entry.type === 'pageerror' || entry.type === 'console.error' ? 'error' : String(entry.type).replace(/^console\./, '');
93
+ }
94
+
95
+ // A check handles the kind of entries it read: the end-of-scenario report
96
+ // leaves those out and still reports the others.
97
+ function markHandled(world, kind) {
98
+ if (!world._jsHandledKinds) world._jsHandledKinds = new Set();
99
+ world._jsHandledKinds.add(kind);
100
+ }
101
+
86
102
  function reportWarning(scope, errs) {
87
103
  const name = (scope && scope.pickle && scope.pickle.name) || 'scenario';
88
104
  // Yellow ANSI when FORCE_COLOR is on, plain otherwise — let the runtime
@@ -95,22 +111,39 @@ function reportWarning(scope, errs) {
95
111
  // Before — attach listeners + (optional) pre-snapshot.
96
112
  // ---------------------------------------------------------------------------
97
113
 
98
- Before({ order: 200 }, function (scope) {
114
+ /**
115
+ * Collect the uncaught errors and the console messages of the captured
116
+ * levels of a page into the World's list.
117
+ */
118
+ function captureErrors(world, page) {
119
+ const settings = world._jsSettings;
120
+ if (!page || !settings || settings.mode === 'off') return;
121
+ const levels = new Set(settings.levels);
122
+ page.on('pageerror', (err) => {
123
+ world._jsErrors.push({ type: 'pageerror', message: String(err && err.message || err) });
124
+ });
125
+ page.on('console', (msg) => {
126
+ if (levels.has(msg.type())) {
127
+ world._jsErrors.push({ type: `console.${msg.type()}`, message: msg.text() });
128
+ }
129
+ });
130
+ }
131
+
132
+ // A page opened by a step in a new browser context (the first page of the
133
+ // scenario is set up by the Before hook below, which runs after webship.js
134
+ // opened it).
135
+ onNewPage((world, page) => {
136
+ if (world._jsSettings) captureErrors(world, page);
137
+ });
138
+
139
+ Before(function (scope) {
99
140
  this._jsErrors = [];
100
141
  this._jsErrorsAsserted = false;
101
142
  this._jsSettings = resolveSettings(this, scope);
102
143
  if (this._jsSettings.mode === 'off') return;
103
144
  if (!this.page) return;
104
145
 
105
- const levels = new Set(this._jsSettings.levels);
106
- this.page.on('pageerror', (err) => {
107
- this._jsErrors.push({ type: 'pageerror', message: String(err && err.message || err) });
108
- });
109
- this.page.on('console', (msg) => {
110
- if (levels.has(msg.type())) {
111
- this._jsErrors.push({ type: `console.${msg.type()}`, message: msg.text() });
112
- }
113
- });
146
+ captureErrors(this, this.page);
114
147
 
115
148
  if (this._jsSettings.beforeScenario) {
116
149
  // Pre-scenario snapshot — typically empty unless the same page is reused.
@@ -128,11 +161,14 @@ Before({ order: 200 }, function (scope) {
128
161
  // ---------------------------------------------------------------------------
129
162
 
130
163
  /**
131
- * Assert that no JavaScript errors have been collected so far.
164
+ * Assert that no JavaScript errors have been collected so far: uncaught
165
+ * errors and console.error. A console warning is not an error, even when
166
+ * warnings are captured.
132
167
  *
133
168
  * Always fails on error (ignoring the active mode) — this is the explicit
134
- * "hard check" step. Calling it also prevents the auto-report at scenario
135
- * end so a single error is not reported twice.
169
+ * "hard check" step. Calling it also leaves the errors out of the
170
+ * auto-report at scenario end, so a single error is not reported twice;
171
+ * captured warnings are still reported there.
136
172
  *
137
173
  * Example #1: Then there should be no JavaScript errors
138
174
  * Example #2: And there should be no JavaScript errors
@@ -142,8 +178,9 @@ Before({ order: 200 }, function (scope) {
142
178
  *
143
179
  */
144
180
  Then(/^there should be no JavaScript errors$/, function () {
145
- this._jsErrorsAsserted = true;
146
- const errs = filterErrors(this._jsErrors || [], this._jsSettings && this._jsSettings.ignore);
181
+ markHandled(this, 'error');
182
+ const errs = filterErrors(this._jsErrors || [], this._jsSettings && this._jsSettings.ignore)
183
+ .filter((e) => kindOf(e) === 'error');
147
184
  if (errs.length === 0) return;
148
185
  assert.fail(`JavaScript errors detected:\n${formatErrors(errs)}`);
149
186
  });
@@ -151,7 +188,8 @@ Then(/^there should be no JavaScript errors$/, function () {
151
188
  /**
152
189
  * Assert that no JavaScript console warnings were collected. Requires
153
190
  * 'warning' to be in the captured console levels (see worldParameters or
154
- * WEBSHIP_JS_ERROR_LEVELS).
191
+ * WEBSHIP_JS_ERROR_LEVELS). The warnings are left out of the auto-report at
192
+ * scenario end; errors are still reported there.
155
193
  *
156
194
  * Example #1: Then there should be no JavaScript warnings
157
195
  * Example #2: And there should be no JavaScript warnings
@@ -161,8 +199,8 @@ Then(/^there should be no JavaScript errors$/, function () {
161
199
  *
162
200
  */
163
201
  Then(/^there should be no JavaScript warnings$/, function () {
164
- this._jsErrorsAsserted = true;
165
- const errs = (this._jsErrors || []).filter((e) => e.type === 'console.warning');
202
+ markHandled(this, 'warning');
203
+ const errs = (this._jsErrors || []).filter((e) => kindOf(e) === 'warning');
166
204
  if (errs.length === 0) return;
167
205
  assert.fail(`JavaScript warnings detected:\n${formatErrors(errs)}`);
168
206
  });
@@ -170,7 +208,9 @@ Then(/^there should be no JavaScript warnings$/, function () {
170
208
  /**
171
209
  * Assert that no collected JavaScript error message matches a regular
172
210
  * expression. Useful when some noise is unavoidable but a specific bug
173
- * pattern must never appear.
211
+ * pattern must never appear. Like the other two checks, it handles the
212
+ * errors it read: the end-of-scenario report, in "fail" mode too, does not
213
+ * fail the scenario on the noise the step tolerated.
174
214
  *
175
215
  * Example #1: Then JavaScript errors should not match "TypeError"
176
216
  * Example #2: Then JavaScript errors should not match "is not a function"
@@ -180,6 +220,7 @@ Then(/^there should be no JavaScript warnings$/, function () {
180
220
  *
181
221
  */
182
222
  Then(/^JavaScript errors should not match "([^"]*)"$/, function (pattern) {
223
+ this._jsErrorsAsserted = true;
183
224
  let re;
184
225
  try { re = new RegExp(pattern); }
185
226
  catch (e) {
@@ -215,13 +256,14 @@ Then(/^print JavaScript errors$/, function () {
215
256
  // After — report per mode.
216
257
  // ---------------------------------------------------------------------------
217
258
 
218
- After({ order: 200 }, function (scope) {
259
+ After(function (scope) {
219
260
  const s = this._jsSettings || resolveSettings(this, scope);
220
261
  if (s.mode === 'off') return;
221
262
  if (!s.afterScenario) return;
222
263
  if (this._jsErrorsAsserted) return; // already handled by explicit step
223
264
 
224
- const errs = filterErrors(this._jsErrors || [], s.ignore);
265
+ const handled = this._jsHandledKinds || new Set();
266
+ const errs = filterErrors(this._jsErrors || [], s.ignore).filter((e) => !handled.has(kindOf(e)));
225
267
  if (errs.length === 0) return;
226
268
 
227
269
  if (s.mode === 'fail') {
@@ -15,12 +15,65 @@ const { When, Then } = require('@cucumber/cucumber');
15
15
  const assert = require('assert');
16
16
  const {
17
17
  getModalLocator,
18
+ getModalSelector,
18
19
  findVisibleModal,
19
20
  isAnyModalVisible,
20
21
  waitForModalState,
21
22
  friendly,
23
+ failure,
24
+ isTimeout,
22
25
  } = require('./webship');
23
26
 
27
+ // The controls a modal is acted on through by their text.
28
+ const MODAL_CONTROLS = 'button, a, [role="button"], input[type="button"], input[type="submit"], .btn';
29
+
30
+ /**
31
+ * The modal that is open, waiting up to 5 seconds for one. When none is
32
+ * open, the step fails at once with what it wanted to do, the modal selector
33
+ * it tried and a hint, instead of a long wait and "the page took too long".
34
+ *
35
+ * @param {Object} world
36
+ * @param {string} action - What the step wanted to do in the modal.
37
+ * @returns {Promise<import('playwright').Locator>}
38
+ */
39
+ async function openModal(world, action) {
40
+ try {
41
+ await waitForModalState(world.page, 'visible', 5000, world);
42
+ } catch (e) {
43
+ if (!isTimeout(e)) throw e;
44
+ throw failure(world.page, 'No modal is open: none was visible after 5 seconds.', {
45
+ hint: `the step wanted to ${action}. Open the modal first, or wait for it: When I wait for the modal to appear. Modals are found with "${getModalSelector(world)}"; register a "modal" CSS selector for other markup.`,
46
+ });
47
+ }
48
+ return findVisibleModal(world.page, world);
49
+ }
50
+
51
+ /**
52
+ * Wait up to 5 seconds for an element of the open modal to be visible; fail
53
+ * plainly, with what the modal offers, when it does not show.
54
+ *
55
+ * @param {Object} world
56
+ * @param {import('playwright').Locator} modal
57
+ * @param {import('playwright').Locator} target
58
+ * @param {string} message - The failure when the element does not show.
59
+ * @param {string} hint
60
+ * @returns {Promise<void>}
61
+ */
62
+ async function inModal(world, modal, target, message, hint) {
63
+ try {
64
+ await target.waitFor({ state: 'visible', timeout: 5000 });
65
+ } catch (e) {
66
+ if (!isTimeout(e)) throw e;
67
+ const names = await modal.locator(MODAL_CONTROLS).evaluateAll((els) => els
68
+ .map((el) => (el.innerText || el.value || el.getAttribute('aria-label') || el.getAttribute('title') || '').replace(/\s+/g, ' ').trim())
69
+ .filter(Boolean)).catch(() => []);
70
+ throw failure(world.page, message, {
71
+ found: names.length ? names.map((n) => `"${n}"`).join(', ') : 'no button or link',
72
+ hint,
73
+ });
74
+ }
75
+ }
76
+
24
77
  // ---------------------------------------------------------------------------
25
78
  // Visibility
26
79
  // ---------------------------------------------------------------------------
@@ -99,6 +152,7 @@ Then(/^(I |we )*should( not)* see (a |the )*"([^"]*)?" modal$/, async function (
99
152
  * Example #2: Then I should see "Delete this item" in the modal
100
153
  * Example #3: Then we should see "Confirmation required" in the modal dialog
101
154
  * Example #4: Then I should not see "Error occurred" in the modal
155
+ * Example #5: Then we should not see "Loading" in the modal dialog
102
156
  *
103
157
  */
104
158
  Then(/^(I |we )*should( not)* see "([^"]*)?" in( the)* modal( dialog)*$/, async function (pronounCase, notCase, expectedText, theCase, dialogCase) {
@@ -162,25 +216,29 @@ Then('the modal should not contain {string}', async function (text) {
162
216
  /**
163
217
  * Click a button or link inside a modal dialog by its visible text.
164
218
  *
219
+ * Waits up to 5 seconds for a modal to be open; when none is, the step fails
220
+ * with "No modal is open". A button or link the open modal does not have
221
+ * fails within 5 seconds, listing the ones it has.
222
+ *
165
223
  * Example #1: When I click "Confirm" in the modal
166
224
  * Example #2: When I click "Cancel" in the modal dialog
167
225
  * Example #3: When we click "OK" button in the modal
168
226
  * Example #4: And I click "Close" in the modal
227
+ * Example #5: When we click "Save changes" in the modal dialog
169
228
  *
170
229
  */
171
230
  When(/^(I |we )*click "([^"]*)?"( button)* in( the)* modal( dialog)*$/, async function (pronounCase, buttonText, buttonCase, theCase, dialogCase) {
231
+ const modal = await openModal(this, `click "${buttonText}" in it`);
232
+ const target = modal.locator(MODAL_CONTROLS).filter({ hasText: buttonText }).first();
233
+ await inModal(this, modal, target, `The open modal has no button or link "${buttonText}".`,
234
+ 'name the button by its visible text. For a button without text, use: I click on "<selector>" in the modal');
172
235
  try {
173
- await waitForModalState(this.page, 'visible', 10000, this);
174
- const modal = await findVisibleModal(this.page, this);
175
- await modal.locator('button, a, [role="button"], input[type="button"], input[type="submit"], .btn')
176
- .filter({ hasText: buttonText })
177
- .first()
178
- .click();
236
+ await target.click({ timeout: 5000 });
179
237
  } catch (e) {
180
238
  throw friendly({
181
239
  action: `click "${buttonText}" in the modal`,
182
240
  cause: e,
183
- hint: `make sure the modal is open ("When I wait for the modal to appear") and the button text matches exactly.`,
241
+ hint: 'the button is in the open modal but could not be clicked; another element may cover it.',
184
242
  });
185
243
  }
186
244
  });
@@ -190,7 +248,9 @@ When(/^(I |we )*click "([^"]*)?"( button)* in( the)* modal( dialog)*$/, async fu
190
248
  *
191
249
  * Distinct from "click :text in the modal" which uses visible button text.
192
250
  * Use this variant when the target lacks readable text (icon button) or
193
- * when text is ambiguous across multiple buttons in the modal.
251
+ * when text is ambiguous across multiple buttons in the modal. The selector
252
+ * is looked for inside the open modal only; when no modal is open within 5
253
+ * seconds, the step fails with "No modal is open".
194
254
  *
195
255
  * Example #1: When I click on "#close-btn" in the modal
196
256
  * Example #2: When I click on ".confirm-delete" in the modal
@@ -202,33 +262,39 @@ When(/^(I |we )*click "([^"]*)?"( button)* in( the)* modal( dialog)*$/, async fu
202
262
  *
203
263
  */
204
264
  When(/^(I |we )*click on "([^"]*)" in the modal$/, async function (pronoun, selector) {
265
+ const modal = await openModal(this, `click on "${selector}" in it`);
266
+ const target = modal.locator(selector).first();
267
+ await inModal(this, modal, target, `The open modal has no visible element "${selector}".`,
268
+ 'the selector is looked for inside the open modal only; to click by visible text, use: I click "<text>" in the modal');
205
269
  try {
206
- await getModalLocator(this.page, this).locator(selector).first().click();
270
+ await target.click({ timeout: 5000 });
207
271
  } catch (e) {
208
272
  throw friendly({
209
273
  action: `click on "${selector}" in the modal`,
210
274
  cause: e,
211
- hint: `make sure the modal is open and the selector matches something inside it.`,
275
+ hint: 'the element is in the open modal but could not be clicked; another element may cover it.',
212
276
  });
213
277
  }
214
278
  });
215
279
 
216
280
  /**
217
281
  * Close or dismiss a modal dialog (uses close button, or Escape fallback).
282
+ * When no modal is open within 5 seconds, the step fails with "No modal is
283
+ * open".
218
284
  *
219
285
  * Example #1: When I close the modal
220
286
  * Example #2: When I dismiss the modal dialog
221
287
  * Example #3: When we close the modal
222
288
  * Example #4: And I dismiss the modal
289
+ * Example #5: When we dismiss the modal dialog
223
290
  *
224
291
  */
225
292
  When(/^(I |we )*(close|dismiss)( the)* modal( dialog)*$/, async function (pronounCase, closeOrDismiss, theCase, dialogCase) {
293
+ const modal = await openModal(this, `${closeOrDismiss} it`);
226
294
  try {
227
- await waitForModalState(this.page, 'visible', 10000, this);
228
- const modal = await findVisibleModal(this.page, this);
229
295
  const closeBtn = modal.locator('.close, .modal-close, [data-dismiss="modal"], [aria-label="Close"], .btn-close, button[class*="close"]').first();
230
296
  if (await closeBtn.isVisible()) {
231
- await closeBtn.click();
297
+ await closeBtn.click({ timeout: 5000 });
232
298
  } else {
233
299
  await modal.press('Escape');
234
300
  }
@@ -18,6 +18,10 @@ const { gotoUrl, resolveUrl, waitForPageLoad, smartSettle } = require('./webship
18
18
  * Example #1: Given I am an anonymous user
19
19
  * Example #2: Given we are an anonymous user
20
20
  * Example #3: Given an anonymous user
21
+ * Example #4: Given I am an anonymous user
22
+ * And I am on "/user/login"
23
+ * Example #5: Given we are an anonymous user
24
+ * When we go to "/admin"
21
25
  *
22
26
  */
23
27
  Given(/^(I am |we are )?an anonymous user$/, async function (pronounCase) {
@@ -117,6 +121,9 @@ When(/^(I go |I navigate |we go |we navigate |navigating )?to "([^"]*)?"$/, asyn
117
121
  * Example #1: When I move forward one page
118
122
  * Example #2: When we move forward one page
119
123
  * Example #3: And move forward one page
124
+ * Example #4: When I move backward one page
125
+ * And I move forward one page
126
+ * Example #5: Then we move forward one page
120
127
  *
121
128
  */
122
129
  When(/^(I |we )*move forward one page$/, async function (pronounCase) {
@@ -129,6 +136,9 @@ When(/^(I |we )*move forward one page$/, async function (pronounCase) {
129
136
  * Example #1: When I move backward one page
130
137
  * Example #2: When we move backward one page
131
138
  * Example #3: And move backward one page
139
+ * Example #4: When I follow "About Us"
140
+ * And I move backward one page
141
+ * Example #5: Then we move backward one page
132
142
  *
133
143
  */
134
144
  When(/^(I |we )*move backward one page$/, async function (pronounCase) {
@@ -142,6 +152,8 @@ When(/^(I |we )*move backward one page$/, async function (pronounCase) {
142
152
  * Example #2: And I reload the page
143
153
  * Example #3: And we reload page
144
154
  * Example #4: And we reload the page
155
+ * Example #5: When I press "Save"
156
+ * And I reload the page
145
157
  *
146
158
  */
147
159
  When(/^(I |we )*reload( the)*( page)*$/, async function (pronounCase, theCase, pageCase) {
@@ -208,6 +220,8 @@ Then(/^(I |we )*should( not)* be on( the)* "([^"]*)?"( page)*$/, async function
208
220
  * Example #1: Then the url should match "/contact-us.html"
209
221
  * Example #2: Then the url should not match "/contact-us.html"
210
222
  * Example #3: And the url should match "^https://"
223
+ * Example #4: Then the url should match "/user/[0-9]+"
224
+ * Example #5: And the url should not match "/admin"
211
225
  *
212
226
  */
213
227
  Then(/^(the )*url should( not)* match "([^"]*)?"$/, async function (theCase, notCase, pattern) {
@@ -1,6 +1,6 @@
1
1
  'use strict';
2
2
 
3
- const { friendly } = require('./webship');
3
+ const { friendly, onNewPage } = require('./webship');
4
4
 
5
5
  // Network interception and mocking via Playwright's `page.route()` API.
6
6
  //
@@ -14,10 +14,8 @@ const { friendly } = require('./webship');
14
14
  const { Given, When, Then } = require('@cucumber/cucumber');
15
15
  const assert = require('assert');
16
16
 
17
- function ensureRequestLog(world) {
18
- if (world._requestLog) return;
19
- world._requestLog = [];
20
- world.page.on('request', (req) => {
17
+ function logRequests(world, page) {
18
+ page.on('request', (req) => {
21
19
  world._requestLog.push({
22
20
  url: req.url(),
23
21
  method: req.method(),
@@ -26,6 +24,18 @@ function ensureRequestLog(world) {
26
24
  });
27
25
  }
28
26
 
27
+ function ensureRequestLog(world) {
28
+ if (world._requestLog) return;
29
+ world._requestLog = [];
30
+ logRequests(world, world.page);
31
+ }
32
+
33
+ // A step that replaces the browser context (restoring an auth state, a video
34
+ // recording) opens a new page: a running request log goes on with it.
35
+ onNewPage((world, page) => {
36
+ if (world._requestLog) logRequests(world, page);
37
+ });
38
+
29
39
  // ---------------------------------------------------------------------------
30
40
  // Stubbing
31
41
  // ---------------------------------------------------------------------------
@@ -8,7 +8,7 @@
8
8
 
9
9
  const { Then, Before } = require('@cucumber/cucumber');
10
10
  const assert = require('assert');
11
- const { friendly } = require('./webship');
11
+ const { friendly, onNewPage } = require('./webship');
12
12
 
13
13
  const trackedPages = new WeakSet();
14
14
 
@@ -18,8 +18,8 @@ function withoutHash(url) {
18
18
  }
19
19
 
20
20
  // Record the response of every main-document navigation on the current page.
21
- // Steps that swap the page (auth state, basic authentication, a new session)
22
- // get the listener on their first use of the response steps.
21
+ // Every page the World opens gets the listener (onNewPage); a page swapped
22
+ // in some other way gets it on its first use of the response steps.
23
23
  function trackResponses(world) {
24
24
  const page = world.page;
25
25
  if (!page || trackedPages.has(page)) return;
@@ -35,7 +35,9 @@ function trackResponses(world) {
35
35
  });
36
36
  }
37
37
 
38
- Before({ order: 100 }, async function () {
38
+ onNewPage((world) => trackResponses(world));
39
+
40
+ Before(async function () {
39
41
  this._lastResponse = null;
40
42
  this._lastResponseHeaders = null;
41
43
  this._lastResponseStatus = null;
@@ -1,34 +1,19 @@
1
1
  'use strict';
2
2
 
3
- const { friendly } = require('./webship');
3
+ const { friendly, breakpoint } = require('./webship');
4
4
 
5
- // Set viewport dimensions and named breakpoints.
5
+ // Set viewport dimensions and named breakpoints. The named sizes come from
6
+ // the one breakpoint registry of webship.js: the built-in names (xs, sm, md,
7
+ // lg, xl, xxl, xxxl, mobile, tablet, desktop), then
8
+ // worldParameters.selectors.breakpoints, then WEBSHIP_SELECTORS_BREAKPOINTS,
9
+ // then the names a scenario adds with "the following responsive breakpoints:".
6
10
 
7
11
  const { Given, When } = require('@cucumber/cucumber');
8
12
 
9
- const DEFAULT_BREAKPOINTS = {
10
- xs: { width: 375, height: 667 },
11
- sm: { width: 576, height: 800 },
12
- md: { width: 768, height: 1024 },
13
- lg: { width: 992, height: 768 },
14
- xl: { width: 1200, height: 900 },
15
- xxl: { width: 1400, height: 900 },
16
- xxxl: { width: 1920, height: 1080 },
17
- mobile: { width: 375, height: 667 },
18
- tablet: { width: 768, height: 1024 },
19
- desktop: { width: 1200, height: 900 },
20
- };
21
-
22
- function getBreakpoints(world) {
23
- if (!world._breakpoints) {
24
- const cfg = (world.parameters && world.parameters.selectors && world.parameters.selectors.breakpoints) || {};
25
- world._breakpoints = { ...DEFAULT_BREAKPOINTS, ...cfg };
26
- }
27
- return world._breakpoints;
28
- }
29
-
30
13
  /**
31
- * Replace the breakpoint registry for the current scenario from a data table.
14
+ * Add named breakpoints for the current scenario from a data table: one row
15
+ * per name, `| name | width | height |`. The names replace the sizes of the
16
+ * same names; every other breakpoint (built in or configured) stays.
32
17
  *
33
18
  * Example #1: Given the following responsive breakpoints:
34
19
  * | mobile | 375 | 667 |
@@ -49,19 +34,30 @@ function getBreakpoints(world) {
49
34
  *
50
35
  */
51
36
  Given('the following responsive breakpoints:', async function (table) {
52
- const map = {};
37
+ const added = {};
53
38
  for (const row of table.raw()) {
54
39
  const [name, w, h] = row;
55
- map[name] = { width: parseInt(w, 10), height: parseInt(h, 10) };
40
+ const width = parseInt(w, 10);
41
+ const height = parseInt(h, 10);
42
+ if (!name || !(width > 0) || !(height > 0)) {
43
+ throw friendly(
44
+ `The breakpoint row | ${row.join(' | ')} | is not a name, a width and a height.\n` +
45
+ ' Hint: write each row as | name | width | height |, with the sizes in whole pixels, such as | tablet | 768 | 1024 |.'
46
+ );
47
+ }
48
+ added[name.trim()] = { width, height };
56
49
  }
57
- this._breakpoints = { ...DEFAULT_BREAKPOINTS, ...map };
50
+ this.__scenarioBreakpoints = Object.assign({}, this.__scenarioBreakpoints, added);
58
51
  });
59
52
 
60
53
  /**
61
- * Resize the viewport to a registered named breakpoint.
54
+ * Resize the viewport to a named breakpoint.
62
55
  *
63
56
  * Built-in names: `xs`, `sm`, `md`, `lg`, `xl`, `xxl`, `xxxl`, `mobile`,
64
- * `tablet`, `desktop`. Project-defined names override built-ins.
57
+ * `tablet`, `desktop`. A project's names (worldParameters.selectors.breakpoints,
58
+ * WEBSHIP_SELECTORS_BREAKPOINTS) and a scenario's own (the table step above)
59
+ * replace the built-in sizes of the same names. An unknown name fails with
60
+ * the list of the known ones.
65
61
  *
66
62
  * Example #1: When I set the viewport to the "mobile" breakpoint
67
63
  * Example #2: When I set the viewport to the "tablet" breakpoint
@@ -71,10 +67,7 @@ Given('the following responsive breakpoints:', async function (table) {
71
67
  *
72
68
  */
73
69
  When(/^(I |we )*set the viewport to the "([^"]*)" breakpoint$/, async function (pronoun, name) {
74
- const bps = getBreakpoints(this);
75
- const bp = bps[name];
76
- if (!bp) throw friendly(`Unknown breakpoint "${name}".`);
77
- await this.page.setViewportSize({ width: bp.width, height: bp.height });
70
+ await this.page.setViewportSize(breakpoint(this, name));
78
71
  });
79
72
 
80
73
  /**
@@ -5,7 +5,9 @@
5
5
  //
6
6
  // Saves PNG (and matching .html) screenshots to a configurable directory.
7
7
  // Supports manual steps, automatic capture on failed step, and per-step
8
- // capture for scenarios tagged @screenshots.
8
+ // capture for scenarios tagged @screenshots. The screenshot of a failed step
9
+ // is also attached to that step in the cucumber JSON report, so the HTML
10
+ // report shows it.
9
11
  //
10
12
  // Configuration: resolved per-scenario with this priority:
11
13
  // 1. process.env.WEBSHIP_SCREENSHOT_* (CI / shell — highest)
@@ -174,7 +176,9 @@ function buildInfo(cfg, ctx) {
174
176
  function makeFileName(cfg, ctx, ext, explicitName, isFailed) {
175
177
  let pattern;
176
178
  if (isFailed) pattern = cfg.filenamePatternFailed;
177
- else if (explicitName) pattern = explicitName;
179
+ // A name that ends with the extension of a file the step writes
180
+ // ("homepage.png") keeps that one extension: homepage.png, homepage.html.
181
+ else if (explicitName) pattern = explicitName.replace(/\.(?:png|jpe?g|html?)$/i, '');
178
182
  else pattern = cfg.filenamePattern;
179
183
 
180
184
  if (!pattern.endsWith('.{ext}')) pattern += '.{ext}';
@@ -212,13 +216,17 @@ async function captureScreenshot(world, options = {}) {
212
216
  fs.writeFileSync(path.join(cfg.dir, htmlName), html);
213
217
  } catch { /* no content yet */ }
214
218
 
215
- // PNG capture.
219
+ // PNG capture. A failure screenshot is also attached to the failed step,
220
+ // so the JSON report carries it and the HTML report shows it.
216
221
  try {
217
222
  const pngName = makeFileName(cfg, ctx, 'png', options.filename, options.isFailed);
218
- await world.page.screenshot({
223
+ const png = await world.page.screenshot({
219
224
  path: path.join(cfg.dir, pngName),
220
225
  fullPage: fullscreen,
221
226
  });
227
+ if (options.isFailed && png && typeof world.attach === 'function') {
228
+ await world.attach(png, 'image/png');
229
+ }
222
230
  } catch { /* driver without screenshot support */ }
223
231
  }
224
232
 
@@ -262,9 +270,14 @@ AfterStep(async function (step) {
262
270
  }
263
271
 
264
272
  const cfg = resolveConfig(this.parameters);
265
- const passed = step.result && step.result.status === 'PASSED';
266
-
267
- if (!passed && cfg.onFailed) {
273
+ const status = step.result && step.result.status;
274
+ const passed = status === 'PASSED';
275
+ // A failure screenshot is for a step that failed, or that no definition
276
+ // (or more than one) matched. A step that skips its scenario on purpose
277
+ // (it returned 'skipped') or is still pending is not a failure.
278
+ const failed = status === 'FAILED' || status === 'AMBIGUOUS' || status === 'UNDEFINED';
279
+
280
+ if (failed && cfg.onFailed) {
268
281
  await captureScreenshot(this, { isFailed: true, fullscreen: cfg.alwaysFullscreen });
269
282
  return;
270
283
  }
@@ -379,7 +392,9 @@ When(/^(I |we )*save fullscreen (\d+) x (\d+) screenshot$/, async function (pron
379
392
  });
380
393
 
381
394
  /**
382
- * Save a screenshot using an explicit filename (tokens supported).
395
+ * Save a screenshot using an explicit filename (tokens supported). The step
396
+ * writes `<name>.png` and `<name>.html`; a name that already ends with
397
+ * `.png`, `.jpg`, `.jpeg` or `.html` keeps that one extension.
383
398
  *
384
399
  * Example #1: Then I save screenshot with name "homepage.png"
385
400
  * Example #2: Then I save screenshot with name "webship-home"
@@ -401,6 +416,8 @@ When(/^(I |we )*save screenshot with name "([^"]*)"$/, async function (pronounCa
401
416
 
402
417
  /**
403
418
  * Save a full-page screenshot using an explicit filename (tokens supported).
419
+ * A name that already ends with `.png`, `.jpg`, `.jpeg` or `.html` keeps that
420
+ * one extension.
404
421
  *
405
422
  * Example #1: Then I save fullscreen screenshot with name "homepage-full.png"
406
423
  * Example #2: Then I save fullscreen screenshot with name "webship-home-full"