webship-js 2.0.1 → 2.0.2

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 (41) hide show
  1. package/bin/generate-reports.js +191 -0
  2. package/bin/init-webship.js +343 -0
  3. package/bin/postinstall.js +8 -74
  4. package/cucumber.js +59 -1
  5. package/examples/diffy/baseline.html +54 -0
  6. package/examples/diffy/changed.html +63 -0
  7. package/examples/diffy/index.html +52 -0
  8. package/examples/index.html +6 -0
  9. package/examples/test--when--i-additionally-select.html +27 -0
  10. package/package.json +10 -4
  11. package/tests/features/diffy/test--diffy-01-example-demo.feature +22 -0
  12. package/tests/features/diffy/test--diffy-02-all-steps.feature +52 -0
  13. package/tests/features/diffy/test--diffy-03-real-api.feature +21 -0
  14. package/tests/features/test--then--i-save-screenshot.feature +33 -0
  15. package/tests/features/test--then--i-see-locator.feature +320 -0
  16. package/tests/features/test--then--i-should-see-n-elements.feature +24 -0
  17. package/tests/features/test--then--print-current-url-and-response.feature +21 -0
  18. package/tests/features/test--when--i-additionally-select.feature +30 -0
  19. package/tests/features/test--when--i-follow.feature +22 -0
  20. package/tests/selectors/back-end-selectors.json +13 -0
  21. package/tests/selectors/front-end-selectors.json +16 -0
  22. package/tests/selectors/homepage-selectors.json +13 -0
  23. package/tests/step-definitions/webship-api.js +234 -41
  24. package/tests/step-definitions/webship-screenshot.js +427 -0
  25. package/tests/step-definitions/webship-selectors.js +961 -0
  26. package/tests/step-definitions/webship.js +829 -230
  27. package/tests/step-definitions-diffy/README.md +329 -0
  28. package/tests/step-definitions-diffy/mock-diffy-api/server.js +84 -0
  29. package/tests/step-definitions-diffy/webship-diffy-mock.js +31 -0
  30. package/tests/step-definitions-diffy/webship-diffy.js +472 -0
  31. package/generate-reports.js +0 -22
  32. package/required/cucumber.js +0 -37
  33. package/required/generate-reports.js +0 -22
  34. package/required/package.json +0 -18
  35. package/required/playwright.config.ts +0 -37
  36. package/required/tests/features/README.md +0 -1
  37. package/required/tests/features/check-homepage.feature +0 -8
  38. package/required/tests/reports/README.md +0 -1
  39. package/required/tests/step-definitions/README.md +0 -1
  40. package/required/tests/step-definitions/custom.js +0 -4
  41. package/required/tsconfig.json +0 -12
@@ -0,0 +1,961 @@
1
+ 'use strict';
2
+
3
+ // ---------------------------------------------------------------------------
4
+ // Webship-JS — Selectors step definitions
5
+ //
6
+ // Uses Playwright Locator API (locator.boundingBox, locator.isVisible,
7
+ // locator.isHidden, locator.click) to assert named page components are
8
+ // positioned relative to each other: above, below, left, right, inside,
9
+ // outside, over, not over. Also asserts visibility, focus, and click.
10
+ //
11
+ // Advanced selector system: named CSS and XPath selectors + layout components
12
+ // + viewport breakpoints — all configured under one `selectors` block, loaded
13
+ // from worldParameters, JSON files, or registered inline via steps.
14
+ //
15
+ // Configuration: resolved per-scenario with this priority:
16
+ // 1. process.env.WEBSHIP_SELECTORS_* (CI / shell — highest)
17
+ // 2. cucumber.js worldParameters.selectors.* (project-level defaults)
18
+ // 3. built-in defaults
19
+ //
20
+ // Supported env vars / worldParameters keys:
21
+ // WEBSHIP_SELECTORS_OFFSET offset scroll offset in px, default 60
22
+ // WEBSHIP_SELECTORS_BREAKPOINTS (JSON string) named breakpoints
23
+ //
24
+ // Unified config block (worldParameters.selectors):
25
+ // selectors: {
26
+ // filesPath: './tests/selectors/', // base path for selector files
27
+ // files: ['front-end-selectors.json', 'back-end-selectors.json'],
28
+ // css: {
29
+ // 'page header': 'header.page-header',
30
+ // 'main nav': 'nav[role="navigation"]',
31
+ // },
32
+ // xpath: {
33
+ // 'page title': '//h1[contains(@class,"page-title")]',
34
+ // },
35
+ // offset: 60, // scroll offset (px)
36
+ // breakpoints: {
37
+ // xs: { width: 375, height: 667 }, // phone portrait
38
+ // sm: { width: 576, height: 800 }, // large phone / phablet
39
+ // md: { width: 768, height: 1024 }, // tablet portrait
40
+ // lg: { width: 992, height: 768 }, // small laptop / tablet landscape
41
+ // xl: { width: 1200, height: 900, default: true }, // desktop
42
+ // xxl: { width: 1400, height: 900 }, // wide desktop / HD
43
+ // xxxl: { width: 1920, height: 1080 }, // Full HD / large monitor
44
+ // },
45
+ // }
46
+ //
47
+ // Selector files (JSON only) have the structure:
48
+ // {
49
+ // "css": { "breadcrumb": ".breadcrumb", "logo": "header .logo" },
50
+ // "xpath": { "page title": "//h1[contains(@class,'title')]" }
51
+ // }
52
+ //
53
+ // One unified CSS registry: layout components and element locators share
54
+ // worldParameters.selectors.css. Register in bulk via "Given I define css selectors:"
55
+ // or one-at-a-time via "When I add ... css selector". Same for XPath via `xpath`.
56
+ // ---------------------------------------------------------------------------
57
+
58
+ const { Given, When, Then, Before } = require('@cucumber/cucumber');
59
+ const fs = require('fs');
60
+ const path = require('path');
61
+
62
+ function parseFile(filePath) {
63
+ const ext = path.extname(filePath).toLowerCase();
64
+ if (ext !== '.json') {
65
+ throw new Error(`Selector files must be JSON (got "${ext}" for "${filePath}").`);
66
+ }
67
+ return JSON.parse(fs.readFileSync(filePath, 'utf8'));
68
+ }
69
+
70
+ // ---------------------------------------------------------------------------
71
+ // Config
72
+ // ---------------------------------------------------------------------------
73
+ function pick(envVal, paramVal, fallback) {
74
+ if (envVal !== undefined && envVal !== '') return envVal;
75
+ if (paramVal !== undefined && paramVal !== '' && paramVal !== null) return paramVal;
76
+ return fallback;
77
+ }
78
+
79
+ function resolveConfig(parameters) {
80
+ const s = (parameters && parameters.selectors) || {};
81
+
82
+ let breakpoints = s.breakpoints || {
83
+ xs: { width: 375, height: 667 },
84
+ sm: { width: 576, height: 800 },
85
+ md: { width: 768, height: 1024 },
86
+ lg: { width: 992, height: 768 },
87
+ xl: { width: 1200, height: 900, default: true },
88
+ xxl: { width: 1400, height: 900 },
89
+ xxxl: { width: 1920, height: 1080 },
90
+ };
91
+
92
+ if (process.env.WEBSHIP_SELECTORS_BREAKPOINTS) {
93
+ try { breakpoints = JSON.parse(process.env.WEBSHIP_SELECTORS_BREAKPOINTS); } catch { /* ignore */ }
94
+ }
95
+
96
+ return {
97
+ offset: parseInt(pick(process.env.WEBSHIP_SELECTORS_OFFSET, s.offset, '60'), 10),
98
+ breakpoints,
99
+ filesPath: s.filesPath || '',
100
+ files: Array.isArray(s.files) ? s.files : [],
101
+ css: Object.assign({}, s.css || {}),
102
+ xpath: Object.assign({}, s.xpath || {}),
103
+ };
104
+ }
105
+
106
+ // ---------------------------------------------------------------------------
107
+ // Per-scenario registries
108
+ // ---------------------------------------------------------------------------
109
+ Before(function () {
110
+ const cfg = resolveConfig(this.parameters);
111
+ this.__selectorsConfig = cfg;
112
+ this.__selectorsCss = Object.assign({}, cfg.css);
113
+ this.__selectorsXpath = Object.assign({}, cfg.xpath);
114
+
115
+ // Auto-load selector files specified in worldParameters.
116
+ for (const file of cfg.files) {
117
+ const filePath = cfg.filesPath ? path.join(cfg.filesPath, file) : file;
118
+ try {
119
+ const parsed = parseFile(filePath);
120
+ if (parsed && parsed.css) Object.assign(this.__selectorsCss, parsed.css);
121
+ if (parsed && parsed.xpath) Object.assign(this.__selectorsXpath, parsed.xpath);
122
+ } catch (e) {
123
+ throw new Error(`Selectors: failed to load selector file "${filePath}": ${e.message}`);
124
+ }
125
+ }
126
+ });
127
+
128
+ // ---------------------------------------------------------------------------
129
+ // Selector resolution helpers
130
+ // ---------------------------------------------------------------------------
131
+
132
+ /**
133
+ * Resolve a named selector to a Playwright-compatible selector string.
134
+ * Priority: css registry → xpath registry.
135
+ */
136
+ function resolveSelector(world, name) {
137
+ const trimmed = name.trim();
138
+
139
+ if (world.__selectorsCss && world.__selectorsCss[trimmed]) {
140
+ return world.__selectorsCss[trimmed];
141
+ }
142
+
143
+ if (world.__selectorsXpath && world.__selectorsXpath[trimmed]) {
144
+ const xp = world.__selectorsXpath[trimmed];
145
+ return xp.startsWith('xpath=') ? xp : `xpath=${xp}`;
146
+ }
147
+
148
+ throw new Error(`Selectors: unknown selector "${trimmed}". Register it with "Given I define css selectors:", "When I add ... css selector", "When I add ... xpath selector", or worldParameters.selectors.`);
149
+ }
150
+
151
+ function parseNames(text) {
152
+ return text.split(/\s*(?:,|and)\s*/).map(s => s.trim()).filter(Boolean);
153
+ }
154
+
155
+ // ---------------------------------------------------------------------------
156
+ // Geometry helpers using Playwright locator.boundingBox()
157
+ // ---------------------------------------------------------------------------
158
+ async function getGeometry(page, selector) {
159
+ const loc = page.locator(selector).first();
160
+ try { await loc.scrollIntoViewIfNeeded({ timeout: 3000 }); } catch { /* may already be visible */ }
161
+
162
+ const box = await loc.boundingBox();
163
+ if (!box) return null;
164
+
165
+ const scroll = await page.evaluate(() => ({ x: window.scrollX, y: window.scrollY }));
166
+
167
+ // z-index still requires evaluate — no native Playwright API for computed style.
168
+ const zIndex = await loc.evaluate(el => {
169
+ let z = 0;
170
+ let node = el;
171
+ while (node && node !== document.body) {
172
+ const cs = window.getComputedStyle(node);
173
+ if (cs.position !== 'static' && cs.zIndex !== 'auto') {
174
+ const n = parseInt(cs.zIndex, 10);
175
+ if (!isNaN(n)) z = n;
176
+ }
177
+ node = node.parentElement;
178
+ }
179
+ return z;
180
+ });
181
+
182
+ return { top: box.y + scroll.y, left: box.x + scroll.x, width: box.width, height: box.height, zIndex };
183
+ }
184
+
185
+ async function assertPosition(page, position, c1Name, c1Sel, c2Name, c2Sel) {
186
+ const g1 = await getGeometry(page, c1Sel);
187
+ if (!g1) throw new Error(`Cannot get bounding box for "${c1Name}" (${c1Sel}) — element not visible`);
188
+ const g2 = await getGeometry(page, c2Sel);
189
+ if (!g2) throw new Error(`Cannot get bounding box for "${c2Name}" (${c2Sel}) — element not visible`);
190
+
191
+ let pass = false;
192
+ switch (position) {
193
+ case 'above': pass = g2.top >= g1.top + g1.height; break;
194
+ case 'below': pass = g1.top >= g2.top + g2.height; break;
195
+ case 'left': pass = g1.left + g1.width <= g2.left; break;
196
+ case 'right': pass = g1.left >= g2.left + g2.width; break;
197
+ case 'inside':
198
+ pass = g1.top >= g2.top && g1.top + g1.height <= g2.top + g2.height &&
199
+ g1.left >= g2.left && g1.left + g1.width <= g2.left + g2.width;
200
+ break;
201
+ case 'outside':
202
+ pass = g1.top <= g2.top && g1.top + g1.height >= g2.top + g2.height &&
203
+ g1.left <= g2.left && g1.left + g1.width >= g2.left + g2.width;
204
+ break;
205
+ case 'over': {
206
+ const intersects = !(g1.left >= g2.left + g2.width || g1.left + g1.width <= g2.left ||
207
+ g1.top >= g2.top + g2.height || g1.top + g1.height <= g2.top);
208
+ pass = intersects && g1.zIndex <= g2.zIndex;
209
+ break;
210
+ }
211
+ }
212
+ return pass;
213
+ }
214
+
215
+ async function dispatcher(world, position, subjectText, othersText, negate = false) {
216
+ const subjects = parseNames(subjectText);
217
+ const others = parseNames(othersText);
218
+ const errors = [];
219
+ for (const subjectName of subjects) {
220
+ const subjectSel = resolveSelector(world, subjectName);
221
+ for (const otherName of others) {
222
+ const otherSel = resolveSelector(world, otherName);
223
+ try {
224
+ const pass = await assertPosition(world.page, position, subjectName, subjectSel, otherName, otherSel);
225
+ if (!pass && !negate) errors.push(`"${subjectName}" is not ${position} "${otherName}"`);
226
+ else if (pass && negate) errors.push(`"${subjectName}" is ${position} "${otherName}" (expected not to be)`);
227
+ } catch (e) { errors.push(e.message); }
228
+ }
229
+ }
230
+ if (errors.length > 0) throw new Error(errors.join('\n'));
231
+ }
232
+
233
+ // ===========================================================================
234
+ // STEP DEFINITIONS — Advanced selector system
235
+ // ===========================================================================
236
+
237
+ /**
238
+ * Register a named CSS selector at runtime.
239
+ *
240
+ * Example #1: When I add "mobile logo" selector for "header img#logo" css selector
241
+ * Example #2: When I add "breadcrumb" selector for ".breadcrumb" css selector
242
+ * Example #3: When I add "breadcrumb first link" selector for ".breadcrumb li:nth-child(1) a" css selector
243
+ * Example #4: When I add "cta button" selector for ".cta .btn-primary" css selector
244
+ * Example #5: When I add "page header" selector for "header.page-header" css selector
245
+ * Example #6: When I add "main nav" selector for "nav[role='navigation']" css selector
246
+ * Example #7: When I add "hero image" selector for ".hero img" css selector
247
+ * Example #8: When I add "footer links" selector for "footer a" css selector
248
+ * Example #9: When I add "search field" selector for "input[type='search']" css selector
249
+ * Example #10: When I add "submit button" selector for "button[type='submit']" css selector
250
+ *
251
+ * Advanced:
252
+ * Example #11: Later override same name → latest wins:
253
+ * When I add "target" selector for "h1" css selector
254
+ * And I add "target" selector for "ul" css selector
255
+ * Example #12: Component (CSS) takes precedence over CSS registry with same name:
256
+ * When I add "shared" selector for "ul" css selector
257
+ * And I define css selectors:
258
+ * | shared | h1 |
259
+ * Example #13: Combine with XPath registration and use together:
260
+ * When I add "cta" selector for ".cta" css selector
261
+ * And I add "cta link" selector for "//a[contains(@class,'cta')]" xpath selector
262
+ */
263
+ When(/^(I |we )*add "([^"]*)" selector for "([^"]*)" css selector$/, function (pronounCase, selectorName, cssSelector) {
264
+ if (!selectorName || !cssSelector) throw new Error('Selectors: selector name and CSS selector must not be empty.');
265
+ this.__selectorsCss[selectorName.trim()] = cssSelector.trim();
266
+ });
267
+
268
+ /**
269
+ * Register a named XPath selector at runtime.
270
+ *
271
+ * Example #1: When I add "page title" selector for "//h1[contains(@class,'page-header')]" xpath selector
272
+ * Example #2: When I add "Dashboard" selector for "//*[@id='navbar-link-admin-dashboard']" xpath selector
273
+ * Example #3: When I add "Vertical orientation" selector for "//*[@id='navbar-item--2-tray']/div/div[2]/div/button" xpath selector
274
+ * Example #4: When I add "admin menu" selector for "//nav[contains(@class,'admin-menu')]" xpath selector
275
+ * Example #5: When I add "first table row" selector for "//table/tbody/tr[1]" xpath selector
276
+ * Example #6: When I add "active tab" selector for "//li[contains(@class,'active')]/a" xpath selector
277
+ * Example #7: When I add "error message" selector for "//*[contains(@class,'error')]" xpath selector
278
+ * Example #8: When I add "site name" selector for "//a[contains(@class,'site-name')]" xpath selector
279
+ * Example #9: When I add "user menu" selector for "//*[@id='user-menu']" xpath selector
280
+ * Example #10: When I add "language switcher" selector for "//ul[contains(@class,'language-switcher')]" xpath selector
281
+ *
282
+ * Advanced:
283
+ * Example #11: Axis predicates — first match only (locator.first() is applied):
284
+ * When I add "first row" selector for "//table//tr[1]" xpath selector
285
+ * Example #12: Text contains — name by rendered label:
286
+ * When I add "login link" selector for "//a[contains(normalize-space(.),'Login')]" xpath selector
287
+ * Example #13: Attribute + position — last nav item:
288
+ * When I add "last nav item" selector for "//nav[@role='navigation']//a[last()]" xpath selector
289
+ */
290
+ When(/^(I |we )*add "([^"]*)" selector for "([^"]*)" xpath selector$/, function (pronounCase, selectorName, xpathSelector) {
291
+ if (!selectorName || !xpathSelector) throw new Error('Selectors: selector name and XPath selector must not be empty.');
292
+ this.__selectorsXpath[selectorName.trim()] = xpathSelector.trim();
293
+ });
294
+
295
+ /**
296
+ * Load CSS and XPath selectors from a JSON file.
297
+ * File path is relative to worldParameters.selectors.filesPath.
298
+ *
299
+ * Example #1: When I add selectors from "selectors.json" file
300
+ * Example #2: When I add selectors from "admin-selectors.json" file
301
+ * Example #3: When I add selectors from "frontend.json" file
302
+ * Example #4: When I add selectors from "theme-selectors.json" file
303
+ * Example #5: When I add selectors from "components.json" file
304
+ * Example #6: When we add selectors from "shared.json" file
305
+ * Example #7: When add selectors from "backend.json" file
306
+ * Example #8: When I add selectors from "page-selectors.json" file
307
+ * Example #9: When I add selectors from "module-selectors.json" file
308
+ * Example #10: When we add selectors from "mobile.json" file
309
+ *
310
+ * Advanced:
311
+ * Example #11: Load a file then override a single entry inline:
312
+ * When I add selectors from "homepage-selectors.json" file
313
+ * And I add "homepage heading" selector for "header h1" css selector
314
+ * Example #12: Load multiple files — later files override earlier keys:
315
+ * When I add selectors from "front-end-selectors.json" file
316
+ * And I add selectors from "back-end-selectors.json" file
317
+ * Example #13: File + inline xpath + component — all three registries merged:
318
+ * When I add selectors from "homepage-selectors.json" file
319
+ * And I add "extra link" selector for "//a[@rel='canonical']" xpath selector
320
+ * And I define css selectors:
321
+ * | wrapper | #main |
322
+ */
323
+ When(/^(I |we )*add selectors from "([^"]*)" file$/, function (pronounCase, fileName) {
324
+ const cfg = this.__selectorsConfig;
325
+ if (!fileName) throw new Error('Selectors: file name must not be empty.');
326
+ if (!cfg.filesPath) throw new Error('Selectors: worldParameters.selectors.filesPath must be set to load selector files.');
327
+ const filePath = path.join(cfg.filesPath, fileName);
328
+ let parsed;
329
+ try { parsed = parseFile(filePath); } catch (e) {
330
+ throw new Error(`Selectors: failed to load selector file "${filePath}": ${e.message}`);
331
+ }
332
+ if (parsed && parsed.css) Object.assign(this.__selectorsCss, parsed.css);
333
+ if (parsed && parsed.xpath) Object.assign(this.__selectorsXpath, parsed.xpath);
334
+ });
335
+
336
+ /**
337
+ * Print all registered CSS selectors to console (debug/inspection).
338
+ *
339
+ * Example #1: Then I print css selectors
340
+ * Example #2: When I print css selectors
341
+ * Example #3: Then we print css selectors
342
+ * Example #4: When we print css selectors
343
+ * Example #5: Then print css selectors
344
+ * Example #6: When print css selectors
345
+ * Example #7: And I print css selectors
346
+ * Example #8: And we print css selectors
347
+ * Example #9: Given I print css selectors
348
+ * Example #10: But I print css selectors
349
+ */
350
+ Then(/^(I |we )*print css selectors$/, function (_pronounCase) {
351
+ console.log('\n--- CSS Selectors ---');
352
+ for (const [name, sel] of Object.entries(this.__selectorsCss || {})) {
353
+ console.log(` "${name}": ${sel}`);
354
+ }
355
+ });
356
+
357
+ /**
358
+ * Print all registered XPath selectors to console (debug/inspection).
359
+ *
360
+ * Example #1: Then I print xpath selectors
361
+ * Example #2: When I print xpath selectors
362
+ * Example #3: Then we print xpath selectors
363
+ * Example #4: When we print xpath selectors
364
+ * Example #5: Then print xpath selectors
365
+ * Example #6: When print xpath selectors
366
+ * Example #7: And I print xpath selectors
367
+ * Example #8: And we print xpath selectors
368
+ * Example #9: Given I print xpath selectors
369
+ * Example #10: But I print xpath selectors
370
+ */
371
+ Then(/^(I |we )*print xpath selectors$/, function (_pronounCase) {
372
+ console.log('\n--- XPath Selectors ---');
373
+ for (const [name, sel] of Object.entries(this.__selectorsXpath || {})) {
374
+ console.log(` "${name}": ${sel}`);
375
+ }
376
+ });
377
+
378
+ // ===========================================================================
379
+ // STEP DEFINITIONS — Layout components
380
+ // ===========================================================================
381
+
382
+ /**
383
+ * Define named CSS selectors in bulk for the current scenario.
384
+ *
385
+ * Example #1:
386
+ * Given I define css selectors:
387
+ * | header | #header |
388
+ * | nav | nav.primary |
389
+ * | footer | footer |
390
+ *
391
+ * Example #2:
392
+ * Given I define css selectors:
393
+ * | logo | .site-logo |
394
+ * | search | #search-input |
395
+ *
396
+ * Example #3:
397
+ * Given I define css selectors:
398
+ * | hero | .hero-banner |
399
+ * | content | .main-content |
400
+ * | sidebar | .sidebar |
401
+ *
402
+ * Example #4:
403
+ * Given I define css selectors:
404
+ * | menu | ul.menu |
405
+ * | button | .cta-button |
406
+ *
407
+ * Example #5:
408
+ * Given I define css selectors:
409
+ * | top bar | .top-bar |
410
+ * | page | #page-wrapper |
411
+ * | footer | .site-footer |
412
+ *
413
+ * Example #6:
414
+ * Given we define css selectors:
415
+ * | modal | .modal-dialog |
416
+ * | overlay | .modal-backdrop |
417
+ *
418
+ * Example #7:
419
+ * When I define css selectors:
420
+ * | input | input[name=q] |
421
+ * | button | button[type=submit] |
422
+ *
423
+ * Example #8:
424
+ * And I define css selectors:
425
+ * | card | .card |
426
+ * | title | .card-title |
427
+ *
428
+ * Example #9:
429
+ * Given define css selectors:
430
+ * | heading | h1 |
431
+ * | list | ul |
432
+ *
433
+ * Example #10:
434
+ * Given I define css selectors:
435
+ * | left | .col-left |
436
+ * | center | .col-center |
437
+ * | right | .col-right |
438
+ *
439
+ * Advanced:
440
+ * Example #11: Later entry with same name overrides earlier:
441
+ * When I add "shared" selector for "ul" css selector
442
+ * Given I define css selectors:
443
+ * | shared | h1 |
444
+ * Then I see visible shared # resolves to h1 (latest wins).
445
+ *
446
+ * Example #12: Define + use in position + visibility asserts:
447
+ * Given I define css selectors:
448
+ * | heading | h1 |
449
+ * | list | ul |
450
+ * Then I see visible heading, list
451
+ * And I see heading above list
452
+ *
453
+ * Example #13: Layered page-shell selectors:
454
+ * Given I define css selectors:
455
+ * | topbar | .topbar |
456
+ * | header | header.site |
457
+ * | nav | nav[role=navigation] |
458
+ * | main | main |
459
+ * | footer | footer |
460
+ */
461
+ Given(/^(I |we )*define css selectors:$/, function (pronounCase, dataTable) {
462
+ for (const [name, selector] of dataTable.raw()) {
463
+ if (name && selector) this.__selectorsCss[name.trim()] = selector.trim();
464
+ }
465
+ });
466
+
467
+ /**
468
+ * Define named XPath selectors in bulk for the current scenario.
469
+ *
470
+ * Example #1:
471
+ * Given I define xpath selectors:
472
+ * | first heading | //h1[1] |
473
+ * | first subline | //h3[1] |
474
+ * Example #2:
475
+ * Given we define xpath selectors:
476
+ * | active tab | //li[contains(@class,'active')]/a |
477
+ * Example #3:
478
+ * Given define xpath selectors:
479
+ * | last nav item | //nav//a[last()] |
480
+ * Example #4:
481
+ * And I define xpath selectors:
482
+ * | login link | //a[contains(normalize-space(.),'Login')] |
483
+ * Example #5:
484
+ * When I define xpath selectors:
485
+ * | error message | //*[contains(@class,'error')] |
486
+ * Example #6:
487
+ * Given I define xpath selectors:
488
+ * | first table row | //table/tbody/tr[1] |
489
+ * | first table cell| //table/tbody/tr[1]/td[1] |
490
+ * Example #7:
491
+ * Given I define xpath selectors:
492
+ * | page title | //h1[contains(@class,'page-header')] |
493
+ * Example #8:
494
+ * Given I define xpath selectors:
495
+ * | admin menu | //nav[contains(@class,'admin-menu')] |
496
+ * Example #9:
497
+ * Given I define xpath selectors:
498
+ * | language switcher | //ul[contains(@class,'language-switcher')] |
499
+ * Example #10:
500
+ * Given I define xpath selectors:
501
+ * | user menu | //*[@id='user-menu'] |
502
+ */
503
+ Given(/^(I |we )*define xpath selectors:$/, function (pronounCase, dataTable) {
504
+ for (const [name, selector] of dataTable.raw()) {
505
+ if (name && selector) this.__selectorsXpath[name.trim()] = selector.trim();
506
+ }
507
+ });
508
+
509
+ /**
510
+ * Resize viewport to a named breakpoint.
511
+ * Built-in names: xs, sm, md, lg, xl, xxl, xxxl.
512
+ *
513
+ * xs 375 x 667 phone portrait
514
+ * sm 576 x 800 large phone / phablet
515
+ * md 768 x 1024 tablet portrait
516
+ * lg 992 x 768 small laptop / tablet landscape
517
+ * xl 1200 x 900 desktop (default)
518
+ * xxl 1400 x 900 wide desktop / HD
519
+ * xxxl 1920 x 1080 Full HD / large monitor
520
+ *
521
+ * Example #1: Given I am viewing the site on a xl screen
522
+ * Example #2: Given I am viewing the site on a xs screen
523
+ * Example #3: Given I am viewing the site on a md screen
524
+ * Example #4: Given I am viewing the site on a "xl" screen
525
+ * Example #5: Given I am viewing the site on a lg device
526
+ * Example #6: Given I am viewing the site on a "sm" device
527
+ * Example #7: Given I am viewing the site on a xxl screen
528
+ * Example #8: Given I am viewing the site on a "xxxl" screen
529
+ * Example #9: Given I am viewing the site on a xxxl device
530
+ * Example #10: Given I am viewing the site on a "xxl" device
531
+ * Example #11: Given we are viewing the site on a xs screen
532
+ * Example #12: Given viewing the site on a lg screen
533
+ */
534
+ Given(/^(I am |we are )?viewing the site on a (?:"([^"]+)"|([a-zA-Z0-9 _,]+)) (?:screen|device)$/, async function (pronounCase, quoted, bare) {
535
+ const name = (quoted || bare || '').trim();
536
+ const cfg = this.__selectorsConfig;
537
+ if (!cfg.breakpoints[name]) throw new Error(`Selectors: breakpoint "${name}" not defined in worldParameters.selectors.breakpoints.`);
538
+ const { width, height } = cfg.breakpoints[name];
539
+ await this.page.setViewportSize({ width, height });
540
+ });
541
+
542
+ // ===========================================================================
543
+ // STEP DEFINITIONS — Relative position assertions
544
+ // ===========================================================================
545
+
546
+ /**
547
+ * Assert a subject locator is above one or more others (absolute page coordinates).
548
+ *
549
+ * Example #1: Then I see header above footer
550
+ * Example #2: Then I see logo above search
551
+ * Example #3: Then I see nav above content, footer
552
+ * Example #4: Then I see hero above sidebar and footer
553
+ * Example #5: Then I see top bar above nav, content and footer
554
+ * Example #6: Then I see heading above subline
555
+ * Example #7: Then I see nav above content
556
+ * Example #8: Then I see search above results
557
+ * Example #9: Then I see banner above body
558
+ * Example #10: Then I see menu above page
559
+ *
560
+ * Advanced — multi-subject / multi-target dispatch:
561
+ * Example #11: Single subject, many targets (comma + "and"):
562
+ * Then I see heading above subline, list and footer
563
+ * Example #12: Many subjects, single target:
564
+ * Then I see heading, subline above list
565
+ * Example #13: Cartesian — many subjects × many targets:
566
+ * Then I see heading, subline above list, footer
567
+ * Example #14: Combined with inline xpath registration:
568
+ * When I add "first heading xp" selector for "//h1[1]" xpath selector
569
+ * Then I see first heading xp above list
570
+ */
571
+ Then(/^(I |we )*see ([a-zA-Z0-9 ,\-]+) above ([a-zA-Z0-9 ,\-]+)$/, async function (pronounCase, subject, others) {
572
+ await dispatcher(this, 'above', subject, others);
573
+ });
574
+
575
+ /**
576
+ * Assert a subject locator is below one or more others.
577
+ *
578
+ * Example #1: Then I see footer below header
579
+ * Example #2: Then I see content below nav
580
+ * Example #3: Then I see footer below header, nav and content
581
+ * Example #4: Then I see results below search
582
+ * Example #5: Then I see sidebar below hero
583
+ * Example #6: Then I see list below heading
584
+ * Example #7: Then I see nav below top bar
585
+ * Example #8: Then I see content below logo
586
+ * Example #9: Then I see page below menu
587
+ * Example #10: Then I see body below banner
588
+ */
589
+ Then(/^(I |we )*see ([a-zA-Z0-9 ,\-]+) below ([a-zA-Z0-9 ,\-]+)$/, async function (pronounCase, subject, others) {
590
+ await dispatcher(this, 'below', subject, others);
591
+ });
592
+
593
+ /**
594
+ * Assert a subject locator is to the left of one or more others.
595
+ *
596
+ * Example #1: Then I see logo to the left of nav
597
+ * Example #2: Then I see sidebar to left of content
598
+ * Example #3: Then I see search to the left of search button
599
+ * Example #4: Then I see menu to the left of cta
600
+ * Example #5: Then I see label to left of input
601
+ * Example #6: Then I see icon to the left of title
602
+ * Example #7: Then I see thumbnail to the left of description
603
+ * Example #8: Then I see avatar to left of username
604
+ * Example #9: Then I see back button to the left of forward button
605
+ * Example #10: Then I see flag to left of country name
606
+ */
607
+ Then(/^(I |we )*see ([a-zA-Z0-9 ,\-]+) to (?:the )?left of ([a-zA-Z0-9 ,\-]+)$/, async function (pronounCase, subject, others) {
608
+ await dispatcher(this, 'left', subject, others);
609
+ });
610
+
611
+ /**
612
+ * Assert a subject locator is to the right of one or more others.
613
+ *
614
+ * Example #1: Then I see nav to the right of logo
615
+ * Example #2: Then I see content to right of sidebar
616
+ * Example #3: Then I see search button to the right of search
617
+ * Example #4: Then I see cta to the right of menu
618
+ * Example #5: Then I see input to right of label
619
+ * Example #6: Then I see title to the right of icon
620
+ * Example #7: Then I see description to the right of thumbnail
621
+ * Example #8: Then I see username to right of avatar
622
+ * Example #9: Then I see forward button to the right of back button
623
+ * Example #10: Then I see country name to right of flag
624
+ */
625
+ Then(/^(I |we )*see ([a-zA-Z0-9 ,\-]+) to (?:the )?right of ([a-zA-Z0-9 ,\-]+)$/, async function (pronounCase, subject, others) {
626
+ await dispatcher(this, 'right', subject, others);
627
+ });
628
+
629
+ /**
630
+ * Assert a subject locator's bounding box is fully inside another's.
631
+ *
632
+ * Example #1: Then I see logo inside of header
633
+ * Example #2: Then I see nav inside of header
634
+ * Example #3: Then I see search inside of header
635
+ * Example #4: Then I see cta inside of hero
636
+ * Example #5: Then I see label inside of form
637
+ * Example #6: Then I see icon inside of button
638
+ * Example #7: Then I see title inside of banner
639
+ * Example #8: Then I see content inside of page
640
+ * Example #9: Then I see sidebar inside of page
641
+ * Example #10: Then I see footer inside of page
642
+ */
643
+ Then(/^(I |we )*see ([a-zA-Z0-9 ,\-]+) inside of ([a-zA-Z0-9 ,\-]+)$/, async function (pronounCase, subject, others) {
644
+ await dispatcher(this, 'inside', subject, others);
645
+ });
646
+
647
+ /**
648
+ * Assert a subject locator's bounding box fully contains another's.
649
+ *
650
+ * Example #1: Then I see header outside of logo
651
+ * Example #2: Then I see header outside of nav
652
+ * Example #3: Then I see hero outside of cta
653
+ * Example #4: Then I see form outside of label
654
+ * Example #5: Then I see button outside of icon
655
+ * Example #6: Then I see banner outside of title
656
+ * Example #7: Then I see page outside of content
657
+ * Example #8: Then I see page outside of sidebar
658
+ * Example #9: Then I see page outside of footer
659
+ * Example #10: Then I see wrapper outside of inner
660
+ */
661
+ Then(/^(I |we )*see ([a-zA-Z0-9 ,\-]+) outside of ([a-zA-Z0-9 ,\-]+)$/, async function (pronounCase, subject, others) {
662
+ await dispatcher(this, 'outside', subject, others);
663
+ });
664
+
665
+ /**
666
+ * Assert a subject locator overlaps another via intersection and z-index.
667
+ *
668
+ * Example #1: Then I see modal over content
669
+ * Example #2: Then I see dropdown over nav
670
+ * Example #3: Then I see tooltip over label
671
+ * Example #4: Then I see overlay over page
672
+ * Example #5: Then I see popup over hero
673
+ * Example #6: Then I see sticky header over content
674
+ * Example #7: Then I see cookie banner over footer
675
+ * Example #8: Then I see dialog over sidebar
676
+ * Example #9: Then I see notification over header
677
+ * Example #10: Then I see lightbox over page
678
+ */
679
+ Then(/^(I |we )*see ((?:[a-zA-Z0-9 ,\-](?!not))+) over ([a-zA-Z0-9 ,\-]+)$/, async function (pronounCase, subject, others) {
680
+ await dispatcher(this, 'over', subject, others);
681
+ });
682
+
683
+ /**
684
+ * Assert a subject locator does NOT overlap another element.
685
+ *
686
+ * Example #1: Then I see header not over content
687
+ * Example #2: Then I see nav not over sidebar
688
+ * Example #3: Then I see footer not over content
689
+ * Example #4: Then I see logo not over search
690
+ * Example #5: Then I see sidebar not over footer
691
+ * Example #6: Then I see menu not over hero
692
+ * Example #7: Then I see label not over input
693
+ * Example #8: Then I see icon not over title
694
+ * Example #9: Then I see button not over form
695
+ * Example #10: Then I see nav not over page
696
+ */
697
+ Then(/^(I |we )*see ([a-zA-Z0-9 ,\-]+) not over ([a-zA-Z0-9 ,\-]+)$/, async function (pronounCase, subject, others) {
698
+ await dispatcher(this, 'over', subject, others, true);
699
+ });
700
+
701
+ // ===========================================================================
702
+ // STEP DEFINITIONS — Visibility and focus (uses locator.isVisible / isHidden)
703
+ // ===========================================================================
704
+
705
+ /**
706
+ * Assert one or more named locators are visible.
707
+ *
708
+ * Example #1: Then I see visible header
709
+ * Example #2: Then I see visible nav, footer
710
+ * Example #3: Then I see visible logo and search
711
+ * Example #4: Then I see visible cta
712
+ * Example #5: Then I see visible hero, content and sidebar
713
+ * Example #6: Then I see visible menu
714
+ * Example #7: Then I see visible search button
715
+ * Example #8: Then I see visible banner
716
+ * Example #9: Then I see visible footer
717
+ * Example #10: Then I see visible top bar, nav and content
718
+ *
719
+ * Advanced:
720
+ * Example #11: Mix of components, inline CSS, inline XPath — all resolve:
721
+ * When I add "page heading" selector for "h1" css selector
722
+ * And I add "first para" selector for "//p[1]" xpath selector
723
+ * Then I see visible page heading, first para
724
+ * Example #12: After breakpoint resize — assert still visible:
725
+ * Given I am viewing the site on a xs screen
726
+ * Then I see visible heading, list
727
+ * Example #13: After loading a selector file — names from file are visible:
728
+ * When I add selectors from "homepage-selectors.json" file
729
+ * Then I see visible homepage heading, homepage first heading
730
+ */
731
+ Then(/^(I |we )*see visible ([a-zA-Z0-9 ,\-]+)$/, async function (pronounCase, subjectsText) {
732
+ const names = parseNames(subjectsText);
733
+ const errors = [];
734
+ for (const name of names) {
735
+ const sel = resolveSelector(this, name);
736
+ // Playwright native auto-retrying assertion — waits until the locator becomes visible.
737
+ try { await this.page.locator(sel).first().waitFor({ state: 'visible', timeout: 5000 }); }
738
+ catch { errors.push(`"${name}" (${sel}) is not visible`); }
739
+ }
740
+ if (errors.length > 0) throw new Error(errors.join('\n'));
741
+ });
742
+
743
+ /**
744
+ * Assert one or more named locators are hidden.
745
+ *
746
+ * Example #1: Then I don't see modal
747
+ * Example #2: Then I don't see dropdown, tooltip
748
+ * Example #3: Then I don't see overlay
749
+ * Example #4: Then I don't see cookie banner
750
+ * Example #5: Then I don't see popup
751
+ * Example #6: Then I don't see notification
752
+ * Example #7: Then I don't see lightbox
753
+ * Example #8: Then I don't see sticky header
754
+ * Example #9: Then I don't see dialog
755
+ * Example #10: Then I don't see sidebar, overlay and popup
756
+ */
757
+ Then(/^(I |we )*(don't|do not) see ([a-zA-Z0-9 ,\-]+)$/, async function (pronounCase, negation, subjectsText) {
758
+ const names = parseNames(subjectsText);
759
+ const errors = [];
760
+ for (const name of names) {
761
+ const sel = resolveSelector(this, name);
762
+ // Playwright native auto-retrying assertion — waits until the locator is detached or hidden.
763
+ try { await this.page.locator(sel).first().waitFor({ state: 'hidden', timeout: 5000 }); }
764
+ catch { errors.push(`"${name}" (${sel}) is visible (expected hidden)`); }
765
+ }
766
+ if (errors.length > 0) throw new Error(errors.join('\n'));
767
+ });
768
+
769
+ /**
770
+ * Assert a named locator has keyboard focus.
771
+ *
772
+ * Example #1: Then search has focus
773
+ * Example #2: Then email input has focus
774
+ * Example #3: Then submit button has focus
775
+ * Example #4: Then username has focus
776
+ * Example #5: Then password has focus
777
+ * Example #6: Then search button has focus
778
+ * Example #7: Then first link has focus
779
+ * Example #8: Then skip link has focus
780
+ * Example #9: Then close button has focus
781
+ * Example #10: Then modal heading has focus
782
+ */
783
+ Then(/^(I |we )*see ([a-zA-Z0-9 ,\-]+) has focus$/, async function (pronounCase, subjectText) {
784
+ const name = subjectText.trim();
785
+ const sel = resolveSelector(this, name);
786
+ const loc = this.page.locator(sel).first();
787
+ // Playwright native auto-retrying focus check via waitForFunction.
788
+ try {
789
+ await loc.waitFor({ state: 'attached', timeout: 5000 });
790
+ const handle = await loc.elementHandle();
791
+ await this.page.waitForFunction((el) => el === document.activeElement, handle, { timeout: 5000 });
792
+ } catch {
793
+ throw new Error(`"${name}" (${sel}) does not have focus`);
794
+ }
795
+ });
796
+
797
+ // ===========================================================================
798
+ // STEP DEFINITIONS — Focus and text selection
799
+ // ===========================================================================
800
+
801
+ /**
802
+ * Resolve a form field by label → placeholder → role=textbox → [name]/#id.
803
+ * Uses Playwright's ready-made semantic locators (getByLabel, getByPlaceholder,
804
+ * getByRole) with .or() fallbacks — matches the accessibility-first lookup
805
+ * chain recommended by https://playwright.dev/docs/locators.
806
+ */
807
+ function resolveField(page, field) {
808
+ return page.getByLabel(field).or(
809
+ page.getByPlaceholder(field)
810
+ ).or(
811
+ page.getByRole('textbox', { name: field })
812
+ ).or(
813
+ page.locator(`[name="${field}"], #${field}`)
814
+ ).first();
815
+ }
816
+
817
+ /**
818
+ * Move keyboard focus to a field by label, name, or id.
819
+ *
820
+ * Example #1: When I move focus to "Title" field
821
+ * Example #2: When I move focus to "Body" field
822
+ * Example #3: When I move focus to "Email" field
823
+ * Example #4: When I move focus to "Search" field
824
+ * Example #5: When I move focus to "Username" field
825
+ * Example #6: When I move focus to "Password" field
826
+ * Example #7: When I move focus to "First name" field
827
+ * Example #8: When I move focus to "Last name" field
828
+ * Example #9: When I move focus to "Description" field
829
+ * Example #10: When I move focus to "Phone" field
830
+ */
831
+ When(/^(I |we )*move focus to "([^"]*)" field$/, async function (pronounCase, fieldLabel) {
832
+ const loc = resolveField(this.page, fieldLabel);
833
+ await loc.focus();
834
+ });
835
+
836
+ /**
837
+ * Select all text inside a field by label, name, or id.
838
+ *
839
+ * Example #1: When I select all text in "Title" field
840
+ * Example #2: When I select all text in "Description" field
841
+ * Example #3: When I select all text in "Body" field
842
+ * Example #4: When I select all text in "Email" field
843
+ * Example #5: When I select all text in "Username" field
844
+ * Example #6: When I select all text in "Search" field
845
+ * Example #7: When I select all text in "Name" field
846
+ * Example #8: When I select all text in "Notes" field
847
+ * Example #9: When I select all text in "Address" field
848
+ * Example #10: When I select all text in "Message" field
849
+ */
850
+ When(/^(I |we )*select all text in "([^"]*)" field$/, async function (pronounCase, fieldLabel) {
851
+ const loc = resolveField(this.page, fieldLabel);
852
+ await loc.focus();
853
+ await loc.selectText();
854
+ });
855
+
856
+ /**
857
+ * Select a character range (from..to) inside a field.
858
+ *
859
+ * Example #1: When I select from 0 to 5 text in "Title" field
860
+ * Example #2: When I select from 0 to 10 text in "Body" field
861
+ * Example #3: When I select from 3 to 8 text in "Description" field
862
+ * Example #4: When I select from 0 to 5 text in "Email" field
863
+ * Example #5: When I select from 2 to 6 text in "Username" field
864
+ * Example #6: When we select from 0 to 4 text in "Name" field
865
+ * Example #7: When select from 1 to 7 text in "Search" field
866
+ * Example #8: When I select from 0 to 20 text in "Notes" field
867
+ * Example #9: When I select from 5 to 15 text in "Address" field
868
+ * Example #10: When we select from 0 to 3 text in "Phone" field
869
+ *
870
+ * Advanced:
871
+ * Example #11: Select first word after fill:
872
+ * And I fill in "Title" with "Release 2.0 notes"
873
+ * When I select from 0 to 7 text in "Title" field
874
+ * Example #12: Select middle substring by index range:
875
+ * And I fill in "Body" with "abcdefghij"
876
+ * When I select from 3 to 6 text in "Body" field
877
+ * Example #13: Chain — fill, focus, range-select, assert focus:
878
+ * And I fill in "Notes" with "hello world"
879
+ * When I move focus to "Notes" field
880
+ * And I select from 0 to 5 text in "Notes" field
881
+ * Then I see Notes has focus
882
+ */
883
+ When(/^(I |we )*select from (\d+) to (\d+) text in "([^"]*)" field$/, async function (pronounCase, from, to, fieldLabel) {
884
+ const start = parseInt(from, 10);
885
+ const end = parseInt(to, 10);
886
+ const loc = resolveField(this.page, fieldLabel);
887
+ await loc.focus();
888
+ await loc.evaluate((el, [s, e]) => {
889
+ if (typeof el.setSelectionRange === 'function') el.setSelectionRange(s, e);
890
+ }, [start, end]);
891
+ });
892
+
893
+ /**
894
+ * Select a specific substring of text inside a field.
895
+ *
896
+ * Example #1: When I select "title name" text in "Title" field
897
+ * Example #2: When I select "some content" text in "Description" field
898
+ * Example #3: When I select "hello" text in "Body" field
899
+ * Example #4: When I select "admin" text in "Username" field
900
+ * Example #5: When I select "example" text in "Email" field
901
+ * Example #6: When we select "webship" text in "Search" field
902
+ * Example #7: When select "lorem" text in "Notes" field
903
+ * Example #8: When I select "street" text in "Address" field
904
+ * Example #9: When we select "555" text in "Phone" field
905
+ * Example #10: When I select "summary" text in "Message" field
906
+ */
907
+ When(/^(I |we )*select "([^"]*)" text in "([^"]*)" field$/, async function (pronounCase, selectedText, fieldLabel) {
908
+ const loc = resolveField(this.page, fieldLabel);
909
+
910
+ const value = await loc.inputValue();
911
+ const start = value.indexOf(selectedText);
912
+ if (start === -1) throw new Error(`Text "${selectedText}" not found in field "${fieldLabel}"`);
913
+ const end = start + selectedText.length;
914
+
915
+ await loc.focus();
916
+ await loc.evaluate((el, [s, e]) => {
917
+ if (typeof el.setSelectionRange === 'function') el.setSelectionRange(s, e);
918
+ }, [start, end]);
919
+ });
920
+
921
+ // ===========================================================================
922
+ // STEP DEFINITIONS — Click by named component/selector
923
+ // ===========================================================================
924
+
925
+ /**
926
+ * Click one or more named components — uses locator.click() which auto-scrolls.
927
+ *
928
+ * Example #1: When I click nav
929
+ * Example #2: When I click search button
930
+ * Example #3: When click cta
931
+ * Example #4: When I click on logo
932
+ * Example #5: When I click menu
933
+ * Example #6: When I click on submit button
934
+ * Example #7: When I click close button
935
+ * Example #8: When click back button
936
+ * Example #9: When I click on forward button
937
+ * Example #10: When I click hero, cta
938
+ *
939
+ * Advanced:
940
+ * Example #11: Click via XPath-registered selector:
941
+ * When I add "login link xp" selector for "//a[contains(.,'Login')]" xpath selector
942
+ * And I click login link xp
943
+ * Example #12: Click a sequence — comma-separated names:
944
+ * Given I define css selectors:
945
+ * | tab 1 | [data-tab='1'] |
946
+ * | tab 2 | [data-tab='2'] |
947
+ * When I click tab 1, tab 2
948
+ * Example #13: Register with CSS then click — no components needed:
949
+ * When I add "cta primary" selector for ".cta .btn-primary" css selector
950
+ * And I click cta primary
951
+ */
952
+ When(/^(I |we )*click (?:on |a )?([a-zA-Z0-9 ,\-]+)$/, async function (pronounCase, subjectsText) {
953
+ const names = parseNames(subjectsText);
954
+ const errors = [];
955
+ for (const name of names) {
956
+ const sel = resolveSelector(this, name);
957
+ try { await this.page.locator(sel).first().click(); }
958
+ catch (e) { errors.push(`Cannot click "${name}" (${sel}): ${e.message}`); }
959
+ }
960
+ if (errors.length > 0) throw new Error(errors.join('\n'));
961
+ });