webship-js 2.0.10 → 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 (248) hide show
  1. package/.circleci/config.yml +10 -1
  2. package/.drone.yml +7 -7
  3. package/.github/ISSUE_TEMPLATE/issue.md +37 -0
  4. package/.github/PULL_REQUEST_TEMPLATE.md +24 -0
  5. package/.github/workflows/github-actions.yml +101 -4
  6. package/.gitlab-ci.yml +9 -4
  7. package/.harness/webship-js-pipeline.yml +5 -6
  8. package/.semaphore/semaphore.yml +6 -9
  9. package/.teamcity/settings.kts +7 -6
  10. package/.travis.yml +6 -1
  11. package/AGENTS.md +1 -1
  12. package/CLAUDE.md +69 -24
  13. package/Jenkinsfile +5 -3
  14. package/README.md +13 -1
  15. package/azure-pipelines.yml +17 -8
  16. package/bamboo-specs/bamboo.yml +9 -15
  17. package/bin/generate-reports.js +51 -7
  18. package/bin/init-webship.js +127 -23
  19. package/bitbucket-pipelines.yml +5 -1
  20. package/buildspec.yml +6 -7
  21. package/cloudbuild.yaml +28 -12
  22. package/codefresh.yml +6 -6
  23. package/cucumber.js +46 -11
  24. package/docs/00-quick-start.md +38 -7
  25. package/docs/02-bbr-smart-waits.md +21 -10
  26. package/docs/03-selector-registry.md +24 -0
  27. package/docs/04-step-reference.md +53 -27
  28. package/docs/05-web-first-assertions.md +6 -0
  29. package/docs/07-auth-state.md +1 -1
  30. package/docs/08-clock-mocking.md +21 -2
  31. package/docs/09-api-testing.md +40 -2
  32. package/docs/10-accessibility.md +2 -0
  33. package/docs/11-debugging.md +24 -1
  34. package/docs/12-ai-agent-guide.md +8 -1
  35. package/docs/13-faq.md +75 -1
  36. package/docs/14-recipes-cookbook.md +2 -0
  37. package/docs/15-tag-conventions.md +5 -1
  38. package/docs/16-ci-cd.md +161 -124
  39. package/docs/README.md +5 -5
  40. package/docs/advanced-screenshots.md +3 -1
  41. package/docs/api-step-definitions.md +16 -2
  42. package/docs/global-settings.md +70 -18
  43. package/docs/install-webship-js/ddev-webship-js.md +3 -0
  44. package/docs/install-webship-js.md +16 -2
  45. package/docs/step-definitions/then-i-should-see.md +14 -1
  46. package/docs/step-definitions/then-item-checkbox.md +2 -0
  47. package/docs/step-definitions/when-i-fill.md +4 -0
  48. package/docs/step-definitions/when-i-select-option-select-list.md +2 -0
  49. package/examples/a11y-legacy-widget.html +34 -0
  50. package/examples/auth-state.html +42 -0
  51. package/examples/choice-controls.html +29 -0
  52. package/examples/clock.html +33 -0
  53. package/examples/datetime-fields.html +52 -0
  54. package/examples/downloads/webship-archive.zip +0 -0
  55. package/examples/downloads/webship-notes.txt +4 -0
  56. package/examples/downloads/webship-report.csv +4 -0
  57. package/examples/downloads.html +16 -0
  58. package/examples/element-selector-hint.html +16 -0
  59. package/examples/element-viewport.html +42 -0
  60. package/examples/field-states.html +27 -0
  61. package/examples/field-types.html +98 -0
  62. package/examples/fill-in-empty.html +26 -0
  63. package/examples/fill-unreachable.html +27 -0
  64. package/examples/iframe-inner.html +20 -0
  65. package/examples/iframe-nested.html +16 -0
  66. package/examples/iframe-newsletter.html +29 -0
  67. package/examples/iframe-order.html +26 -0
  68. package/examples/iframe-outer.html +15 -0
  69. package/examples/iframe.html +21 -0
  70. package/examples/javascript-errors.html +35 -0
  71. package/examples/links.html +1 -0
  72. package/examples/metatags.html +18 -0
  73. package/examples/mouse-and-pointer.html +83 -0
  74. package/examples/multi-value-fields.html +54 -0
  75. package/examples/native-dialogs.html +8 -0
  76. package/examples/network.html +83 -0
  77. package/examples/registered-names.html +15 -0
  78. package/examples/scroll-horizontal.html +50 -0
  79. package/examples/select-by-label.html +33 -0
  80. package/examples/selectors-position.html +29 -0
  81. package/examples/settle-budget.html +21 -0
  82. package/examples/sorted-tables.html +38 -0
  83. package/examples/storage.html +57 -0
  84. package/examples/text-matching.html +48 -0
  85. package/examples/text-order.html +25 -0
  86. package/examples/touch.html +22 -0
  87. package/examples/viewport-size.html +24 -0
  88. package/examples/viewport-top.html +36 -0
  89. package/examples/wait-conditions.html +69 -0
  90. package/examples/web-first.html +99 -0
  91. package/package.json +24 -2
  92. package/playwright.config.ts +3 -1
  93. package/tests/assets/catalog.xml +19 -0
  94. package/tests/assets/feed-namespaced.xml +13 -0
  95. package/tests/assets/sitemap.xml +14 -0
  96. package/tests/assets/webship-site-expected.yaml +21 -0
  97. package/tests/assets/webship-site.schema.json +46 -0
  98. package/tests/assets/webship-site.yaml +21 -0
  99. package/tests/check-api-launch-url.js +106 -0
  100. package/tests/check-assets.js +103 -0
  101. package/tests/check-attachments.js +105 -0
  102. package/tests/check-breakpoints.js +117 -0
  103. package/tests/check-clock.js +143 -0
  104. package/tests/check-config.js +90 -0
  105. package/tests/check-context.js +215 -0
  106. package/tests/check-dry-run.js +104 -0
  107. package/tests/check-examples.js +241 -0
  108. package/tests/check-exit-report.js +141 -0
  109. package/tests/check-javascript-errors.js +105 -0
  110. package/tests/check-must-fail.js +85 -0
  111. package/tests/check-paths.js +82 -0
  112. package/tests/check-report.js +119 -0
  113. package/tests/check-scaffold.js +246 -0
  114. package/tests/check-screenshots.js +117 -0
  115. package/tests/check-settle-verbs.js +137 -0
  116. package/tests/check-time-limit.js +104 -0
  117. package/tests/check-video.js +156 -0
  118. package/tests/check-world.js +167 -0
  119. package/tests/features/a11y.feature +18 -0
  120. package/tests/features/api-base-url.feature +25 -0
  121. package/tests/features/api-form-data.feature +18 -0
  122. package/tests/features/api-json-paths.feature +24 -0
  123. package/tests/features/api-response-contains.feature +21 -0
  124. package/tests/features/api-response-header-presence.feature +17 -0
  125. package/tests/features/api-response-header.feature +17 -0
  126. package/tests/features/api-saved-placeholders.feature +37 -0
  127. package/tests/features/api-step-definitions-individual.feature +1 -1
  128. package/tests/features/api-tables.feature +40 -0
  129. package/tests/features/auth-state.feature +32 -0
  130. package/tests/features/breakpoints.feature +25 -0
  131. package/tests/features/choice-controls.feature +35 -0
  132. package/tests/features/clock.feature +27 -0
  133. package/tests/features/complete-api-testing-examples.feature +1 -1
  134. package/tests/features/cookie.feature +9 -0
  135. package/tests/features/datetime-field-lookup.feature +29 -0
  136. package/tests/features/dialog.feature +27 -0
  137. package/tests/features/element-selector-hint.feature +14 -0
  138. package/tests/features/element.feature +47 -0
  139. package/tests/features/field-state.feature +21 -0
  140. package/tests/features/field.feature +104 -0
  141. package/tests/features/file-download.feature +64 -0
  142. package/tests/features/fill-in-empty-value.feature +41 -0
  143. package/tests/features/fill-reachable.feature +13 -0
  144. package/tests/features/iframe-nested.feature +43 -0
  145. package/tests/features/iframe.feature +83 -0
  146. package/tests/features/javascript-tolerated-errors.feature +20 -0
  147. package/tests/features/javascript.feature +47 -0
  148. package/tests/features/link.feature +11 -0
  149. package/tests/features/metatag.feature +38 -0
  150. package/tests/features/modal-open.feature +13 -0
  151. package/tests/features/mouse-and-pointer.feature +86 -0
  152. package/tests/features/multi-value-field-lookup.feature +30 -0
  153. package/tests/features/network-mocking.feature +80 -0
  154. package/tests/features/registered-names.feature +14 -0
  155. package/tests/features/responsive.feature +27 -0
  156. package/tests/features/scroll-horizontal.feature +55 -0
  157. package/tests/features/select-by-label.feature +31 -0
  158. package/tests/features/selector-files.feature +14 -0
  159. package/tests/features/selectors-position.feature +41 -0
  160. package/tests/features/selectors-table-header.feature +35 -0
  161. package/tests/features/settle-budget.feature +11 -0
  162. package/tests/features/sorted-tables.feature +19 -0
  163. package/tests/features/storage-quoted-values.feature +26 -0
  164. package/tests/features/storage.feature +98 -0
  165. package/tests/features/test--then--i-see-locator.feature +13 -0
  166. package/tests/features/test--then--i-should--see-text-in-element.feature +9 -1
  167. package/tests/features/test--then--the-field-should-contain-value.feature +8 -0
  168. package/tests/features/text-matching.feature +38 -0
  169. package/tests/features/text-order.feature +14 -0
  170. package/tests/features/touch.feature +21 -0
  171. package/tests/features/video.feature +1 -0
  172. package/tests/features/viewport-top.feature +13 -0
  173. package/tests/features/wait.feature +89 -0
  174. package/tests/features/web-first.feature +100 -0
  175. package/tests/features/xml-namespaces.feature +34 -0
  176. package/tests/features/xml.feature +96 -0
  177. package/tests/features/yaml.feature +75 -0
  178. package/tests/must-fail/api-json-paths.feature +21 -0
  179. package/tests/must-fail/api-response-contains.feature +23 -0
  180. package/tests/must-fail/api-response-header-presence.feature +17 -0
  181. package/tests/must-fail/api-response-header.feature +21 -0
  182. package/tests/must-fail/api-without-base-url.feature +11 -0
  183. package/tests/must-fail/assertions.feature +96 -0
  184. package/tests/must-fail/breakpoints.feature +15 -0
  185. package/tests/must-fail/choice-controls.feature +25 -0
  186. package/tests/must-fail/clock.feature +11 -0
  187. package/tests/must-fail/datetime-field.feature +10 -0
  188. package/tests/must-fail/element-selector-hint.feature +17 -0
  189. package/tests/must-fail/field-state.feature +20 -0
  190. package/tests/must-fail/fill-field.feature +30 -0
  191. package/tests/must-fail/iframe-text.feature +17 -0
  192. package/tests/must-fail/modal-open.feature +26 -0
  193. package/tests/must-fail/multi-value-field.feature +18 -0
  194. package/tests/must-fail/registered-names.feature +25 -0
  195. package/tests/must-fail/select-list.feature +15 -0
  196. package/tests/must-fail/selector-files.feature +10 -0
  197. package/tests/must-fail/sorted-tables.feature +20 -0
  198. package/tests/must-fail/storage-before-a-page.feature +13 -0
  199. package/tests/must-fail/text-matching.feature +16 -0
  200. package/tests/must-fail/text-order.feature +15 -0
  201. package/tests/must-fail/viewport-top.feature +20 -0
  202. package/tests/must-fail/waits.feature +51 -0
  203. package/tests/must-fail/yaml-numbers.feature +48 -0
  204. package/tests/reports/README.md +2 -2
  205. package/tests/step-definitions/a11y.steps.js +36 -23
  206. package/tests/step-definitions/action.steps.js +22 -8
  207. package/tests/step-definitions/api.steps.js +349 -67
  208. package/tests/step-definitions/assertion.steps.js +327 -63
  209. package/tests/step-definitions/auth.steps.js +15 -18
  210. package/tests/step-definitions/clock.steps.js +22 -0
  211. package/tests/step-definitions/debug.steps.js +8 -0
  212. package/tests/step-definitions/dialog.steps.js +9 -2
  213. package/tests/step-definitions/element.steps.js +135 -18
  214. package/tests/step-definitions/field.steps.js +523 -80
  215. package/tests/step-definitions/file-download.steps.js +74 -10
  216. package/tests/step-definitions/form.steps.js +76 -29
  217. package/tests/step-definitions/iframe.steps.js +89 -29
  218. package/tests/step-definitions/input.steps.js +26 -7
  219. package/tests/step-definitions/javascript.steps.js +64 -22
  220. package/tests/step-definitions/modal.steps.js +79 -13
  221. package/tests/step-definitions/navigation.steps.js +14 -0
  222. package/tests/step-definitions/network.steps.js +15 -5
  223. package/tests/step-definitions/response.steps.js +6 -4
  224. package/tests/step-definitions/responsive.steps.js +26 -33
  225. package/tests/step-definitions/screenshot.steps.js +26 -9
  226. package/tests/step-definitions/scroll.steps.js +20 -0
  227. package/tests/step-definitions/selectors.steps.js +104 -51
  228. package/tests/step-definitions/storage.steps.js +41 -16
  229. package/tests/step-definitions/table.steps.js +81 -6
  230. package/tests/step-definitions/video.steps.js +52 -55
  231. package/tests/step-definitions/wait.steps.js +209 -54
  232. package/tests/step-definitions/web-first.steps.js +69 -35
  233. package/tests/step-definitions/webship.js +807 -128
  234. package/tests/step-definitions/xml.steps.js +124 -28
  235. package/tests/step-definitions/yaml.steps.js +90 -46
  236. package/.scratch/commit.txt +0 -14
  237. package/.scratch/docs.py +0 -42
  238. package/.scratch/echo-server.js +0 -8
  239. package/.scratch/echo.js +0 -35
  240. package/.scratch/echo.pid +0 -1
  241. package/.scratch/features/cookies.feature +0 -22
  242. package/.scratch/http.pid +0 -1
  243. package/.scratch/https.pid +0 -1
  244. package/.scratch/issue.md +0 -49
  245. package/.scratch/one.js +0 -2
  246. package/.scratch/one.json +0 -280
  247. package/.scratch/patch.py +0 -163
  248. package/.scratch/pr.md +0 -30
@@ -4,6 +4,7 @@
4
4
 
5
5
  const { Given, When, Then } = require('@cucumber/cucumber');
6
6
  const assert = require('assert');
7
+ const { friendly, failure, fillLocator, humanize, isTimeout } = require('./webship');
7
8
 
8
9
  // Resolve a field by label, name, id, or selector.
9
10
  function fieldLocator(page, field) {
@@ -27,6 +28,206 @@ async function getField(page, field) {
27
28
  return loc;
28
29
  }
29
30
 
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;
114
+ }
115
+
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.
118
+ async function datetimePart(page, label, type, half) {
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;
195
+ try {
196
+ checked = await loc.isChecked({ timeout: 5000 });
197
+ } catch (e) {
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.`,
227
+ });
228
+ }
229
+ }
230
+
30
231
  /**
31
232
  * Assert a field's current value is the empty string.
32
233
  *
@@ -91,21 +292,59 @@ Then('the field {string} should not exist', async function (field) {
91
292
  assert.strictEqual(await loc.count(), 0, `Field "${field}" should not exist.`);
92
293
  });
93
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
+
94
310
  /**
95
- * 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.
96
315
  *
97
316
  * Example #1: Then the field "username" should have "enabled" state
98
317
  * Example #2: Then the field "Email" should have "disabled" state
99
318
  * Example #3: And the field "#search" should have "enabled" state
100
319
  * Example #4: Then the field "Password" should have "disabled" state
101
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
102
323
  *
103
324
  */
104
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
+ }
105
334
  const loc = await getField(this.page, field);
106
- const disabled = await loc.isDisabled();
107
- if (state === 'disabled') assert.ok(disabled, `Field "${field}" should be disabled.`);
108
- 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
+ }
109
348
  });
110
349
 
111
350
  /**
@@ -142,8 +381,77 @@ Then('the field {string} should not be required', async function (field) {
142
381
  assert.ok(req === null && aria !== 'true', `Field "${field}" should not be required.`);
143
382
  });
144
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
+
145
446
  /**
146
- * 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.
147
455
  *
148
456
  * Example #1: When I fill in the multi-value field "tags" with the following values:
149
457
  * | bdd |
@@ -162,15 +470,32 @@ Then('the field {string} should not be required', async function (field) {
162
470
  * | tech |
163
471
  * | devops |
164
472
  * | testing |
473
+ * Example #6: When I fill in the multi-value field "Phone numbers" with the following values:
474
+ * | 0790000000 |
475
+ * | 0791111111 |
165
476
  *
166
477
  */
167
478
  When(/^(I |we )*fill in the multi-value field "([^"]*)" with the following values:$/, async function (pronoun, field, table) {
168
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
+ }
169
497
  for (let i = 0; i < values.length; i++) {
170
- const inputs = this.page.locator(`[name="${field}[${i}]"], [name="${field}[]"]`);
171
- const count = await inputs.count();
172
- const target = count > i ? inputs.nth(i) : inputs.first();
173
- await target.fill(values[i]);
498
+ await fillLocator(this.page, this.page.locator(paths[i]), values[i], `${field} (value ${i + 1})`);
174
499
  }
175
500
  });
176
501
 
@@ -207,6 +532,12 @@ Then('the color field {string} should have the value {string}', async function (
207
532
  /**
208
533
  * Fill a CKEditor / contenteditable rich-text field with HTML.
209
534
  *
535
+ * The field is found by the name or the id of its form control, by the text
536
+ * of its label, or by the accessible name of its editable area
537
+ * (`aria-label` / `aria-labelledby`). The editable area that is filled is the
538
+ * one that belongs to that field, so a page with several editors is filled in
539
+ * the right place. A page with a single editor is filled whatever the name.
540
+ *
210
541
  * Example #1: When I fill in the WYSIWYG field "body" with the "Hello world"
211
542
  * Example #2: When I fill in the WYSIWYG field "Description" with the "<strong>Bold</strong>"
212
543
  * Example #3: And we fill in the WYSIWYG field "content" with the "Plain paragraph"
@@ -215,13 +546,77 @@ Then('the color field {string} should have the value {string}', async function (
215
546
  *
216
547
  */
217
548
  When(/^(I |we )*fill in the WYSIWYG field "([^"]*)" with the "([^"]*)"$/, async function (pronoun, field, value) {
218
- // CKEditor5/4 fallback: try contenteditable.
219
- await this.page.evaluate(({ field, value }) => {
220
- const editor = document.querySelector(`[name="${field}"], #${field}`);
221
- if (editor && 'value' in editor) editor.value = value;
222
- const ce = document.querySelector('.ck-editor__editable, [contenteditable="true"]');
223
- if (ce) ce.innerHTML = `<p>${value}</p>`;
549
+ const filled = await this.page.evaluate(({ field, value }) => {
550
+ const EDITABLE = '.ck-editor__editable, [contenteditable="true"], [contenteditable=""]';
551
+ const html = `<p>${value}</p>`;
552
+ const byId = (id) => (id ? document.getElementById(id) : null);
553
+ const sameText = (el) => (el.textContent || '').replace(/\s+/g, ' ').trim() === field;
554
+
555
+ // 1. What the name points at: a form control by its name or id, a label
556
+ // by its text, or an editable area by its accessible name.
557
+ let source = Array.from(document.getElementsByName(field))[0] || byId(field);
558
+ if (!source) {
559
+ const label = Array.from(document.querySelectorAll('label')).find(sameText);
560
+ if (label) source = label.control || byId(label.getAttribute('for'));
561
+ }
562
+ if (!source) {
563
+ source = Array.from(document.querySelectorAll(EDITABLE)).find((el) => {
564
+ if (el.getAttribute('aria-label') === field) return true;
565
+ const ids = (el.getAttribute('aria-labelledby') || '').split(/\s+/).filter(Boolean);
566
+ return ids.some((id) => { const named = byId(id); return named && sameText(named); });
567
+ }) || null;
568
+ }
569
+
570
+ // 2. The editable area that belongs to it. An editor renders right after
571
+ // the form control it replaces; failing that, it is the only editable
572
+ // area of the closest wrapper around the control.
573
+ let editable = null;
574
+ if (source && source.matches(EDITABLE)) {
575
+ editable = source;
576
+ } else if (source) {
577
+ for (let el = source.nextElementSibling; el && !editable; el = el.nextElementSibling) {
578
+ if (el.matches('label, input, textarea, select')) break;
579
+ editable = el.matches(EDITABLE) ? el : el.querySelector(EDITABLE);
580
+ }
581
+ for (let box = source.parentElement; box && box !== document.body && !editable; box = box.parentElement) {
582
+ const inside = box.querySelectorAll(EDITABLE);
583
+ if (inside.length === 1) editable = inside[0];
584
+ if (inside.length > 1) break;
585
+ }
586
+ } else {
587
+ const all = document.querySelectorAll(EDITABLE);
588
+ if (all.length === 1) editable = all[0];
589
+ }
590
+
591
+ const control = source && source !== editable && 'value' in source ? source : null;
592
+ if (control) {
593
+ control.value = value;
594
+ control.dispatchEvent(new Event('input', { bubbles: true }));
595
+ control.dispatchEvent(new Event('change', { bubbles: true }));
596
+ }
597
+ if (editable) {
598
+ const ck5 = editable.ckeditorInstance;
599
+ if (ck5 && typeof ck5.setData === 'function') ck5.setData(html);
600
+ else {
601
+ editable.innerHTML = html;
602
+ editable.dispatchEvent(new Event('input', { bubbles: true }));
603
+ }
604
+ }
605
+ // CKEditor 4 edits inside an iframe and keeps its instances by control id or name.
606
+ const registry = window.CKEDITOR && window.CKEDITOR.instances;
607
+ const ck4 = registry && control ? (registry[control.id] || registry[control.name]) : null;
608
+ if (ck4 && typeof ck4.setData === 'function') ck4.setData(html);
609
+
610
+ return Boolean(control || editable || ck4);
224
611
  }, { field, value });
612
+ if (!filled) {
613
+ throw friendly({
614
+ action: 'fill in the WYSIWYG field',
615
+ target: field,
616
+ cause: 'no form control with that name or id, no label with that text and no editable area with that accessible name was found',
617
+ hint: 'use the name or the id of the textarea behind the editor, the text of its label, or the aria-label of the editable area.',
618
+ });
619
+ }
225
620
  });
226
621
 
227
622
  /**
@@ -319,7 +714,11 @@ When(/^(I |we )*clear the select "([^"]*)"$/, async function (pronoun, sel) {
319
714
  });
320
715
 
321
716
  /**
322
- * 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.
323
722
  *
324
723
  * Example #1: When I check the checkbox "#agree"
325
724
  * Example #2: When I check the checkbox "input[name=newsletter]"
@@ -329,11 +728,15 @@ When(/^(I |we )*clear the select "([^"]*)"$/, async function (pronoun, sel) {
329
728
  *
330
729
  */
331
730
  When(/^(I |we )*check the checkbox "([^"]*)"$/, async function (pronoun, sel) {
332
- await this.page.locator(sel).first().check();
731
+ await setChoice(this, sel, 'checkbox', 'check');
333
732
  });
334
733
 
335
734
  /**
336
- * 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.
337
740
  *
338
741
  * Example #1: When I uncheck the checkbox "#newsletter"
339
742
  * Example #2: When I uncheck the checkbox "input[name=marketing]"
@@ -343,11 +746,15 @@ When(/^(I |we )*check the checkbox "([^"]*)"$/, async function (pronoun, sel) {
343
746
  *
344
747
  */
345
748
  When(/^(I |we )*uncheck the checkbox "([^"]*)"$/, async function (pronoun, sel) {
346
- await this.page.locator(sel).first().uncheck();
749
+ await setChoice(this, sel, 'checkbox', 'uncheck');
347
750
  });
348
751
 
349
752
  /**
350
- * 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.
351
758
  *
352
759
  * Example #1: When I choose the radio button "#gender-male"
353
760
  * Example #2: When I choose the radio button "input[value=premium]"
@@ -357,7 +764,7 @@ When(/^(I |we )*uncheck the checkbox "([^"]*)"$/, async function (pronoun, sel)
357
764
  *
358
765
  */
359
766
  When(/^(I |we )*choose the radio button "([^"]*)"$/, async function (pronoun, sel) {
360
- await this.page.locator(sel).first().check();
767
+ await setChoice(this, sel, 'radio', 'check');
361
768
  });
362
769
 
363
770
  // Note: "the radio button :sel should be selected" is already provided by
@@ -365,7 +772,10 @@ When(/^(I |we )*choose the radio button "([^"]*)"$/, async function (pronoun, se
365
772
  // ambiguous step matches.
366
773
 
367
774
  /**
368
- * 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.
369
779
  *
370
780
  * Example #1: When I fill in the field "#username" with "alice"
371
781
  * Example #2: When I fill in the field "input[name=email]" with "alice@example.com"
@@ -375,7 +785,8 @@ When(/^(I |we )*choose the radio button "([^"]*)"$/, async function (pronoun, se
375
785
  *
376
786
  */
377
787
  When(/^(I |we )*fill in the field "([^"]*)" with "([^"]*)"$/, async function (pronoun, sel, value) {
378
- 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);
379
790
  });
380
791
 
381
792
  /**
@@ -401,6 +812,13 @@ Given('browser validation for the form {string} is disabled', async function (se
401
812
  /**
402
813
  * Fill paired `<input type=date>` + `<input type=time>` controls for a label.
403
814
  *
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.
821
+ *
404
822
  * Example #1: When I fill in the datetime field "Start" with date "2026-05-08" and time "10:00"
405
823
  * Example #2: When I fill in the datetime field "Departure" with date "2026-12-31" and time "23:59"
406
824
  * Example #3: And we fill in the datetime field "Pickup" with date "2026-07-04" and time "08:30"
@@ -409,9 +827,11 @@ Given('browser validation for the form {string} is disabled', async function (se
409
827
  *
410
828
  */
411
829
  When(/^(I |we )*fill in the datetime field "([^"]*)" with date "([^"]*)" and time "([^"]*)"$/, async function (pronoun, label, date, time) {
412
- const root = this.page.locator(`label:has-text("${label}")`).first();
413
- await this.page.locator(`input[type="date"][name*="${label}"], label:has-text("${label}") ~ * input[type="date"]`).first().fill(date).catch(() => {});
414
- await this.page.locator(`input[type="time"][name*="${label}"], label:has-text("${label}") ~ * input[type="time"]`).first().fill(time).catch(() => {});
830
+ // Both inputs are found before either is filled: a failure leaves the form as it was.
831
+ const dateInput = await datetimePart(this.page, label, 'date');
832
+ const timeInput = await datetimePart(this.page, label, 'time');
833
+ await dateInput.fill(date);
834
+ await timeInput.fill(time);
415
835
  });
416
836
 
417
837
  /**
@@ -425,7 +845,7 @@ When(/^(I |we )*fill in the datetime field "([^"]*)" with date "([^"]*)" and tim
425
845
  *
426
846
  */
427
847
  When(/^(I |we )*fill in the date part of the datetime field "([^"]*)" with "([^"]*)"$/, async function (pronoun, label, date) {
428
- await this.page.locator(`label:has-text("${label}") ~ * input[type="date"], input[type="date"][name*="${label}"]`).first().fill(date);
848
+ await (await datetimePart(this.page, label, 'date')).fill(date);
429
849
  });
430
850
 
431
851
  /**
@@ -439,12 +859,16 @@ When(/^(I |we )*fill in the date part of the datetime field "([^"]*)" with "([^"
439
859
  *
440
860
  */
441
861
  When(/^(I |we )*fill in the time part of the datetime field "([^"]*)" with "([^"]*)"$/, async function (pronoun, label, time) {
442
- await this.page.locator(`label:has-text("${label}") ~ * input[type="time"], input[type="time"][name*="${label}"]`).first().fill(time);
862
+ await (await datetimePart(this.page, label, 'time')).fill(time);
443
863
  });
444
864
 
445
865
  /**
446
866
  * Fill the `start` half of a date-range pair.
447
867
  *
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.
871
+ *
448
872
  * Example #1: When I fill in the start datetime field "Event" with date "2026-05-08" and time "10:00"
449
873
  * Example #2: When I fill in the start datetime field "Trip" with date "2026-12-31" and time "08:00"
450
874
  * Example #3: And we fill in the start datetime field "Window" with date "2026-07-04" and time "12:00"
@@ -453,13 +877,19 @@ When(/^(I |we )*fill in the time part of the datetime field "([^"]*)" with "([^"
453
877
  *
454
878
  */
455
879
  When(/^(I |we )*fill in the start datetime field "([^"]*)" with date "([^"]*)" and time "([^"]*)"$/, async function (pronoun, label, date, time) {
456
- await this.page.locator(`input[name*="${label}"][name*="start"][type="date"]`).first().fill(date).catch(() => {});
457
- await this.page.locator(`input[name*="${label}"][name*="start"][type="time"]`).first().fill(time).catch(() => {});
880
+ const dateInput = await datetimePart(this.page, label, 'date', 'start');
881
+ const timeInput = await datetimePart(this.page, label, 'time', 'start');
882
+ await dateInput.fill(date);
883
+ await timeInput.fill(time);
458
884
  });
459
885
 
460
886
  /**
461
887
  * Fill the `end` half of a date-range pair.
462
888
  *
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.
892
+ *
463
893
  * Example #1: When I fill in the end datetime field "Event" with date "2026-05-09" and time "18:00"
464
894
  * Example #2: When I fill in the end datetime field "Trip" with date "2027-01-07" and time "20:00"
465
895
  * Example #3: And we fill in the end datetime field "Window" with date "2026-07-04" and time "18:00"
@@ -468,8 +898,10 @@ When(/^(I |we )*fill in the start datetime field "([^"]*)" with date "([^"]*)" a
468
898
  *
469
899
  */
470
900
  When(/^(I |we )*fill in the end datetime field "([^"]*)" with date "([^"]*)" and time "([^"]*)"$/, async function (pronoun, label, date, time) {
471
- await this.page.locator(`input[name*="${label}"][name*="end"][type="date"]`).first().fill(date).catch(() => {});
472
- await this.page.locator(`input[name*="${label}"][name*="end"][type="time"]`).first().fill(time).catch(() => {});
901
+ const dateInput = await datetimePart(this.page, label, 'date', 'end');
902
+ const timeInput = await datetimePart(this.page, label, 'time', 'end');
903
+ await dateInput.fill(date);
904
+ await timeInput.fill(time);
473
905
  });
474
906
 
475
907
  // ---------------------------------------------------------------------------
@@ -479,24 +911,28 @@ When(/^(I |we )*fill in the end datetime field "([^"]*)" with date "([^"]*)" and
479
911
 
480
912
  const { Then: ThenF } = require('@cucumber/cucumber');
481
913
  const assertF = require('assert');
482
- const { getLocatorText: getLocatorTextF } = require('./webship');
914
+ const { getLocatorText: getLocatorTextF, locateByLabelOrSelector: locateByLabelOrSelectorF, friendly: friendlyF } = require('./webship');
483
915
 
484
916
  /**
485
917
  * Assert that a form field contains or does not contain specific text.
486
918
  *
919
+ * The field is named by the exact text of its label, or by a CSS selector.
920
+ *
487
921
  * Example #1: Then the "Username" field should contain "John Smith"
488
922
  * Example #2: Then the "#username" field should not contain "John Smith"
489
923
  * Example #3: And the "Email" field should contain "jon@example.com"
924
+ * Example #4: Then the "[name=username]" field should contain "John Smith"
925
+ * Example #5: And the "input.email" field should not contain "example.org"
490
926
  *
491
927
  */
492
928
  ThenF(/^(the )*"([^"]*)?" field should( not)* contain "([^"]*)?"$/, async function (theCase, field, notCase, expectedText) {
493
- let selector = field;
494
- if (!field.startsWith('#') && !field.startsWith('.')) {
495
- const forAttr = await this.page.getByText(field, { exact: true }).getAttribute('for').catch(() => null);
496
- if (forAttr) selector = '#' + forAttr;
929
+ const loc = await locateByLabelOrSelectorF(this.page, field, 5000);
930
+ if (!loc) {
931
+ throw friendlyF({
932
+ message: `The field "${field}" was not found on the page after 5 seconds.`,
933
+ hint: `"${field}" is read as the exact text of a label, else as a CSS selector such as "#username" or "[name=username]".`,
934
+ });
497
935
  }
498
- const loc = this.page.locator(selector).first();
499
- await loc.waitFor({ timeout: 5000 });
500
936
  const content = await getLocatorTextF(loc);
501
937
  if (notCase) {
502
938
  assertF.ok(!content.includes(expectedText), `Field should NOT contain "${expectedText}" but it does.`);
@@ -508,6 +944,10 @@ ThenF(/^(the )*"([^"]*)?" field should( not)* contain "([^"]*)?"$/, async functi
508
944
  /**
509
945
  * Assert that a checkbox should or should not be checked.
510
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
+ *
511
951
  * Example #1: Then the "#privacy-policy" checkbox should be checked
512
952
  * Example #2: Then the "#newsletter" checkbox should not be checked
513
953
  * Example #3: And the "#agree" checkbox should be checked
@@ -517,17 +957,16 @@ ThenF(/^(the )*"([^"]*)?" field should( not)* contain "([^"]*)?"$/, async functi
517
957
  *
518
958
  */
519
959
  ThenF(/^(the )*"([^"]*)?" checkbox should( not)* be checked$/, async function (theCase, checkbox, notCase) {
520
- const isChecked = await this.page.locator(checkbox).isChecked();
521
- if (notCase) {
522
- assertF.ok(!isChecked, `Checkbox "${checkbox}" should NOT be checked but it is.`);
523
- } else {
524
- assertF.ok(isChecked, `Checkbox "${checkbox}" should be checked but it is not.`);
525
- }
960
+ await assertChoice(this, checkbox, 'checkbox', !notCase);
526
961
  });
527
962
 
528
963
  /**
529
964
  * Assert that a checkbox is or is not checked.
530
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
+ *
531
970
  * Alternate phrasing of "should be / should not be checked".
532
971
  *
533
972
  * Example #1: Then the "#remember-me" checkbox is checked
@@ -539,17 +978,16 @@ ThenF(/^(the )*"([^"]*)?" checkbox should( not)* be checked$/, async function (t
539
978
  *
540
979
  */
541
980
  ThenF(/^(the )*"([^"]*)?" checkbox is( not)* checked$/, async function (theCase, checkbox, notCase) {
542
- const isChecked = await this.page.locator(checkbox).isChecked();
543
- if (notCase) {
544
- assertF.ok(!isChecked, `Checkbox "${checkbox}" should NOT be checked but it is.`);
545
- } else {
546
- assertF.ok(isChecked, `Checkbox "${checkbox}" should be checked but it is not.`);
547
- }
981
+ await assertChoice(this, checkbox, 'checkbox', !notCase);
548
982
  });
549
983
 
550
984
  /**
551
985
  * Assert that a named checkbox should or should not be checked.
552
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
+ *
553
991
  * Reverse phrasing — "checkbox <selector>" instead of "<selector> checkbox".
554
992
  *
555
993
  * Example #1: Then the checkbox "#privacy-policy" should be checked
@@ -561,17 +999,16 @@ ThenF(/^(the )*"([^"]*)?" checkbox is( not)* checked$/, async function (theCase,
561
999
  *
562
1000
  */
563
1001
  ThenF(/^(the )*checkbox "([^"]*)?" should( not)* be checked$/, async function (theCase, checkbox, notCase) {
564
- const isChecked = await this.page.locator(checkbox).isChecked();
565
- if (notCase) {
566
- assertF.ok(!isChecked, `Checkbox "${checkbox}" should NOT be checked but it is.`);
567
- } else {
568
- assertF.ok(isChecked, `Checkbox "${checkbox}" should be checked but it is not.`);
569
- }
1002
+ await assertChoice(this, checkbox, 'checkbox', !notCase);
570
1003
  });
571
1004
 
572
1005
  /**
573
1006
  * Assert that a named checkbox is or is not checked.
574
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
+ *
575
1012
  * Reverse phrasing using "is / is not".
576
1013
  *
577
1014
  * Example #1: Then the checkbox "#remember-me" is checked
@@ -583,29 +1020,25 @@ ThenF(/^(the )*checkbox "([^"]*)?" should( not)* be checked$/, async function (t
583
1020
  *
584
1021
  */
585
1022
  ThenF(/^(the )*checkbox "([^"]*)?" is( not)* checked$/, async function (theCase, checkbox, notCase) {
586
- const isChecked = await this.page.locator(checkbox).isChecked();
587
- if (notCase) {
588
- assertF.ok(!isChecked, `Checkbox "${checkbox}" should NOT be checked but it is.`);
589
- } else {
590
- assertF.ok(isChecked, `Checkbox "${checkbox}" should be checked but it is not.`);
591
- }
1023
+ await assertChoice(this, checkbox, 'checkbox', !notCase);
592
1024
  });
593
1025
 
594
1026
  /**
595
1027
  * Assert that a radio button should or should not be selected.
596
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
+ *
597
1033
  * Example #1: Then the radio button "#gender-male" should be selected
598
1034
  * Example #2: Then the radio button "#gender-female" should not be selected
599
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
600
1038
  *
601
1039
  */
602
1040
  ThenF(/^(the )*radio button "([^"]*)?" should( not)* be selected$/, async function (theCase, radioButton, notCase) {
603
- const isChecked = await this.page.locator(radioButton).isChecked();
604
- if (notCase) {
605
- assertF.ok(!isChecked, `Radio button "${radioButton}" should NOT be selected but it is.`);
606
- } else {
607
- assertF.ok(isChecked, `Radio button "${radioButton}" should be selected but it is not.`);
608
- }
1041
+ await assertChoice(this, radioButton, 'radio', !notCase);
609
1042
  });
610
1043
 
611
1044
  /**
@@ -622,17 +1055,32 @@ ThenF(/^(the )*radio button "([^"]*)?" should( not)* be selected$/, async functi
622
1055
  *
623
1056
  */
624
1057
  ThenF(/^(the )*radio button with value "([^"]*)?" should( not)* be selected$/, async function (theCase, radioValue, notCase) {
625
- const isChecked = await this.page.locator(`input[type="radio"][value="${radioValue}"]`).first().isChecked();
626
- if (notCase) {
627
- assertF.ok(!isChecked, `Radio button with value "${radioValue}" should NOT be selected but it is.`);
628
- } else {
629
- 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
+ });
630
1074
  }
631
1075
  });
632
1076
 
633
1077
  /**
634
1078
  * Assert that the radio button is or is not selected.
635
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
+ *
636
1084
  * Alternate phrasing using "is / is not selected".
637
1085
  *
638
1086
  * Example #1: Then the "#gender-male" radio button is selected
@@ -644,10 +1092,5 @@ ThenF(/^(the )*radio button with value "([^"]*)?" should( not)* be selected$/, a
644
1092
  *
645
1093
  */
646
1094
  ThenF(/^(the )*"([^"]*)?" radio button is( not)* selected$/, async function (theCase, radioButton, notCase) {
647
- const isChecked = await this.page.locator(radioButton).isChecked();
648
- if (notCase) {
649
- assertF.ok(!isChecked, `Radio button "${radioButton}" should NOT be selected but it is.`);
650
- } else {
651
- assertF.ok(isChecked, `Radio button "${radioButton}" should be selected but it is not.`);
652
- }
1095
+ await assertChoice(this, radioButton, 'radio', !notCase);
653
1096
  });