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
@@ -4,7 +4,7 @@
4
4
 
5
5
  const { Given, When, Then } = require('@cucumber/cucumber');
6
6
  const assert = require('assert');
7
- const { friendly } = require('./webship');
7
+ const { friendly, failure, fillLocator, humanize, isTimeout } = require('./webship');
8
8
 
9
9
  // Resolve a field by label, name, id, or selector.
10
10
  function fieldLocator(page, field) {
@@ -28,42 +28,204 @@ async function getField(page, field) {
28
28
  return loc;
29
29
  }
30
30
 
31
- // Escape a label for use inside a quoted CSS / Playwright selector string.
32
- function quoted(text) {
33
- return String(text).replace(/\\/g, '\\\\').replace(/"/g, '\\"');
31
+ // Find, in the page, the date or the time input of the datetime field named
32
+ // `label`, and return a CSS path to it (null when there is none yet). The
33
+ // field is looked for in this order, and the first that has such an input
34
+ // wins:
35
+ // 1. a <label> whose text is the label (white space and letter case aside):
36
+ // an input inside it, the control it is for, else the inputs that follow
37
+ // it in its own field: up to the next label, legend or fieldset of the
38
+ // same level, within the container it shares with its control (or its
39
+ // parent; a label alone in its wrapper reads the wrapper's next siblings);
40
+ // 2. a <fieldset> whose <legend> is the label: the inputs inside it;
41
+ // 3. an input whose name, then whose aria-label, contains the label.
42
+ // `half` narrows a date range to its "start" or its "end" input (by name, id
43
+ // or aria-label).
44
+ function findDatetimeInput({ label, type, half }) {
45
+ const norm = (text) => String(text || '').replace(/\s+/g, ' ').trim().toLowerCase();
46
+ const wanted = norm(label);
47
+ const halfOk = (el) => !half || [el.name, el.id, el.getAttribute('aria-label')].some((v) => String(v || '').toLowerCase().includes(half));
48
+ const fits = (el) => !!el && el.nodeType === 1 && el.matches(`input[type="${type}"]`) && halfOk(el);
49
+ const inside = (root) => Array.from(root.querySelectorAll(`input[type="${type}"]`)).filter(halfOk);
50
+ const follows = (a, b) => !!(a.compareDocumentPosition(b) & Node.DOCUMENT_POSITION_FOLLOWING);
51
+ const BOUNDARY = 'label, legend, fieldset';
52
+
53
+ // The inputs after `start`, within `box`, up to the next label, legend or
54
+ // fieldset that is not nested deeper than `start` (another field).
55
+ function after(start, box) {
56
+ const all = Array.from(box.querySelectorAll(`input[type="${type}"], ${BOUNDARY}`));
57
+ for (const el of all) {
58
+ if (el === start || start.contains(el) || !follows(start, el)) continue;
59
+ if (el.matches(BOUNDARY)) {
60
+ if (el.parentElement && el.parentElement.contains(start)) return null;
61
+ continue;
62
+ }
63
+ if (fits(el)) return el;
64
+ }
65
+ return null;
66
+ }
67
+
68
+ function inField(lab) {
69
+ const own = inside(lab);
70
+ if (own.length) return own[0];
71
+ const control = lab.control;
72
+ if (fits(control)) return control;
73
+ if (control) {
74
+ let box = control.parentElement;
75
+ while (box && !box.contains(lab)) box = box.parentElement;
76
+ if (box) return after(lab, box);
77
+ }
78
+ let unit = lab;
79
+ for (let level = 0; level < 3 && unit.parentElement && unit.parentElement !== document.body; level += 1) {
80
+ const found = after(unit, unit.parentElement);
81
+ if (found || unit.nextElementSibling) return found;
82
+ unit = unit.parentElement;
83
+ }
84
+ return null;
85
+ }
86
+
87
+ function pathTo(el) {
88
+ const parts = [];
89
+ for (let node = el; node && node.nodeType === 1 && node !== document.documentElement; node = node.parentElement) {
90
+ let index = 1;
91
+ for (let sib = node.previousElementSibling; sib; sib = sib.previousElementSibling) {
92
+ if (sib.tagName === node.tagName) index += 1;
93
+ }
94
+ parts.unshift(`${node.tagName.toLowerCase()}:nth-of-type(${index})`);
95
+ }
96
+ return 'html > ' + parts.join(' > ');
97
+ }
98
+
99
+ for (const lab of document.querySelectorAll('label')) {
100
+ if (norm(lab.textContent) !== wanted) continue;
101
+ const found = inField(lab);
102
+ if (found) return pathTo(found);
103
+ }
104
+ for (const legend of document.querySelectorAll('fieldset > legend')) {
105
+ if (norm(legend.textContent) !== wanted) continue;
106
+ const found = inside(legend.parentElement)[0];
107
+ if (found) return pathTo(found);
108
+ }
109
+ const all = Array.from(document.querySelectorAll(`input[type="${type}"]`)).filter(halfOk);
110
+ const byName = all.find((el) => norm(el.name).includes(wanted));
111
+ if (byName) return pathTo(byName);
112
+ const byAria = all.find((el) => norm(el.getAttribute('aria-label')).includes(wanted));
113
+ return byAria ? pathTo(byAria) : null;
34
114
  }
35
115
 
36
- // Resolve the date or the time input of a datetime field named by its label.
37
- // The pair is written in many ways, so every usual one is looked at, and the
38
- // first input in the page that fits is taken:
39
- // - inputs in an element that follows the label, or right after the label;
40
- // - inputs inside the label;
41
- // - inputs of a fieldset whose legend carries the label;
42
- // - inputs whose name or accessible name contains the label, whatever the case.
43
- // `half` narrows a date range to its "start" or its "end" input.
116
+ // Resolve the date or the time input of a datetime field named by its label
117
+ // (see findDatetimeInput), waiting up to 5 seconds for it.
44
118
  async function datetimePart(page, label, type, half) {
45
- const l = quoted(label);
46
- const input = `input[type="${type}"]${half ? `[name*="${half}" i]` : ''}`;
47
- const named = `input[type="${type}"][name*="${l}" i]${half ? `[name*="${half}" i]` : ''}`;
48
- const loc = page.locator([
49
- `label:has-text("${l}") ~ * ${input}`,
50
- `label:has-text("${l}") ~ ${input}`,
51
- `label:has-text("${l}") ${input}`,
52
- `fieldset:has(legend:has-text("${l}")) ${input}`,
53
- named,
54
- `${input}[aria-label*="${l}" i]`,
55
- ].join(', ')).first();
119
+ const deadline = Date.now() + 5000;
120
+ for (;;) {
121
+ const path = await page.evaluate(findDatetimeInput, { label, type, half: half || null }).catch(() => null);
122
+ if (path) return page.locator(path);
123
+ if (Date.now() >= deadline) break;
124
+ await page.waitForTimeout(100);
125
+ }
126
+ throw failure(page, `The datetime field "${label}" has no ${half ? half + ' ' : ''}${type} input.`, {
127
+ hint: `the field is named by the exact text of its label or of the legend of its fieldset; its ${type} input is the one inside the label, the one the label is for, or one that follows the label before the next field. An input whose name or aria-label contains "${label}" is found too.`,
128
+ });
129
+ }
130
+
131
+ // The checkbox, radio button and field steps find a control by a CSS
132
+ // selector, the exact text of its label, its name, its id or (a checkbox or a
133
+ // radio button) its value. A radio button is not found by its name: the name
134
+ // is shared by its whole group.
135
+ const CONTROLS = {
136
+ checkbox: {
137
+ css: 'input[type="checkbox"], [role="checkbox"]',
138
+ noun: 'checkbox', state: 'checked', by: ['name', 'id', 'value'],
139
+ says: 'the label, the name, the id or the selector',
140
+ },
141
+ radio: {
142
+ css: 'input[type="radio"], [role="radio"]',
143
+ noun: 'radio button', state: 'selected', by: ['id', 'value'],
144
+ says: 'the label, the id, the value or the selector',
145
+ },
146
+ field: {
147
+ css: 'input:not([type="hidden"]):not([type="checkbox"]):not([type="radio"]):not([type="submit"]):not([type="button"]):not([type="reset"]):not([type="image"]), textarea, select',
148
+ noun: 'field', by: ['name', 'id'],
149
+ says: 'the label, the name, the id or the selector',
150
+ },
151
+ };
152
+
153
+ /**
154
+ * Find the checkbox, radio button or field a step names, waiting up to 5
155
+ * seconds for it; fail the step plainly when there is none.
156
+ *
157
+ * @param {import('playwright').Page} page
158
+ * @param {string} name - A CSS selector, or the label, name, id or value.
159
+ * @param {'checkbox'|'radio'|'field'} kind
160
+ * @returns {Promise<import('playwright').Locator>}
161
+ */
162
+ async function locateControl(page, name, kind) {
163
+ const spec = CONTROLS[kind];
164
+ const q = String(name).replace(/["\\]/g, '\\$&');
165
+ const ofKind = page.locator(spec.css);
166
+ let named = page.getByLabel(name, { exact: true }).and(ofKind);
167
+ for (const attr of spec.by) named = named.or(ofKind.and(page.locator(`[${attr}="${q}"]`)));
168
+ // A name that is not a valid selector is left out of the search instead of
169
+ // failing it.
170
+ for (const loc of [named.or(page.locator(name)).first(), named.first()]) {
171
+ try {
172
+ await loc.waitFor({ state: 'attached', timeout: 5000 });
173
+ return loc;
174
+ } catch (e) {
175
+ if (isTimeout(e)) break;
176
+ }
177
+ }
178
+ throw failure(page, `No ${spec.noun} with ${spec.says} "${name}" was found after 5 seconds.`, {
179
+ hint: `name the ${spec.noun} by the exact text of its label, ${spec.by.map((a) => `its ${a}`).join(', ')}, or by a CSS selector such as "#id" or "input[name=…]".`,
180
+ });
181
+ }
182
+
183
+ /**
184
+ * Check that a checkbox is (or is not) checked, or a radio button selected.
185
+ *
186
+ * @param {Object} world
187
+ * @param {string} name
188
+ * @param {'checkbox'|'radio'} kind
189
+ * @param {boolean} wanted - true when it should be checked / selected.
190
+ */
191
+ async function assertChoice(world, name, kind, wanted) {
192
+ const spec = CONTROLS[kind];
193
+ const loc = await locateControl(world.page, name, kind);
194
+ let checked;
56
195
  try {
57
- await loc.waitFor({ state: 'attached', timeout: 5000 });
196
+ checked = await loc.isChecked({ timeout: 5000 });
58
197
  } catch (e) {
59
- throw friendly({
60
- action: `find the ${half ? half + ' ' : ''}${type} input of the datetime field`,
61
- target: label,
62
- cause: `no <input type="${type}"> was found after a label, inside a label or a fieldset, or by a name that contains "${label}"`,
63
- hint: 'use the visible label of the field, the legend of its fieldset, or a part of the name of its inputs.',
198
+ throw failure(world.page, `Could not read whether the ${spec.noun} "${name}" is ${spec.state}.`, {
199
+ hint: `${humanize(e)}; the element the step found may not be a ${spec.noun}.`,
200
+ });
201
+ }
202
+ if (checked === wanted) return;
203
+ throw failure(world.page, wanted
204
+ ? `The ${spec.noun} "${name}" is not ${spec.state}.`
205
+ : `The ${spec.noun} "${name}" is ${spec.state}, but it should not be.`, {
206
+ hint: `the ${spec.noun} is found by ${spec.says.replace(/ or the selector$/, '')} or a CSS selector; check that the step before it ${wanted ? spec.state.replace('ed', 's') : 'changes'} it.`,
207
+ });
208
+ }
209
+
210
+ /**
211
+ * Check or uncheck a checkbox, or select a radio button, found as the
212
+ * assertions find it.
213
+ *
214
+ * @param {Object} world
215
+ * @param {string} name
216
+ * @param {'checkbox'|'radio'} kind
217
+ * @param {'check'|'uncheck'} action
218
+ */
219
+ async function setChoice(world, name, kind, action) {
220
+ const spec = CONTROLS[kind];
221
+ const loc = await locateControl(world.page, name, kind);
222
+ try {
223
+ await loc[action]({ timeout: 5000 });
224
+ } catch (e) {
225
+ throw failure(world.page, `Could not ${action === 'check' && kind === 'radio' ? 'select' : action} the ${spec.noun} "${name}".`, {
226
+ hint: `${humanize(e)}; a ${spec.noun} that is hidden or disabled cannot be changed.`,
64
227
  });
65
228
  }
66
- return loc;
67
229
  }
68
230
 
69
231
  /**
@@ -130,21 +292,59 @@ Then('the field {string} should not exist', async function (field) {
130
292
  assert.strictEqual(await loc.count(), 0, `Field "${field}" should not exist.`);
131
293
  });
132
294
 
295
+ // The states `the field "X" should have "<state>" state` can check: how to
296
+ // read each one from the field, and how to name what the field is instead.
297
+ const FIELD_STATES = {
298
+ enabled: async (loc) => !(await loc.isDisabled()),
299
+ disabled: (loc) => loc.isDisabled(),
300
+ editable: (loc) => loc.isEditable(),
301
+ 'read-only': async (loc) => !(await loc.isDisabled()) && !(await loc.isEditable()),
302
+ };
303
+ const FIELD_STATE_ALIASES = { readonly: 'read-only', 'read only': 'read-only' };
304
+
305
+ async function fieldStateNow(loc) {
306
+ if (await loc.isDisabled()) return 'disabled';
307
+ return (await loc.isEditable()) ? 'enabled and editable' : 'enabled and read-only';
308
+ }
309
+
133
310
  /**
134
- * Assert a field's enabled / disabled state.
311
+ * Assert a field's state: `enabled`, `disabled`, `editable` (enabled and not
312
+ * read-only) or `read-only` (enabled, but its value cannot be changed;
313
+ * `readonly` works too). Any other word fails the step with the list of the
314
+ * states it can check.
135
315
  *
136
316
  * Example #1: Then the field "username" should have "enabled" state
137
317
  * Example #2: Then the field "Email" should have "disabled" state
138
318
  * Example #3: And the field "#search" should have "enabled" state
139
319
  * Example #4: Then the field "Password" should have "disabled" state
140
320
  * Example #5: Then the field "Country" should have "enabled" state
321
+ * Example #6: Then the field "Reference" should have "read-only" state
322
+ * Example #7: Then the field "Display name" should have "editable" state
141
323
  *
142
324
  */
143
325
  Then('the field {string} should have {string} state', async function (field, state) {
326
+ const wanted = String(state).trim().toLowerCase();
327
+ const name = FIELD_STATE_ALIASES[wanted] || wanted;
328
+ const check = FIELD_STATES[name];
329
+ if (!check) {
330
+ throw failure(this.page, `"${state}" is not a state this step can check.`, {
331
+ hint: `use one of: ${Object.keys(FIELD_STATES).join(', ')}. For the other states use their own steps: the field "${field}" should be required, the "${field}" checkbox should be checked, "${field}" should be visible.`,
332
+ });
333
+ }
144
334
  const loc = await getField(this.page, field);
145
- const disabled = await loc.isDisabled();
146
- if (state === 'disabled') assert.ok(disabled, `Field "${field}" should be disabled.`);
147
- else assert.ok(!disabled, `Field "${field}" should be enabled.`);
335
+ try {
336
+ await loc.waitFor({ state: 'attached', timeout: 5000 });
337
+ } catch (e) {
338
+ throw failure(this.page, `The field "${field}" was not found on the page after 5 seconds.`, {
339
+ hint: `"${field}" is read as the text of a label, else as a name or an id, else as a CSS selector that starts with #, . or [.`,
340
+ });
341
+ }
342
+ if (!(await check(loc))) {
343
+ throw failure(this.page, `The field "${field}" is not ${name}.`, {
344
+ found: `it is ${await fieldStateNow(loc)}`,
345
+ hint: 'a disabled field is neither editable nor read-only; a read-only field is enabled but its value cannot be changed.',
346
+ });
347
+ }
148
348
  });
149
349
 
150
350
  /**
@@ -181,8 +381,77 @@ Then('the field {string} should not be required', async function (field) {
181
381
  assert.ok(req === null && aria !== 'true', `Field "${field}" should not be required.`);
182
382
  });
183
383
 
384
+ // Find, in the page, the inputs of the multi-value field named `field`, in
385
+ // the order of the page, and return a CSS path to each (an empty list when
386
+ // there are none yet). In this order, the first that has inputs wins:
387
+ // 1. inputs whose name is `field[]`, `field[0]`, `field[0][value]`…;
388
+ // 2. the inputs of a <fieldset> whose <legend> is the text;
389
+ // 3. the inputs that follow a <label> whose text is the text: from the
390
+ // control it is for (else from the label) up to the next label, legend
391
+ // or fieldset of the same level, in the container they share.
392
+ // Text compared with letter case and white space aside. Text-like inputs and
393
+ // textareas only: a hidden input, a checkbox or a weight select is no value.
394
+ function findMultiValueInputs(field) {
395
+ const VALUE = 'input:not([type]), input[type="text"], input[type="email"], input[type="tel"], input[type="url"], input[type="number"], input[type="search"], input[type="date"], input[type="time"], input[type="datetime-local"], textarea';
396
+ const norm = (text) => String(text || '').replace(/\s+/g, ' ').trim().toLowerCase();
397
+ const wanted = norm(field);
398
+ const follows = (a, b) => !!(a.compareDocumentPosition(b) & Node.DOCUMENT_POSITION_FOLLOWING);
399
+ const BOUNDARY = 'label, legend, fieldset';
400
+
401
+ function pathTo(el) {
402
+ const parts = [];
403
+ for (let node = el; node && node.nodeType === 1 && node !== document.documentElement; node = node.parentElement) {
404
+ let index = 1;
405
+ for (let sib = node.previousElementSibling; sib; sib = sib.previousElementSibling) {
406
+ if (sib.tagName === node.tagName) index += 1;
407
+ }
408
+ parts.unshift(`${node.tagName.toLowerCase()}:nth-of-type(${index})`);
409
+ }
410
+ return 'html > ' + parts.join(' > ');
411
+ }
412
+
413
+ const byName = Array.from(document.querySelectorAll(VALUE)).filter((el) => {
414
+ const name = el.getAttribute('name') || '';
415
+ return name === `${field}[]` || name.startsWith(`${field}[`);
416
+ });
417
+ if (byName.length) return byName.map(pathTo);
418
+
419
+ for (const legend of document.querySelectorAll('fieldset > legend')) {
420
+ if (norm(legend.textContent) !== wanted) continue;
421
+ const inputs = Array.from(legend.parentElement.querySelectorAll(VALUE));
422
+ if (inputs.length) return inputs.map(pathTo);
423
+ }
424
+
425
+ for (const lab of document.querySelectorAll('label')) {
426
+ if (norm(lab.textContent) !== wanted) continue;
427
+ const start = lab.control && lab.control.matches(VALUE) ? lab.control : lab;
428
+ let box = start.parentElement;
429
+ while (box && !box.contains(lab)) box = box.parentElement;
430
+ if (!box) continue;
431
+ const inputs = [];
432
+ if (start !== lab) inputs.push(start);
433
+ for (const el of box.querySelectorAll(`${VALUE}, ${BOUNDARY}`)) {
434
+ if (el === start || el === lab || lab.contains(el) || !follows(start, el)) continue;
435
+ if (el.matches(BOUNDARY)) {
436
+ if (el.parentElement && el.parentElement.contains(lab)) break;
437
+ continue;
438
+ }
439
+ inputs.push(el);
440
+ }
441
+ if (inputs.length) return inputs.map(pathTo);
442
+ }
443
+ return [];
444
+ }
445
+
184
446
  /**
185
- * Fill a multi-value form field (e.g. `name[]` array inputs) from a table.
447
+ * Fill a multi-value form field from a table, one value per input, in the
448
+ * order of the page.
449
+ *
450
+ * The field is named by the name of its inputs (`tags` for `tags[]`,
451
+ * `tags[0]` or `tags[0][value]`), by the legend of its fieldset, or by its
452
+ * label (the inputs from the one the label is for up to the next field).
453
+ * A field that is not found within 5 seconds, or that has fewer inputs than
454
+ * values, fails the step before anything is filled.
186
455
  *
187
456
  * Example #1: When I fill in the multi-value field "tags" with the following values:
188
457
  * | bdd |
@@ -201,15 +470,32 @@ Then('the field {string} should not be required', async function (field) {
201
470
  * | tech |
202
471
  * | devops |
203
472
  * | testing |
473
+ * Example #6: When I fill in the multi-value field "Phone numbers" with the following values:
474
+ * | 0790000000 |
475
+ * | 0791111111 |
204
476
  *
205
477
  */
206
478
  When(/^(I |we )*fill in the multi-value field "([^"]*)" with the following values:$/, async function (pronoun, field, table) {
207
479
  const values = table.raw().flat();
480
+ const deadline = Date.now() + 5000;
481
+ let paths = [];
482
+ for (;;) {
483
+ paths = await this.page.evaluate(findMultiValueInputs, field).catch(() => []);
484
+ if (paths.length || Date.now() >= deadline) break;
485
+ await this.page.waitForTimeout(100);
486
+ }
487
+ if (!paths.length) {
488
+ throw failure(this.page, `No multi-value field "${field}" was found after 5 seconds.`, {
489
+ hint: `name the field by the name of its inputs ("${field}" for ${field}[] or ${field}[0]), by the legend of its fieldset, or by the exact text of its label.`,
490
+ });
491
+ }
492
+ if (paths.length < values.length) {
493
+ throw failure(this.page, `The multi-value field "${field}" has ${paths.length} input${paths.length === 1 ? '' : 's'} for ${values.length} values.`, {
494
+ hint: 'add inputs first (a form often has an "Add another item" button), or give as many values as the field has inputs.',
495
+ });
496
+ }
208
497
  for (let i = 0; i < values.length; i++) {
209
- const inputs = this.page.locator(`[name="${field}[${i}]"], [name="${field}[]"]`);
210
- const count = await inputs.count();
211
- const target = count > i ? inputs.nth(i) : inputs.first();
212
- await target.fill(values[i]);
498
+ await fillLocator(this.page, this.page.locator(paths[i]), values[i], `${field} (value ${i + 1})`);
213
499
  }
214
500
  });
215
501
 
@@ -428,7 +714,11 @@ When(/^(I |we )*clear the select "([^"]*)"$/, async function (pronoun, sel) {
428
714
  });
429
715
 
430
716
  /**
431
- * Check a CSS-addressed checkbox.
717
+ * Check a checkbox.
718
+ *
719
+ * The checkbox is named by a CSS selector, the exact text of its label, its
720
+ * name, its id or its value; one that is not found within 5 seconds fails
721
+ * the step plainly.
432
722
  *
433
723
  * Example #1: When I check the checkbox "#agree"
434
724
  * Example #2: When I check the checkbox "input[name=newsletter]"
@@ -438,11 +728,15 @@ When(/^(I |we )*clear the select "([^"]*)"$/, async function (pronoun, sel) {
438
728
  *
439
729
  */
440
730
  When(/^(I |we )*check the checkbox "([^"]*)"$/, async function (pronoun, sel) {
441
- await this.page.locator(sel).first().check();
731
+ await setChoice(this, sel, 'checkbox', 'check');
442
732
  });
443
733
 
444
734
  /**
445
- * Uncheck a CSS-addressed checkbox.
735
+ * Uncheck a checkbox.
736
+ *
737
+ * The checkbox is named by a CSS selector, the exact text of its label, its
738
+ * name, its id or its value; one that is not found within 5 seconds fails
739
+ * the step plainly.
446
740
  *
447
741
  * Example #1: When I uncheck the checkbox "#newsletter"
448
742
  * Example #2: When I uncheck the checkbox "input[name=marketing]"
@@ -452,11 +746,15 @@ When(/^(I |we )*check the checkbox "([^"]*)"$/, async function (pronoun, sel) {
452
746
  *
453
747
  */
454
748
  When(/^(I |we )*uncheck the checkbox "([^"]*)"$/, async function (pronoun, sel) {
455
- await this.page.locator(sel).first().uncheck();
749
+ await setChoice(this, sel, 'checkbox', 'uncheck');
456
750
  });
457
751
 
458
752
  /**
459
- * Select a CSS-addressed radio button.
753
+ * Select a radio button.
754
+ *
755
+ * The radio button is named by a CSS selector, the exact text of its label,
756
+ * its id or its value (not its name, which its whole group shares); one that
757
+ * is not found within 5 seconds fails the step plainly.
460
758
  *
461
759
  * Example #1: When I choose the radio button "#gender-male"
462
760
  * Example #2: When I choose the radio button "input[value=premium]"
@@ -466,7 +764,7 @@ When(/^(I |we )*uncheck the checkbox "([^"]*)"$/, async function (pronoun, sel)
466
764
  *
467
765
  */
468
766
  When(/^(I |we )*choose the radio button "([^"]*)"$/, async function (pronoun, sel) {
469
- await this.page.locator(sel).first().check();
767
+ await setChoice(this, sel, 'radio', 'check');
470
768
  });
471
769
 
472
770
  // Note: "the radio button :sel should be selected" is already provided by
@@ -474,7 +772,10 @@ When(/^(I |we )*choose the radio button "([^"]*)"$/, async function (pronoun, se
474
772
  // ambiguous step matches.
475
773
 
476
774
  /**
477
- * Fill a CSS-addressed input/textarea with a value.
775
+ * Fill an input or a textarea with a value. The field is named by a CSS
776
+ * selector, the exact text of its label, its name or its id; one that is not
777
+ * found within 5 seconds, or that is hidden, disabled or read-only, fails the
778
+ * step plainly.
478
779
  *
479
780
  * Example #1: When I fill in the field "#username" with "alice"
480
781
  * Example #2: When I fill in the field "input[name=email]" with "alice@example.com"
@@ -484,7 +785,8 @@ When(/^(I |we )*choose the radio button "([^"]*)"$/, async function (pronoun, se
484
785
  *
485
786
  */
486
787
  When(/^(I |we )*fill in the field "([^"]*)" with "([^"]*)"$/, async function (pronoun, sel, value) {
487
- await this.page.locator(sel).first().fill(value);
788
+ const loc = await locateControl(this.page, sel, 'field');
789
+ await fillLocator(this.page, loc, value, sel);
488
790
  });
489
791
 
490
792
  /**
@@ -510,10 +812,12 @@ Given('browser validation for the form {string} is disabled', async function (se
510
812
  /**
511
813
  * Fill paired `<input type=date>` + `<input type=time>` controls for a label.
512
814
  *
513
- * The field is named by its visible label or the legend of its fieldset; an
514
- * input whose name or aria-label contains that text is found too, whatever
515
- * the letter case. When an input is not found within 5 seconds the step
516
- * fails and fills nothing.
815
+ * The field is named by the exact text of its label or of the legend of its
816
+ * fieldset (white space and letter case aside), and only its own inputs are
817
+ * filled: the one inside the label, the one the label is for, or the ones
818
+ * that follow the label before the next field. An input whose name or
819
+ * aria-label contains that text is found too. When an input is not found
820
+ * within 5 seconds the step fails and fills nothing.
517
821
  *
518
822
  * Example #1: When I fill in the datetime field "Start" with date "2026-05-08" and time "10:00"
519
823
  * Example #2: When I fill in the datetime field "Departure" with date "2026-12-31" and time "23:59"
@@ -561,8 +865,9 @@ When(/^(I |we )*fill in the time part of the datetime field "([^"]*)" with "([^"
561
865
  /**
562
866
  * Fill the `start` half of a date-range pair.
563
867
  *
564
- * The range is named by its label or the legend of its fieldset; of its
565
- * inputs, the ones whose name contains "start" are filled.
868
+ * The range is named by the exact text of its label or of the legend of its
869
+ * fieldset; of its inputs, the ones whose name, id or aria-label contains
870
+ * "start" are filled.
566
871
  *
567
872
  * Example #1: When I fill in the start datetime field "Event" with date "2026-05-08" and time "10:00"
568
873
  * Example #2: When I fill in the start datetime field "Trip" with date "2026-12-31" and time "08:00"
@@ -581,8 +886,9 @@ When(/^(I |we )*fill in the start datetime field "([^"]*)" with date "([^"]*)" a
581
886
  /**
582
887
  * Fill the `end` half of a date-range pair.
583
888
  *
584
- * The range is named by its label or the legend of its fieldset; of its
585
- * inputs, the ones whose name contains "end" are filled.
889
+ * The range is named by the exact text of its label or of the legend of its
890
+ * fieldset; of its inputs, the ones whose name, id or aria-label contains
891
+ * "end" are filled.
586
892
  *
587
893
  * Example #1: When I fill in the end datetime field "Event" with date "2026-05-09" and time "18:00"
588
894
  * Example #2: When I fill in the end datetime field "Trip" with date "2027-01-07" and time "20:00"
@@ -638,6 +944,10 @@ ThenF(/^(the )*"([^"]*)?" field should( not)* contain "([^"]*)?"$/, async functi
638
944
  /**
639
945
  * Assert that a checkbox should or should not be checked.
640
946
  *
947
+ * The checkbox is named by a CSS selector, the exact text of its label, its
948
+ * name, its id or its value; one that is not found within 5 seconds fails
949
+ * the step plainly.
950
+ *
641
951
  * Example #1: Then the "#privacy-policy" checkbox should be checked
642
952
  * Example #2: Then the "#newsletter" checkbox should not be checked
643
953
  * Example #3: And the "#agree" checkbox should be checked
@@ -647,17 +957,16 @@ ThenF(/^(the )*"([^"]*)?" field should( not)* contain "([^"]*)?"$/, async functi
647
957
  *
648
958
  */
649
959
  ThenF(/^(the )*"([^"]*)?" checkbox should( not)* be checked$/, async function (theCase, checkbox, notCase) {
650
- const isChecked = await this.page.locator(checkbox).isChecked();
651
- if (notCase) {
652
- assertF.ok(!isChecked, `Checkbox "${checkbox}" should NOT be checked but it is.`);
653
- } else {
654
- assertF.ok(isChecked, `Checkbox "${checkbox}" should be checked but it is not.`);
655
- }
960
+ await assertChoice(this, checkbox, 'checkbox', !notCase);
656
961
  });
657
962
 
658
963
  /**
659
964
  * Assert that a checkbox is or is not checked.
660
965
  *
966
+ * The checkbox is named by a CSS selector, the exact text of its label, its
967
+ * name, its id or its value; one that is not found within 5 seconds fails
968
+ * the step plainly.
969
+ *
661
970
  * Alternate phrasing of "should be / should not be checked".
662
971
  *
663
972
  * Example #1: Then the "#remember-me" checkbox is checked
@@ -669,17 +978,16 @@ ThenF(/^(the )*"([^"]*)?" checkbox should( not)* be checked$/, async function (t
669
978
  *
670
979
  */
671
980
  ThenF(/^(the )*"([^"]*)?" checkbox is( not)* checked$/, async function (theCase, checkbox, notCase) {
672
- const isChecked = await this.page.locator(checkbox).isChecked();
673
- if (notCase) {
674
- assertF.ok(!isChecked, `Checkbox "${checkbox}" should NOT be checked but it is.`);
675
- } else {
676
- assertF.ok(isChecked, `Checkbox "${checkbox}" should be checked but it is not.`);
677
- }
981
+ await assertChoice(this, checkbox, 'checkbox', !notCase);
678
982
  });
679
983
 
680
984
  /**
681
985
  * Assert that a named checkbox should or should not be checked.
682
986
  *
987
+ * The checkbox is named by a CSS selector, the exact text of its label, its
988
+ * name, its id or its value; one that is not found within 5 seconds fails
989
+ * the step plainly.
990
+ *
683
991
  * Reverse phrasing — "checkbox <selector>" instead of "<selector> checkbox".
684
992
  *
685
993
  * Example #1: Then the checkbox "#privacy-policy" should be checked
@@ -691,17 +999,16 @@ ThenF(/^(the )*"([^"]*)?" checkbox is( not)* checked$/, async function (theCase,
691
999
  *
692
1000
  */
693
1001
  ThenF(/^(the )*checkbox "([^"]*)?" should( not)* be checked$/, async function (theCase, checkbox, notCase) {
694
- const isChecked = await this.page.locator(checkbox).isChecked();
695
- if (notCase) {
696
- assertF.ok(!isChecked, `Checkbox "${checkbox}" should NOT be checked but it is.`);
697
- } else {
698
- assertF.ok(isChecked, `Checkbox "${checkbox}" should be checked but it is not.`);
699
- }
1002
+ await assertChoice(this, checkbox, 'checkbox', !notCase);
700
1003
  });
701
1004
 
702
1005
  /**
703
1006
  * Assert that a named checkbox is or is not checked.
704
1007
  *
1008
+ * The checkbox is named by a CSS selector, the exact text of its label, its
1009
+ * name, its id or its value; one that is not found within 5 seconds fails
1010
+ * the step plainly.
1011
+ *
705
1012
  * Reverse phrasing using "is / is not".
706
1013
  *
707
1014
  * Example #1: Then the checkbox "#remember-me" is checked
@@ -713,29 +1020,25 @@ ThenF(/^(the )*checkbox "([^"]*)?" should( not)* be checked$/, async function (t
713
1020
  *
714
1021
  */
715
1022
  ThenF(/^(the )*checkbox "([^"]*)?" is( not)* checked$/, async function (theCase, checkbox, notCase) {
716
- const isChecked = await this.page.locator(checkbox).isChecked();
717
- if (notCase) {
718
- assertF.ok(!isChecked, `Checkbox "${checkbox}" should NOT be checked but it is.`);
719
- } else {
720
- assertF.ok(isChecked, `Checkbox "${checkbox}" should be checked but it is not.`);
721
- }
1023
+ await assertChoice(this, checkbox, 'checkbox', !notCase);
722
1024
  });
723
1025
 
724
1026
  /**
725
1027
  * Assert that a radio button should or should not be selected.
726
1028
  *
1029
+ * The radio button is named by a CSS selector, the exact text of its label,
1030
+ * its id or its value (not its name, which its whole group shares); one that
1031
+ * is not found within 5 seconds fails the step plainly.
1032
+ *
727
1033
  * Example #1: Then the radio button "#gender-male" should be selected
728
1034
  * Example #2: Then the radio button "#gender-female" should not be selected
729
1035
  * Example #3: Then the radio button ".option-1" should be selected
1036
+ * Example #4: Then the radio button "Monthly" should be selected
1037
+ * Example #5: And the radio button "#plan-yearly" should not be selected
730
1038
  *
731
1039
  */
732
1040
  ThenF(/^(the )*radio button "([^"]*)?" should( not)* be selected$/, async function (theCase, radioButton, notCase) {
733
- const isChecked = await this.page.locator(radioButton).isChecked();
734
- if (notCase) {
735
- assertF.ok(!isChecked, `Radio button "${radioButton}" should NOT be selected but it is.`);
736
- } else {
737
- assertF.ok(isChecked, `Radio button "${radioButton}" should be selected but it is not.`);
738
- }
1041
+ await assertChoice(this, radioButton, 'radio', !notCase);
739
1042
  });
740
1043
 
741
1044
  /**
@@ -752,17 +1055,32 @@ ThenF(/^(the )*radio button "([^"]*)?" should( not)* be selected$/, async functi
752
1055
  *
753
1056
  */
754
1057
  ThenF(/^(the )*radio button with value "([^"]*)?" should( not)* be selected$/, async function (theCase, radioValue, notCase) {
755
- const isChecked = await this.page.locator(`input[type="radio"][value="${radioValue}"]`).first().isChecked();
756
- if (notCase) {
757
- assertF.ok(!isChecked, `Radio button with value "${radioValue}" should NOT be selected but it is.`);
758
- } else {
759
- assertF.ok(isChecked, `Radio button with value "${radioValue}" should be selected but it is not.`);
1058
+ const loc = this.page.locator(`input[type="radio"][value="${String(radioValue).replace(/["\\]/g, '\\$&')}"]`).first();
1059
+ try {
1060
+ await loc.waitFor({ state: 'attached', timeout: 5000 });
1061
+ } catch (e) {
1062
+ if (!isTimeout(e)) throw e;
1063
+ throw failure(this.page, `No radio button with the value "${radioValue}" was found after 5 seconds.`, {
1064
+ hint: 'the step reads the value attribute of the radio buttons, not their label; to name one by its label, use: the radio button "<label>" should be selected',
1065
+ });
1066
+ }
1067
+ const isChecked = await loc.isChecked();
1068
+ if (isChecked !== !notCase) {
1069
+ throw failure(this.page, notCase
1070
+ ? `The radio button with the value "${radioValue}" is selected, but it should not be.`
1071
+ : `The radio button with the value "${radioValue}" is not selected.`, {
1072
+ hint: 'check that the step before it selects the radio button you expect.',
1073
+ });
760
1074
  }
761
1075
  });
762
1076
 
763
1077
  /**
764
1078
  * Assert that the radio button is or is not selected.
765
1079
  *
1080
+ * The radio button is named by a CSS selector, the exact text of its label,
1081
+ * its id or its value (not its name, which its whole group shares); one that
1082
+ * is not found within 5 seconds fails the step plainly.
1083
+ *
766
1084
  * Alternate phrasing using "is / is not selected".
767
1085
  *
768
1086
  * Example #1: Then the "#gender-male" radio button is selected
@@ -774,10 +1092,5 @@ ThenF(/^(the )*radio button with value "([^"]*)?" should( not)* be selected$/, a
774
1092
  *
775
1093
  */
776
1094
  ThenF(/^(the )*"([^"]*)?" radio button is( not)* selected$/, async function (theCase, radioButton, notCase) {
777
- const isChecked = await this.page.locator(radioButton).isChecked();
778
- if (notCase) {
779
- assertF.ok(!isChecked, `Radio button "${radioButton}" should NOT be selected but it is.`);
780
- } else {
781
- assertF.ok(isChecked, `Radio button "${radioButton}" should be selected but it is not.`);
782
- }
1095
+ await assertChoice(this, radioButton, 'radio', !notCase);
783
1096
  });