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
@@ -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, setChecked } = 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 setChecked(loc, action === 'check', { 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,12 @@ 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. One whose input is covered by a part of its own label (a toggle
718
+ * switch) or hidden (a box drawn by its label) is clicked through its label.
719
+ *
720
+ * The checkbox is named by a CSS selector, the exact text of its label, its
721
+ * name, its id or its value; one that is not found within 5 seconds fails
722
+ * the step plainly.
432
723
  *
433
724
  * Example #1: When I check the checkbox "#agree"
434
725
  * Example #2: When I check the checkbox "input[name=newsletter]"
@@ -438,11 +729,16 @@ When(/^(I |we )*clear the select "([^"]*)"$/, async function (pronoun, sel) {
438
729
  *
439
730
  */
440
731
  When(/^(I |we )*check the checkbox "([^"]*)"$/, async function (pronoun, sel) {
441
- await this.page.locator(sel).first().check();
732
+ await setChoice(this, sel, 'checkbox', 'check');
442
733
  });
443
734
 
444
735
  /**
445
- * Uncheck a CSS-addressed checkbox.
736
+ * Uncheck a checkbox. One whose input is covered by a part of its own label (a toggle
737
+ * switch) or hidden (a box drawn by its label) is clicked through its label.
738
+ *
739
+ * The checkbox is named by a CSS selector, the exact text of its label, its
740
+ * name, its id or its value; one that is not found within 5 seconds fails
741
+ * the step plainly.
446
742
  *
447
743
  * Example #1: When I uncheck the checkbox "#newsletter"
448
744
  * Example #2: When I uncheck the checkbox "input[name=marketing]"
@@ -452,11 +748,16 @@ When(/^(I |we )*check the checkbox "([^"]*)"$/, async function (pronoun, sel) {
452
748
  *
453
749
  */
454
750
  When(/^(I |we )*uncheck the checkbox "([^"]*)"$/, async function (pronoun, sel) {
455
- await this.page.locator(sel).first().uncheck();
751
+ await setChoice(this, sel, 'checkbox', 'uncheck');
456
752
  });
457
753
 
458
754
  /**
459
- * Select a CSS-addressed radio button.
755
+ * Select a radio button. One whose input is covered by a part of its own label (a toggle
756
+ * switch) or hidden (a box drawn by its label) is clicked through its label.
757
+ *
758
+ * The radio button is named by a CSS selector, the exact text of its label,
759
+ * its id or its value (not its name, which its whole group shares); one that
760
+ * is not found within 5 seconds fails the step plainly.
460
761
  *
461
762
  * Example #1: When I choose the radio button "#gender-male"
462
763
  * Example #2: When I choose the radio button "input[value=premium]"
@@ -466,7 +767,7 @@ When(/^(I |we )*uncheck the checkbox "([^"]*)"$/, async function (pronoun, sel)
466
767
  *
467
768
  */
468
769
  When(/^(I |we )*choose the radio button "([^"]*)"$/, async function (pronoun, sel) {
469
- await this.page.locator(sel).first().check();
770
+ await setChoice(this, sel, 'radio', 'check');
470
771
  });
471
772
 
472
773
  // Note: "the radio button :sel should be selected" is already provided by
@@ -474,7 +775,10 @@ When(/^(I |we )*choose the radio button "([^"]*)"$/, async function (pronoun, se
474
775
  // ambiguous step matches.
475
776
 
476
777
  /**
477
- * Fill a CSS-addressed input/textarea with a value.
778
+ * Fill an input or a textarea with a value. The field is named by a CSS
779
+ * selector, the exact text of its label, its name or its id; one that is not
780
+ * found within 5 seconds, or that is hidden, disabled or read-only, fails the
781
+ * step plainly.
478
782
  *
479
783
  * Example #1: When I fill in the field "#username" with "alice"
480
784
  * Example #2: When I fill in the field "input[name=email]" with "alice@example.com"
@@ -484,7 +788,8 @@ When(/^(I |we )*choose the radio button "([^"]*)"$/, async function (pronoun, se
484
788
  *
485
789
  */
486
790
  When(/^(I |we )*fill in the field "([^"]*)" with "([^"]*)"$/, async function (pronoun, sel, value) {
487
- await this.page.locator(sel).first().fill(value);
791
+ const loc = await locateControl(this.page, sel, 'field');
792
+ await fillLocator(this.page, loc, value, sel);
488
793
  });
489
794
 
490
795
  /**
@@ -510,10 +815,12 @@ Given('browser validation for the form {string} is disabled', async function (se
510
815
  /**
511
816
  * Fill paired `<input type=date>` + `<input type=time>` controls for a label.
512
817
  *
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.
818
+ * The field is named by the exact text of its label or of the legend of its
819
+ * fieldset (white space and letter case aside), and only its own inputs are
820
+ * filled: the one inside the label, the one the label is for, or the ones
821
+ * that follow the label before the next field. An input whose name or
822
+ * aria-label contains that text is found too. When an input is not found
823
+ * within 5 seconds the step fails and fills nothing.
517
824
  *
518
825
  * Example #1: When I fill in the datetime field "Start" with date "2026-05-08" and time "10:00"
519
826
  * Example #2: When I fill in the datetime field "Departure" with date "2026-12-31" and time "23:59"
@@ -561,8 +868,9 @@ When(/^(I |we )*fill in the time part of the datetime field "([^"]*)" with "([^"
561
868
  /**
562
869
  * Fill the `start` half of a date-range pair.
563
870
  *
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.
871
+ * The range is named by the exact text of its label or of the legend of its
872
+ * fieldset; of its inputs, the ones whose name, id or aria-label contains
873
+ * "start" are filled.
566
874
  *
567
875
  * Example #1: When I fill in the start datetime field "Event" with date "2026-05-08" and time "10:00"
568
876
  * Example #2: When I fill in the start datetime field "Trip" with date "2026-12-31" and time "08:00"
@@ -581,8 +889,9 @@ When(/^(I |we )*fill in the start datetime field "([^"]*)" with date "([^"]*)" a
581
889
  /**
582
890
  * Fill the `end` half of a date-range pair.
583
891
  *
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.
892
+ * The range is named by the exact text of its label or of the legend of its
893
+ * fieldset; of its inputs, the ones whose name, id or aria-label contains
894
+ * "end" are filled.
586
895
  *
587
896
  * Example #1: When I fill in the end datetime field "Event" with date "2026-05-09" and time "18:00"
588
897
  * Example #2: When I fill in the end datetime field "Trip" with date "2027-01-07" and time "20:00"
@@ -638,6 +947,10 @@ ThenF(/^(the )*"([^"]*)?" field should( not)* contain "([^"]*)?"$/, async functi
638
947
  /**
639
948
  * Assert that a checkbox should or should not be checked.
640
949
  *
950
+ * The checkbox is named by a CSS selector, the exact text of its label, its
951
+ * name, its id or its value; one that is not found within 5 seconds fails
952
+ * the step plainly.
953
+ *
641
954
  * Example #1: Then the "#privacy-policy" checkbox should be checked
642
955
  * Example #2: Then the "#newsletter" checkbox should not be checked
643
956
  * Example #3: And the "#agree" checkbox should be checked
@@ -647,17 +960,16 @@ ThenF(/^(the )*"([^"]*)?" field should( not)* contain "([^"]*)?"$/, async functi
647
960
  *
648
961
  */
649
962
  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
- }
963
+ await assertChoice(this, checkbox, 'checkbox', !notCase);
656
964
  });
657
965
 
658
966
  /**
659
967
  * Assert that a checkbox is or is not checked.
660
968
  *
969
+ * The checkbox is named by a CSS selector, the exact text of its label, its
970
+ * name, its id or its value; one that is not found within 5 seconds fails
971
+ * the step plainly.
972
+ *
661
973
  * Alternate phrasing of "should be / should not be checked".
662
974
  *
663
975
  * Example #1: Then the "#remember-me" checkbox is checked
@@ -669,17 +981,16 @@ ThenF(/^(the )*"([^"]*)?" checkbox should( not)* be checked$/, async function (t
669
981
  *
670
982
  */
671
983
  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
- }
984
+ await assertChoice(this, checkbox, 'checkbox', !notCase);
678
985
  });
679
986
 
680
987
  /**
681
988
  * Assert that a named checkbox should or should not be checked.
682
989
  *
990
+ * The checkbox is named by a CSS selector, the exact text of its label, its
991
+ * name, its id or its value; one that is not found within 5 seconds fails
992
+ * the step plainly.
993
+ *
683
994
  * Reverse phrasing — "checkbox <selector>" instead of "<selector> checkbox".
684
995
  *
685
996
  * Example #1: Then the checkbox "#privacy-policy" should be checked
@@ -691,17 +1002,16 @@ ThenF(/^(the )*"([^"]*)?" checkbox is( not)* checked$/, async function (theCase,
691
1002
  *
692
1003
  */
693
1004
  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
- }
1005
+ await assertChoice(this, checkbox, 'checkbox', !notCase);
700
1006
  });
701
1007
 
702
1008
  /**
703
1009
  * Assert that a named checkbox is or is not checked.
704
1010
  *
1011
+ * The checkbox is named by a CSS selector, the exact text of its label, its
1012
+ * name, its id or its value; one that is not found within 5 seconds fails
1013
+ * the step plainly.
1014
+ *
705
1015
  * Reverse phrasing using "is / is not".
706
1016
  *
707
1017
  * Example #1: Then the checkbox "#remember-me" is checked
@@ -713,29 +1023,25 @@ ThenF(/^(the )*checkbox "([^"]*)?" should( not)* be checked$/, async function (t
713
1023
  *
714
1024
  */
715
1025
  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
- }
1026
+ await assertChoice(this, checkbox, 'checkbox', !notCase);
722
1027
  });
723
1028
 
724
1029
  /**
725
1030
  * Assert that a radio button should or should not be selected.
726
1031
  *
1032
+ * The radio button is named by a CSS selector, the exact text of its label,
1033
+ * its id or its value (not its name, which its whole group shares); one that
1034
+ * is not found within 5 seconds fails the step plainly.
1035
+ *
727
1036
  * Example #1: Then the radio button "#gender-male" should be selected
728
1037
  * Example #2: Then the radio button "#gender-female" should not be selected
729
1038
  * Example #3: Then the radio button ".option-1" should be selected
1039
+ * Example #4: Then the radio button "Monthly" should be selected
1040
+ * Example #5: And the radio button "#plan-yearly" should not be selected
730
1041
  *
731
1042
  */
732
1043
  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
- }
1044
+ await assertChoice(this, radioButton, 'radio', !notCase);
739
1045
  });
740
1046
 
741
1047
  /**
@@ -752,17 +1058,32 @@ ThenF(/^(the )*radio button "([^"]*)?" should( not)* be selected$/, async functi
752
1058
  *
753
1059
  */
754
1060
  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.`);
1061
+ const loc = this.page.locator(`input[type="radio"][value="${String(radioValue).replace(/["\\]/g, '\\$&')}"]`).first();
1062
+ try {
1063
+ await loc.waitFor({ state: 'attached', timeout: 5000 });
1064
+ } catch (e) {
1065
+ if (!isTimeout(e)) throw e;
1066
+ throw failure(this.page, `No radio button with the value "${radioValue}" was found after 5 seconds.`, {
1067
+ 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',
1068
+ });
1069
+ }
1070
+ const isChecked = await loc.isChecked();
1071
+ if (isChecked !== !notCase) {
1072
+ throw failure(this.page, notCase
1073
+ ? `The radio button with the value "${radioValue}" is selected, but it should not be.`
1074
+ : `The radio button with the value "${radioValue}" is not selected.`, {
1075
+ hint: 'check that the step before it selects the radio button you expect.',
1076
+ });
760
1077
  }
761
1078
  });
762
1079
 
763
1080
  /**
764
1081
  * Assert that the radio button is or is not selected.
765
1082
  *
1083
+ * The radio button is named by a CSS selector, the exact text of its label,
1084
+ * its id or its value (not its name, which its whole group shares); one that
1085
+ * is not found within 5 seconds fails the step plainly.
1086
+ *
766
1087
  * Alternate phrasing using "is / is not selected".
767
1088
  *
768
1089
  * Example #1: Then the "#gender-male" radio button is selected
@@ -774,10 +1095,5 @@ ThenF(/^(the )*radio button with value "([^"]*)?" should( not)* be selected$/, a
774
1095
  *
775
1096
  */
776
1097
  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
- }
1098
+ await assertChoice(this, radioButton, 'radio', !notCase);
783
1099
  });