@webship-js/magento-steps 0.0.0-stage → 2.0.1

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 (31) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +405 -2
  3. package/package.json +66 -4
  4. package/scripts/build-site.sh +190 -0
  5. package/scripts/site-accounts.php +119 -0
  6. package/tests/features/01-admin-session.feature +35 -0
  7. package/tests/features/02-admin-menu-pages.feature +54 -0
  8. package/tests/features/03-admin-permissions.feature +51 -0
  9. package/tests/features/04-admin-grids.feature +97 -0
  10. package/tests/features/05-admin-products.feature +87 -0
  11. package/tests/features/06-admin-categories.feature +44 -0
  12. package/tests/features/07-admin-orders.feature +95 -0
  13. package/tests/features/08-admin-customers.feature +55 -0
  14. package/tests/features/09-admin-cart-price-rules.feature +49 -0
  15. package/tests/features/10-admin-content.feature +63 -0
  16. package/tests/features/11-admin-configuration-cache.feature +46 -0
  17. package/tests/features/12-admin-reviews-newsletter.feature +66 -0
  18. package/tests/features/20-storefront-catalog.feature +64 -0
  19. package/tests/features/21-storefront-search.feature +40 -0
  20. package/tests/features/22-storefront-product-cart.feature +68 -0
  21. package/tests/features/23-storefront-checkout.feature +65 -0
  22. package/tests/features/24-storefront-customer.feature +93 -0
  23. package/tests/features/25-storefront-wishlist-compare-contact.feature +50 -0
  24. package/tests/features/90-assertions-must-fail.feature +165 -0
  25. package/tests/fixtures/pixel.png +0 -0
  26. package/tests/step-definitions/README.md +36 -0
  27. package/tests/step-definitions/magento-admin-content.steps.js +818 -0
  28. package/tests/step-definitions/magento-admin.steps.js +856 -0
  29. package/tests/step-definitions/magento-helpers.js +992 -0
  30. package/tests/step-definitions/magento-storefront.steps.js +1797 -0
  31. package/tests/step-definitions/magento.steps.js +158 -0
@@ -0,0 +1,992 @@
1
+ 'use strict';
2
+
3
+ // Shared helpers for the step files of this pack.
4
+ //
5
+ // Not a step file: it registers no step definitions and no hooks. It holds the
6
+ // plumbing the steps use and that downstream packs can require instead of
7
+ // copying: the wait budget, the "settled" signal of the admin panel and of the
8
+ // storefront, friendly presence assertions, URL building, the users registry,
9
+ // the messages, the admin grids (both kinds), the admin forms and the
10
+ // confirmation dialogs.
11
+ //
12
+ // Everything here was written from what the real pages do in a browser; the
13
+ // notes are in exploration/*.md of the repository.
14
+
15
+ const { gotoUrl, friendly } = require('webship-js/tests/step-definitions/webship');
16
+
17
+ // ---------------------------------------------------------------------------
18
+ // Small utilities
19
+ // ---------------------------------------------------------------------------
20
+
21
+ /**
22
+ * The per-assertion wait budget: `minWaitTime.page` from cucumber.js, at least
23
+ * 15 seconds (an order or a product save can take several), kept below
24
+ * webship-js's 45 second step timeout. WEBSHIP_ASSERT_BUDGET=<milliseconds>
25
+ * changes the 15 seconds (the must-fail check lowers it: every one of its
26
+ * scenarios waits the whole budget before it fails).
27
+ *
28
+ * @param {object} world
29
+ * @returns {number}
30
+ */
31
+ function budget(world) {
32
+ const floor = Number(process.env.WEBSHIP_ASSERT_BUDGET) || 15000;
33
+ return Math.min(Math.max((world && world.minWaitTime && world.minWaitTime.page) || 0, floor), 30000);
34
+ }
35
+
36
+ /**
37
+ * Escape a literal string for use in a RegExp.
38
+ *
39
+ * @param {string} text
40
+ * @returns {RegExp}
41
+ */
42
+ function escapeRegExp(text) {
43
+ return String(text).replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
44
+ }
45
+
46
+ /**
47
+ * A case-sensitive RegExp that matches the literal text anywhere.
48
+ *
49
+ * @param {string} text
50
+ * @returns {RegExp}
51
+ */
52
+ function literal(text) {
53
+ return new RegExp(escapeRegExp(text));
54
+ }
55
+
56
+ /**
57
+ * A RegExp that matches the whole text, ignoring the case and the space around
58
+ * it. The storefront theme prints several labels in capitals through CSS, so a
59
+ * label is compared without its case.
60
+ *
61
+ * @param {string} text
62
+ * @returns {RegExp}
63
+ */
64
+ function exactly(text) {
65
+ return new RegExp('^\\s*' + escapeRegExp(String(text).trim()).replace(/\s+/g, '\\s+') + '\\s*$', 'i');
66
+ }
67
+
68
+ /**
69
+ * Collapse runs of white space and trim.
70
+ *
71
+ * @param {string} text
72
+ * @returns {string}
73
+ */
74
+ function clean(text) {
75
+ return String(text === null || text === undefined ? '' : text).replace(/\s+/g, ' ').trim();
76
+ }
77
+
78
+ /**
79
+ * A text as the value of a Playwright `:text-is("…")` pseudo-class.
80
+ *
81
+ * @param {string} text
82
+ * @returns {string}
83
+ */
84
+ function quoted(text) {
85
+ return '"' + String(text).replace(/\\/g, '\\\\').replace(/"/g, '\\"') + '"';
86
+ }
87
+
88
+ /**
89
+ * The site root without a trailing slash.
90
+ *
91
+ * @param {object} world
92
+ * @returns {string}
93
+ */
94
+ function siteRoot(world) {
95
+ return String(world.launchUrl).replace(/\/+$/, '');
96
+ }
97
+
98
+ /**
99
+ * Join the site root and a path with exactly one slash. Absolute URLs pass
100
+ * through.
101
+ *
102
+ * @param {object} world
103
+ * @param {string} url
104
+ * @returns {string}
105
+ */
106
+ function siteUrl(world, url) {
107
+ if (!url) return siteRoot(world) + '/';
108
+ if (/^https?:\/\//i.test(url)) return url;
109
+ return siteRoot(world) + '/' + String(url).replace(/^\/+/, '');
110
+ }
111
+
112
+ /**
113
+ * The first path segment of the admin panel (`adminPath` in cucumber.js, the
114
+ * `--backend-frontname` of the installation; "admin" by default).
115
+ *
116
+ * @param {object} world
117
+ * @returns {string}
118
+ */
119
+ function adminPath(world) {
120
+ const value = (world.parameters && world.parameters.adminPath) || 'admin';
121
+ return String(value).replace(/^\/+|\/+$/g, '');
122
+ }
123
+
124
+ /**
125
+ * The URL of an admin page from its route ("catalog/product", "admin/cache").
126
+ *
127
+ * @param {object} world
128
+ * @param {string} route
129
+ * @returns {string}
130
+ */
131
+ function adminUrl(world, route) {
132
+ const tail = String(route || '').replace(/^\/+|\/+$/g, '');
133
+ return siteRoot(world) + '/' + adminPath(world) + '/' + (tail ? tail + '/' : '');
134
+ }
135
+
136
+ // ---------------------------------------------------------------------------
137
+ // The "settled" signal
138
+ // ---------------------------------------------------------------------------
139
+
140
+ // Runs in the page. Returns '' when the page is settled, else what it is still
141
+ // doing. Measured in a real browser: `document.readyState` is "complete" long
142
+ // before the page works (RequireJS still loads 20 to 130 modules and the
143
+ // `text/x-magento-init` blocks are not processed yet), so "page loaded" is not
144
+ // the signal. A page is settled when RequireJS has no requested module left to
145
+ // load, every init block is consumed, no request is in flight and no loading
146
+ // mask shows. The modules load in waves with short idle gaps between them, so
147
+ // the caller asks for several quiet readings in a row.
148
+ /* istanbul ignore next */
149
+ function settledProbe() {
150
+ if (document.readyState !== 'complete') return 'the document is still loading';
151
+ const ctx = window.require && window.require.s && window.require.s.contexts && window.require.s.contexts._;
152
+ if (ctx) {
153
+ // Only the modules somebody asked for count: the admin panel keeps a few named
154
+ // modules nobody requires (globalNavigation, modalPopup, …) in the registry for good.
155
+ const pending = Object.keys(ctx.registry || {}).filter((id) => ctx.registry[id] && ctx.registry[id].enabled);
156
+ if (pending.length) return 'scripts are still loading (' + pending.slice(0, 3).join(', ') + (pending.length > 3 ? ', …' : '') + ')';
157
+ }
158
+ if (document.querySelector('script[type="text/x-magento-init"]')) return 'the page components are not initialised yet';
159
+ if (window.jQuery && window.jQuery.active) return 'a request is in flight';
160
+ const masks = document.querySelectorAll('.loading-mask, [data-role="spinner"], [data-role="loader"], ._block-content-loading, .admin__data-grid-loading-mask, .admin__form-loading-mask, .popup-loading');
161
+ for (const mask of masks) {
162
+ if (getComputedStyle(mask).display !== 'none' && getComputedStyle(mask).visibility !== 'hidden' && mask.getClientRects().length) {
163
+ return 'a loading mask is showing (' + (mask.id ? '#' + mask.id : '.' + String(mask.className).trim().split(/\s+/).join('.')) + ')';
164
+ }
165
+ }
166
+ return '';
167
+ }
168
+
169
+ /**
170
+ * Wait until the page is settled: scripts loaded, components initialised, no
171
+ * request in flight, no loading mask. Three readings in a row must agree, so a
172
+ * navigation that a click has just started is not mistaken for a quiet page.
173
+ * Works in the admin panel and on the storefront.
174
+ *
175
+ * @param {object} world
176
+ * @param {number} [timeout]
177
+ */
178
+ async function settle(world, timeout) {
179
+ const page = world.page;
180
+ const limit = Date.now() + (timeout || budget(world));
181
+ let quiet = 0;
182
+ let last = 'the page did not answer';
183
+ while (Date.now() < limit) {
184
+ let state;
185
+ try {
186
+ state = await page.evaluate(settledProbe);
187
+ } catch {
188
+ state = 'the page is navigating';
189
+ }
190
+ if (state === '') {
191
+ quiet += 1;
192
+ if (quiet >= 3) return;
193
+ } else {
194
+ quiet = 0;
195
+ last = state;
196
+ }
197
+ await page.waitForTimeout(120);
198
+ }
199
+ throw friendly({
200
+ message: `The page did not settle within ${timeout || budget(world)} ms: ${last}.`,
201
+ hint: 'A loading mask that never goes away usually means a failed request: open the browser console and the network tab on this page.',
202
+ });
203
+ }
204
+
205
+ /**
206
+ * Open a URL and wait for the page to settle.
207
+ *
208
+ * @param {object} world
209
+ * @param {string} url
210
+ */
211
+ async function open(world, url) {
212
+ try {
213
+ await gotoUrl(world.page, url);
214
+ } catch (err) {
215
+ // The browser drops a request when the network of the machine changes under
216
+ // it (a container network coming or going on a shared host) and asks for
217
+ // the page to be loaded again: do that once.
218
+ if (!/ERR_NETWORK_CHANGED/.test(String(err && err.message))) throw err;
219
+ await gotoUrl(world.page, url);
220
+ }
221
+ await settle(world);
222
+ }
223
+
224
+ /**
225
+ * Run an action that may load a new page (a click on a link or a submit
226
+ * button), then wait for the page to settle. While a form is being posted the
227
+ * old page still looks settled, so the navigation itself is watched: when the
228
+ * action starts a main-frame navigation request, the step waits until that
229
+ * page has arrived. Nothing is required: the same step works for an AJAX
230
+ * action. The clicks passed in carry `noWaitAfter`: this helper does the
231
+ * waiting, and Playwright's own wait after a click now and then never returns
232
+ * in Firefox although the page has arrived.
233
+ *
234
+ * @param {object} world
235
+ * @param {Function} action
236
+ */
237
+ async function actAndSettle(world, action) {
238
+ const page = world.page;
239
+ let started = 0;
240
+ let arrived = 0;
241
+ const onRequest = (request) => {
242
+ // A redirect is a new request of the same navigation: count the first hop only.
243
+ if (request.isNavigationRequest() && request.frame() === page.mainFrame() && !request.redirectedFrom()) started += 1;
244
+ };
245
+ const onNavigated = (frame) => {
246
+ if (frame === page.mainFrame()) arrived += 1;
247
+ };
248
+ page.on('request', onRequest);
249
+ page.on('framenavigated', onNavigated);
250
+ try {
251
+ await action();
252
+ // The request of a click starts within a moment of it.
253
+ const grace = Date.now() + 600;
254
+ while (!started && !arrived && Date.now() < grace) await page.waitForTimeout(50);
255
+ const limit = Date.now() + budget(world);
256
+ while (started > arrived && Date.now() < limit) await page.waitForTimeout(50);
257
+ } finally {
258
+ page.off('request', onRequest);
259
+ page.off('framenavigated', onNavigated);
260
+ }
261
+ await settle(world);
262
+ }
263
+
264
+ /**
265
+ * Run an action and rethrow its failure as a friendly error (action, target,
266
+ * cause and a hint) instead of Playwright's raw timeout stack.
267
+ *
268
+ * @param {string} label
269
+ * @param {string} target
270
+ * @param {Function} fn
271
+ * @param {string} hint
272
+ */
273
+ async function actOrExplain(label, target, fn, hint) {
274
+ try {
275
+ return await fn();
276
+ } catch (err) {
277
+ if (err && err.stack === err.message && /Hint:/.test(err.message)) throw err;
278
+ throw friendly({ action: label, target, cause: err, hint });
279
+ }
280
+ }
281
+
282
+ /**
283
+ * Wait until a locator has (or, with `notCase`, no longer has) a visible match
284
+ * and fail with a friendly error otherwise: the wait and the assertion are one
285
+ * call, so content that arrives a moment late still passes.
286
+ *
287
+ * @param {import('playwright').Locator} locator
288
+ * @param {string|null|undefined} notCase
289
+ * @param {{label: string, hint: string, timeout: number, found?: Function}} options
290
+ */
291
+ async function assertPresence(locator, notCase, { label, hint, timeout, found }) {
292
+ try {
293
+ await locator.first().waitFor({ state: notCase ? 'hidden' : 'visible', timeout });
294
+ } catch {
295
+ const seen = found ? await found().catch(() => '') : '';
296
+ throw friendly({
297
+ message: (notCase ? `Expected not to see ${label}, but it is on the page.` : `Expected to see ${label}, but it did not appear within ${timeout} ms.`) + (seen ? ` Found instead: ${seen}.` : ''),
298
+ hint,
299
+ });
300
+ }
301
+ }
302
+
303
+ /**
304
+ * Poll a reader until it returns the expected value (or, with `notCase`, any
305
+ * other value) and fail with what was found.
306
+ *
307
+ * @param {object} world
308
+ * @param {Function} read - async () => string
309
+ * @param {string|RegExp} expected
310
+ * @param {{label: string, hint: string, notCase?: string|null}} options
311
+ */
312
+ async function assertValue(world, read, expected, { label, hint, notCase }) {
313
+ const limit = Date.now() + budget(world);
314
+ const matches = (value) => (expected instanceof RegExp ? expected.test(value) : value === String(expected));
315
+ let value = '';
316
+ for (;;) {
317
+ value = clean(await read().catch(() => ''));
318
+ if (matches(value) !== Boolean(notCase)) return value;
319
+ if (Date.now() > limit) break;
320
+ await world.page.waitForTimeout(150);
321
+ }
322
+ const wanted = expected instanceof RegExp ? String(expected) : `"${expected}"`;
323
+ throw friendly({
324
+ message: notCase ? `Expected ${label} not to be ${wanted}, but it is.` : `Expected ${label} to be ${wanted}, but found "${value}".`,
325
+ hint,
326
+ });
327
+ }
328
+
329
+ // ---------------------------------------------------------------------------
330
+ // Accounts
331
+ // ---------------------------------------------------------------------------
332
+
333
+ /**
334
+ * An account of the `users` registry in cucumber.js (`worldParameters.users`).
335
+ * Admin accounts carry `username`, customers carry `email`.
336
+ *
337
+ * @param {object} world
338
+ * @param {string} handle
339
+ * @param {'admin'|'customer'} kind
340
+ * @returns {{login: string, password: string, name: string}}
341
+ */
342
+ function resolveUser(world, handle, kind) {
343
+ const users = (world.parameters && world.parameters.users) || {};
344
+ const entry = users[handle];
345
+ const key = kind === 'customer' ? 'email' : 'username';
346
+ const known = Object.keys(users).filter((name) => users[name] && users[name][key]);
347
+ if (!entry || !entry[key]) {
348
+ throw friendly({
349
+ message: `"${handle}" is not ${kind === 'customer' ? 'a customer' : 'an admin user'} of the users registry. Known: ${known.join(', ') || '(none)'}.`,
350
+ hint: `Add it to worldParameters.users in cucumber.js: ${handle}: { ${key}: '...', password: process.env.${handle.toUpperCase()}_PASSWORD }. The account itself is created once by the site build script, never by a feature.`,
351
+ });
352
+ }
353
+ if (!entry.password) {
354
+ throw friendly({
355
+ message: `The user "${handle}" has no password in the users registry.`,
356
+ hint: `Set worldParameters.users.${handle}.password in cucumber.js, from an environment variable.`,
357
+ });
358
+ }
359
+ return { login: entry[key], password: entry.password, name: entry.name || '' };
360
+ }
361
+
362
+ // ---------------------------------------------------------------------------
363
+ // Messages
364
+ // ---------------------------------------------------------------------------
365
+
366
+ const MESSAGE_TYPES = ['success', 'error', 'warning', 'notice'];
367
+
368
+ /**
369
+ * The messages of the page: `#messages .message` in the admin panel,
370
+ * `.page.messages .message` on the storefront (rendered there by KnockoutJS
371
+ * from the messages cookie and section), optionally of one type and with a
372
+ * text.
373
+ *
374
+ * @param {object} world
375
+ * @param {string} [type] success, error, warning or notice
376
+ * @param {string} [text]
377
+ * @returns {import('playwright').Locator}
378
+ */
379
+ function messages(world, type, text) {
380
+ const kind = type ? '.message-' + String(type).toLowerCase() : '';
381
+ // `.login-content .messages` is the message area of the admin sign-in page, which has no `#messages`.
382
+ let locator = world.page.locator(`#messages .message${kind}, .login-content .messages .message${kind}, .page.messages .message${kind}, .column.main > .message${kind === '.message-notice' ? '.notice' : kind}`);
383
+ if (text !== undefined && text !== null && text !== '') locator = locator.filter({ hasText: literal(text) });
384
+ return locator;
385
+ }
386
+
387
+ /**
388
+ * The text of every message on the page, for a failure message.
389
+ *
390
+ * @param {object} world
391
+ * @returns {Promise<string>}
392
+ */
393
+ async function messagesSeen(world) {
394
+ const texts = await world.page.locator('#messages .message, .login-content .messages .message, .page.messages .message, .column.main > .message').allInnerTexts().catch(() => []);
395
+ return texts.length ? texts.map((text) => `"${clean(text)}"`).join(', ') : 'no message';
396
+ }
397
+
398
+ // ---------------------------------------------------------------------------
399
+ // Confirmation dialogs
400
+ // ---------------------------------------------------------------------------
401
+
402
+ /**
403
+ * The open dialog of the page (`.modal-popup._show`).
404
+ *
405
+ * @param {object} world
406
+ * @returns {import('playwright').Locator}
407
+ */
408
+ function dialog(world) {
409
+ return world.page.locator('.modal-popup._show').last();
410
+ }
411
+
412
+ /**
413
+ * Press OK (or Cancel) in the open confirmation dialog and wait for what
414
+ * follows.
415
+ *
416
+ * @param {object} world
417
+ * @param {boolean} accept
418
+ */
419
+ async function answerDialog(world, accept) {
420
+ const box = dialog(world);
421
+ try {
422
+ await box.waitFor({ state: 'visible', timeout: budget(world) });
423
+ } catch {
424
+ throw friendly({
425
+ message: 'No confirmation dialog is open.',
426
+ hint: 'The dialog opens after an action that asks "Are you sure…?" (Delete, Cancel an order, a grid action).',
427
+ });
428
+ }
429
+ const button = box.locator(accept ? 'button.action-accept' : 'button.action-dismiss').first();
430
+ await actAndSettle(world, () => button.click({ noWaitAfter: true }));
431
+ }
432
+
433
+ // ---------------------------------------------------------------------------
434
+ // Admin panel: session and pages
435
+ // ---------------------------------------------------------------------------
436
+
437
+ // The named admin pages, by the name of their menu item. The value is the route
438
+ // after the admin path.
439
+ const ADMIN_PAGES = {
440
+ 'dashboard': 'admin/dashboard',
441
+ 'orders': 'sales/order',
442
+ 'invoices': 'sales/invoice',
443
+ 'shipments': 'sales/shipment',
444
+ 'credit memos': 'sales/creditmemo',
445
+ 'products': 'catalog/product',
446
+ 'new product': 'catalog/product/new/set/4/type/simple',
447
+ 'categories': 'catalog/category',
448
+ 'customers': 'customer/index',
449
+ 'customer groups': 'customer/group',
450
+ 'cart price rules': 'sales_rule/promo_quote',
451
+ 'new cart price rule': 'sales_rule/promo_quote/new',
452
+ 'catalog price rules': 'catalog_rule/promo_catalog',
453
+ 'newsletter subscribers': 'newsletter/subscriber',
454
+ 'reviews': 'review/product/index',
455
+ 'pending reviews': 'review/product/pending',
456
+ 'pages': 'cms/page',
457
+ 'new page': 'cms/page/new',
458
+ 'blocks': 'cms/block',
459
+ 'configuration': 'admin/system_config',
460
+ 'cache management': 'admin/cache',
461
+ 'index management': 'indexer/indexer/list',
462
+ 'users': 'admin/user',
463
+ 'roles': 'admin/user_role',
464
+ 'product attributes': 'catalog/product_attribute',
465
+ 'order statuses': 'sales/order_status',
466
+ 'my account': 'admin/system_account/index',
467
+ };
468
+
469
+ /**
470
+ * The route of a named admin page. A name that is not in the table but looks
471
+ * like a route ("sales/order", "cms/page/new") is used as it is.
472
+ *
473
+ * @param {string} name
474
+ * @returns {string}
475
+ */
476
+ function adminRoute(name) {
477
+ const key = clean(name).toLowerCase();
478
+ if (Object.prototype.hasOwnProperty.call(ADMIN_PAGES, key)) return ADMIN_PAGES[key];
479
+ if (/^[a-z0-9_]+(\/[A-Za-z0-9_=.-]+)+\/?$/.test(clean(name))) return clean(name);
480
+ throw friendly({
481
+ message: `"${name}" is not a known admin page.`,
482
+ hint: `Use one of: ${Object.keys(ADMIN_PAGES).join(', ')}; or a route such as "sales/order".`,
483
+ });
484
+ }
485
+
486
+ /**
487
+ * The username shown in the admin header, or '' when nobody is signed in.
488
+ *
489
+ * @param {object} world
490
+ * @returns {Promise<string>}
491
+ */
492
+ async function adminUser(world) {
493
+ const name = world.page.locator('.admin-user .admin-user-account-text');
494
+ if (!(await name.count())) return '';
495
+ return clean(await name.first().textContent());
496
+ }
497
+
498
+ /**
499
+ * Fail with a hint when the admin sign-in form shows instead of a page.
500
+ *
501
+ * @param {object} world
502
+ * @param {string} what
503
+ */
504
+ async function requireAdminSession(world, what) {
505
+ if (await world.page.locator('body.adminhtml-auth-login').count()) {
506
+ throw friendly({
507
+ message: `The admin sign-in form is showing instead of "${what}": nobody is logged in to the admin panel.`,
508
+ hint: 'Add `Given I am logged in to the admin panel as "admin"` before this step.',
509
+ });
510
+ }
511
+ }
512
+
513
+ /**
514
+ * Open an admin page by route and make sure a session is there.
515
+ *
516
+ * @param {object} world
517
+ * @param {string} route
518
+ * @param {string} what
519
+ */
520
+ async function openAdmin(world, route, what) {
521
+ await open(world, adminUrl(world, route));
522
+ await requireAdminSession(world, what || route);
523
+ }
524
+
525
+ // ---------------------------------------------------------------------------
526
+ // Admin grids
527
+ // ---------------------------------------------------------------------------
528
+ //
529
+ // The admin panel has two kinds of grid:
530
+ // "ui" the UI-component listing (products, orders, customers, pages):
531
+ // `.admin__data-grid-outer-wrap` with a toolbar (keyword search,
532
+ // Filters panel, Actions, pager) and `tr.data-row` rows. It keeps a
533
+ // hidden copy of its header and of its table head in
534
+ // `.sticky-header`, FIRST in the DOM: every lookup goes through the
535
+ // direct children of the visible wrapper.
536
+ // "legacy" the older grid (cart price rules, reviews, subscribers, cache,
537
+ // index): `table.data-grid` with a filter row, "Search" and "Reset
538
+ // Filter" buttons and a mass-action select.
539
+ // Both remember their filters for the admin user between visits.
540
+
541
+ /**
542
+ * The grid of the page.
543
+ *
544
+ * @param {object} world
545
+ * @returns {Promise<{kind: string, wrap: import('playwright').Locator, header: import('playwright').Locator, table: import('playwright').Locator, rows: import('playwright').Locator}>}
546
+ */
547
+ async function grid(world) {
548
+ const page = world.page;
549
+ await settle(world);
550
+ const ui = page.locator('.admin__data-grid-outer-wrap:visible').first();
551
+ if (await ui.count()) {
552
+ const table = ui.locator(':scope > .admin__data-grid-wrap > table.data-grid');
553
+ return { kind: 'ui', wrap: ui, header: ui.locator(':scope > .admin__data-grid-header'), table, rows: table.locator('tbody tr.data-row') };
554
+ }
555
+ const table = page.locator('table.data-grid:visible').first();
556
+ if (await table.count()) {
557
+ const wrap = table.locator('xpath=ancestor::*[@data-grid-id or contains(concat(" ", normalize-space(@class), " "), " admin__scope-old ") or @id="container"][1]');
558
+ return { kind: 'legacy', wrap, header: wrap.locator('.admin__data-grid-header').first(), table, rows: table.locator('tbody tr:not(.data-grid-tr-no-data)') };
559
+ }
560
+ throw friendly({
561
+ message: 'There is no grid on this page.',
562
+ hint: 'Open a list page first, for example `When I go to the "products" admin page`.',
563
+ });
564
+ }
565
+
566
+ /**
567
+ * The column titles of a grid, in order (one entry per cell of the head row).
568
+ *
569
+ * @param {{table: import('playwright').Locator}} g
570
+ * @returns {Promise<string[]>}
571
+ */
572
+ async function gridColumns(g) {
573
+ return g.table.locator('thead tr').first().locator('th').evaluateAll((cells) => cells.map((cell) => {
574
+ const own = cell.querySelector('.data-grid-cell-content, span[data-sort], a span, span') || cell;
575
+ return (own.textContent || '').replace(/\s+/g, ' ').trim();
576
+ }));
577
+ }
578
+
579
+ /**
580
+ * The index of a column by its title.
581
+ *
582
+ * @param {{table: import('playwright').Locator}} g
583
+ * @param {string} title
584
+ * @returns {Promise<number>}
585
+ */
586
+ async function gridColumnIndex(g, title) {
587
+ const columns = await gridColumns(g);
588
+ const wanted = clean(title).toLowerCase();
589
+ const index = columns.findIndex((column) => column.toLowerCase() === wanted);
590
+ if (index === -1) {
591
+ throw friendly({
592
+ message: `The grid has no "${title}" column. Its columns: ${columns.filter(Boolean).join(', ')}.`,
593
+ hint: 'Use the column title as the grid shows it; a hidden column is added with the "Columns" button of the grid.',
594
+ });
595
+ }
596
+ return index;
597
+ }
598
+
599
+ /**
600
+ * The rows of a grid that contain a text.
601
+ *
602
+ * @param {{rows: import('playwright').Locator}} g
603
+ * @param {string} text
604
+ * @returns {import('playwright').Locator}
605
+ */
606
+ function gridRows(g, text) {
607
+ return g.rows.filter({ hasText: literal(text) });
608
+ }
609
+
610
+ /**
611
+ * What the grid shows, for a failure message.
612
+ *
613
+ * @param {{rows: import('playwright').Locator}} g
614
+ * @returns {Promise<string>}
615
+ */
616
+ async function gridSeen(g) {
617
+ const texts = await g.rows.allInnerTexts().catch(() => []);
618
+ if (!texts.length) return 'an empty grid';
619
+ return `${texts.length} row(s): ` + texts.slice(0, 5).map((text) => `"${clean(text).slice(0, 80)}"`).join(', ') + (texts.length > 5 ? ', …' : '');
620
+ }
621
+
622
+ /**
623
+ * Remove every filter of the grid (the keyword too), when one is set.
624
+ *
625
+ * @param {object} world
626
+ */
627
+ async function clearGrid(world) {
628
+ const g = await grid(world);
629
+ if (g.kind === 'ui') {
630
+ const clear = g.header.locator('.admin__data-grid-filters-current._show button.action-clear');
631
+ if (await clear.count() && await clear.first().isVisible()) {
632
+ await clear.first().click();
633
+ await settle(world);
634
+ }
635
+ return;
636
+ }
637
+ const reset = g.wrap.locator('button[data-action="grid-filter-reset"]').first();
638
+ const filled = await g.table.locator('thead tr.data-grid-filters').locator('input[type="text"], select').evaluateAll((controls) => controls.some((control) => control.value !== ''));
639
+ if (filled && await reset.count()) {
640
+ await actAndSettle(world, () => reset.click({ noWaitAfter: true }));
641
+ }
642
+ }
643
+
644
+ /**
645
+ * Run an action that changes what a UI grid remembers for the admin user (its
646
+ * page size, its sorting, its page) and wait until the grid has saved it. The
647
+ * grid posts its state to `mui/bookmark/save` about two seconds after a
648
+ * change: a scenario that ends before that leaves the old state behind for the
649
+ * next one.
650
+ *
651
+ * @param {object} world
652
+ * @param {Function} action
653
+ */
654
+ async function actAndSaveGridState(world, action) {
655
+ const saved = world.page.waitForResponse((response) => /\/mui\/bookmark\/save/.test(response.url()), { timeout: 6000 }).catch(() => null);
656
+ await action();
657
+ await settle(world);
658
+ await saved;
659
+ await settle(world);
660
+ }
661
+
662
+ /**
663
+ * Search a UI grid by keyword.
664
+ *
665
+ * @param {object} world
666
+ * @param {string} keyword
667
+ */
668
+ async function searchGrid(world, keyword) {
669
+ const g = await grid(world);
670
+ if (g.kind !== 'ui') {
671
+ throw friendly({
672
+ message: 'This grid has no keyword search.',
673
+ hint: 'Filter it by a column instead: `When I filter the grid by "Rule" with "…"`.',
674
+ });
675
+ }
676
+ const box = g.header.getByRole('textbox', { name: 'Search by keyword' }).first();
677
+ await box.fill(keyword);
678
+ await box.press('Enter');
679
+ await settle(world);
680
+ }
681
+
682
+ /**
683
+ * Filter a grid by one field: the Filters panel of a UI grid (field by its
684
+ * label), the filter row of a legacy grid (field under the column title).
685
+ *
686
+ * @param {object} world
687
+ * @param {string} label
688
+ * @param {string} value
689
+ */
690
+ async function filterGrid(world, label, value) {
691
+ const g = await grid(world);
692
+ if (g.kind === 'ui') {
693
+ const panel = g.header.locator('.admin__data-grid-filters-wrap');
694
+ if (!/(^|\s)_show(\s|$)/.test((await panel.getAttribute('class')) || '')) {
695
+ await g.header.locator('button[data-action="grid-filter-expand"]').click();
696
+ await panel.locator('.admin__data-grid-filters-footer').waitFor({ state: 'visible', timeout: budget(world) });
697
+ }
698
+ const field = panel.locator('.admin__form-field').filter({ has: world.page.locator('label, legend', { hasText: exactly(label) }) }).last();
699
+ if (!(await field.count())) {
700
+ const labels = await panel.locator('.admin__form-field > label, .admin__form-field > legend').allInnerTexts();
701
+ throw friendly({
702
+ message: `The grid has no "${label}" filter. Its filters: ${[...new Set(labels.map(clean).filter(Boolean))].join(', ')}.`,
703
+ hint: 'Use the label of the field as the Filters panel shows it.',
704
+ });
705
+ }
706
+ const control = field.locator('select, input[type="text"]').first();
707
+ if ((await control.evaluate((el) => el.tagName)) === 'SELECT') {
708
+ await control.selectOption({ label: value });
709
+ } else {
710
+ await control.fill(value);
711
+ await control.dispatchEvent('change');
712
+ }
713
+ await panel.locator('button[data-action="grid-filter-apply"]').click();
714
+ await settle(world);
715
+ return;
716
+ }
717
+ const index = await gridColumnIndex(g, label);
718
+ const cell = g.table.locator('thead tr.data-grid-filters > *').nth(index);
719
+ const control = cell.locator('select, input[type="text"]').first();
720
+ if (!(await control.count())) {
721
+ throw friendly({
722
+ message: `The "${label}" column of this grid cannot be filtered.`,
723
+ hint: 'Filter by another column.',
724
+ });
725
+ }
726
+ if ((await control.evaluate((el) => el.tagName)) === 'SELECT') {
727
+ await control.selectOption({ label: value });
728
+ } else {
729
+ await control.fill(value);
730
+ }
731
+ await actAndSettle(world, () => g.wrap.locator('button[data-action="grid-filter-apply"]').first().click({ noWaitAfter: true }));
732
+ }
733
+
734
+ /**
735
+ * Tick the checkbox of the rows that contain a text.
736
+ *
737
+ * @param {object} world
738
+ * @param {string} text
739
+ * @returns {Promise<number>} how many rows were ticked
740
+ */
741
+ async function selectGridRows(world, text) {
742
+ const g = await grid(world);
743
+ const rows = gridRows(g, text);
744
+ const count = await rows.count();
745
+ for (let i = 0; i < count; i += 1) {
746
+ const box = rows.nth(i).locator('input[type="checkbox"]').first();
747
+ await box.check();
748
+ }
749
+ return count;
750
+ }
751
+
752
+ /**
753
+ * Run an action of the grid's "Actions" control on the ticked rows. A nested
754
+ * action is written "Change status > Disable".
755
+ *
756
+ * @param {object} world
757
+ * @param {string} action
758
+ */
759
+ async function runGridAction(world, action) {
760
+ const g = await grid(world);
761
+ const path = String(action).split('>').map(clean);
762
+ if (g.kind === 'ui') {
763
+ const wrap = g.header.locator('.action-select-wrap').filter({ has: world.page.locator(':scope > button.action-select') }).first();
764
+ await wrap.locator(':scope > button.action-select').click();
765
+ let scope = wrap.locator('.action-menu-items > ul.action-menu');
766
+ for (let i = 0; i < path.length; i += 1) {
767
+ const item = scope.locator(':scope > li').filter({ has: world.page.locator(':scope > .action-menu-item', { hasText: exactly(path[i]) }) }).first();
768
+ if (!(await item.count())) {
769
+ const all = await scope.locator(':scope > li > .action-menu-item').allInnerTexts();
770
+ throw friendly({
771
+ message: `The grid has no "${path[i]}" action. Its actions: ${all.map(clean).join(', ')}.`,
772
+ hint: 'Write a nested action as "Change status > Disable".',
773
+ });
774
+ }
775
+ const last = i === path.length - 1;
776
+ if (last) await actAndSettle(world, () => item.locator(':scope > .action-menu-item').click({ noWaitAfter: true }));
777
+ else await item.locator(':scope > .action-menu-item').click();
778
+ scope = item.locator(':scope > ul.action-submenu');
779
+ }
780
+ return;
781
+ }
782
+ const select = g.wrap.locator('select[id$="_massaction-select"]').first();
783
+ if (!(await select.count())) {
784
+ throw friendly({ message: 'This grid has no "Actions" control.', hint: 'Open the row and use the buttons of its page instead.' });
785
+ }
786
+ await select.selectOption({ label: path[0] });
787
+ await actAndSettle(world, () => g.wrap.locator('[id$="_massaction"] button', { hasText: /Submit/ }).first().click({ noWaitAfter: true }));
788
+ }
789
+
790
+ /**
791
+ * Open the row that contains a text: its "Edit" or "View" link, the "Edit"
792
+ * entry of its "Select" menu, or the row itself in a legacy grid.
793
+ *
794
+ * @param {object} world
795
+ * @param {string} text
796
+ */
797
+ async function openGridRow(world, text) {
798
+ const g = await grid(world);
799
+ const row = gridRows(g, text).first();
800
+ if (!(await row.count())) {
801
+ throw friendly({
802
+ message: `The grid has no row with "${text}". It shows ${await gridSeen(g)}.`,
803
+ hint: 'Search or filter the grid for the row first; a grid shows 20 rows a page.',
804
+ });
805
+ }
806
+ const direct = row.locator('td.data-grid-actions-cell > a.action-menu-item, td a', { hasText: /^\s*(Edit|View)\s*$/ }).first();
807
+ if (await direct.count() && await direct.isVisible()) {
808
+ await actAndSettle(world, () => direct.click({ noWaitAfter: true }));
809
+ return;
810
+ }
811
+ const menu = row.locator('button.action-select').first();
812
+ if (await menu.count()) {
813
+ await menu.click();
814
+ await actAndSettle(world, () => row.locator('a[data-action="item-edit"], ul.action-menu a.action-menu-item').first().click({ noWaitAfter: true }));
815
+ return;
816
+ }
817
+ await actAndSettle(world, () => row.locator('td', { hasText: literal(text) }).first().click({ noWaitAfter: true }));
818
+ }
819
+
820
+ // ---------------------------------------------------------------------------
821
+ // Admin forms
822
+ // ---------------------------------------------------------------------------
823
+ //
824
+ // A form field is an `.admin__field` with its label in `.admin__field-label`.
825
+ // The label is NOT always the accessible name of the control (several selects
826
+ // carry `aria-label="notice-…"`), so a field is found by the label text of its
827
+ // wrapper. The forms are KnockoutJS models that read an input on its `change`
828
+ // event: a value is filled, `change` is dispatched and the value is read back.
829
+
830
+ /**
831
+ * The form field with a label.
832
+ *
833
+ * @param {object} world
834
+ * @param {string} label
835
+ * @returns {Promise<import('playwright').Locator>}
836
+ */
837
+ async function formField(world, label) {
838
+ const page = world.page;
839
+ const text = quoted(clean(label));
840
+ const selector = [
841
+ `.admin__field:has(> .admin__field-label :text-is(${text}))`,
842
+ `.admin__field:has(> label.admin__field-label:text-is(${text}))`,
843
+ `.admin__field:has(> .admin__field-label:text-is(${text}))`,
844
+ `.admin__field:has(> legend.admin__field-label :text-is(${text}))`,
845
+ ].join(', ');
846
+ const fields = page.locator(selector);
847
+ try {
848
+ await fields.first().waitFor({ state: 'attached', timeout: budget(world) });
849
+ } catch {
850
+ const labels = await page.locator('.admin__field:visible > .admin__field-label').allInnerTexts().catch(() => []);
851
+ throw friendly({
852
+ message: `The form has no "${label}" field. Visible fields: ${[...new Set(labels.map(clean).filter(Boolean))].slice(0, 30).join(', ') || '(none)'}.`,
853
+ hint: 'A field of a closed section is not visible: open the section first (`When I open the "…" form section`).',
854
+ });
855
+ }
856
+ const count = await fields.count();
857
+ for (let i = 0; i < count; i += 1) {
858
+ if (await fields.nth(i).isVisible()) return fields.nth(i);
859
+ }
860
+ throw friendly({
861
+ message: `The "${label}" field is in the form but not visible.`,
862
+ hint: 'Open its section or tab first (`When I open the "…" form section`, `When I open the "…" admin tab`).',
863
+ });
864
+ }
865
+
866
+ /**
867
+ * The control of a form field (the first input, select or textarea that is not
868
+ * hidden).
869
+ *
870
+ * @param {import('playwright').Locator} field
871
+ * @returns {import('playwright').Locator}
872
+ */
873
+ function formControl(field) {
874
+ return field.locator('input:not([type="hidden"]):not([type="file"]), select, textarea').first();
875
+ }
876
+
877
+ /**
878
+ * Set a form field: text, select (by option text) or switch/checkbox
879
+ * ("Yes"/"No"). The value is read back; a model that did not take it fails the
880
+ * step.
881
+ *
882
+ * @param {object} world
883
+ * @param {string} label
884
+ * @param {string} value
885
+ */
886
+ async function setFormField(world, label, value) {
887
+ const field = await formField(world, label);
888
+ const control = formControl(field);
889
+ const info = await control.evaluate((el) => ({ tag: el.tagName, type: (el.getAttribute('type') || '').toLowerCase(), multiple: Boolean(el.multiple) }));
890
+ if (info.tag === 'SELECT') {
891
+ const labels = info.multiple ? String(value).split(',').map(clean).map((item) => ({ label: item })) : { label: value };
892
+ await actOrExplain('select', `${value} in ${label}`, () => control.selectOption(labels, { timeout: budget(world) }), `Check the option texts of the "${label}" field.`);
893
+ return;
894
+ }
895
+ if (info.type === 'checkbox' || info.type === 'radio') {
896
+ const on = /^(yes|on|true|1|enabled|checked)$/i.test(clean(value));
897
+ if ((await control.isChecked()) !== on) {
898
+ const toggle = field.locator('label.admin__actions-switch-label, label[for]').last();
899
+ if (await toggle.count()) await toggle.click();
900
+ else await control.setChecked(on, { force: true });
901
+ }
902
+ if ((await control.isChecked()) !== on) {
903
+ throw friendly({ message: `The "${label}" switch did not turn ${on ? 'on' : 'off'}.`, hint: 'The switch may be disabled for this record or scope.' });
904
+ }
905
+ return;
906
+ }
907
+ for (let attempt = 0; attempt < 2; attempt += 1) {
908
+ await control.fill(String(value));
909
+ await control.dispatchEvent('change');
910
+ await control.blur();
911
+ if ((await control.inputValue()) === String(value)) return;
912
+ }
913
+ throw friendly({
914
+ message: `The "${label}" field holds "${await control.inputValue()}" after filling it with "${value}".`,
915
+ hint: 'The form rewrote the value (a mask, a length limit or a value copied from another field).',
916
+ });
917
+ }
918
+
919
+ /**
920
+ * Open (or close) a collapsible section of a form by its title.
921
+ *
922
+ * @param {object} world
923
+ * @param {string} title
924
+ * @param {boolean} open
925
+ */
926
+ async function toggleFormSection(world, title, open) {
927
+ const page = world.page;
928
+ // The title element also holds two hidden tooltips ("Changes have been made to this section…"): the name is its first span.
929
+ const section = page.locator('.fieldset-wrapper, .admin__collapsible-block-wrapper').filter({ has: page.locator(':scope > .fieldset-wrapper-title .admin__collapsible-title > span:first-child, :scope > .fieldset-wrapper-title > .title', { hasText: exactly(title) }) }).last();
930
+ try {
931
+ await section.waitFor({ state: 'visible', timeout: budget(world) });
932
+ } catch {
933
+ const titles = await page.locator('.fieldset-wrapper:visible > .fieldset-wrapper-title').allInnerTexts().catch(() => []);
934
+ throw friendly({
935
+ message: `The form has no "${title}" section. Its sections: ${titles.map(clean).filter(Boolean).join(', ') || '(none)'}.`,
936
+ hint: 'Use the section title as the form shows it.',
937
+ });
938
+ }
939
+ const isOpen = async () => /(^|\s)_show(\s|$)/.test((await section.getAttribute('class')) || '');
940
+ if ((await isOpen()) !== open) {
941
+ await section.locator(':scope > .fieldset-wrapper-title').click();
942
+ const limit = Date.now() + budget(world);
943
+ while ((await isOpen()) !== open && Date.now() < limit) await page.waitForTimeout(100);
944
+ }
945
+ await settle(world);
946
+ }
947
+
948
+ module.exports = {
949
+ budget,
950
+ escapeRegExp,
951
+ literal,
952
+ exactly,
953
+ clean,
954
+ quoted,
955
+ siteRoot,
956
+ siteUrl,
957
+ adminPath,
958
+ adminUrl,
959
+ settle,
960
+ open,
961
+ actAndSettle,
962
+ actOrExplain,
963
+ assertPresence,
964
+ assertValue,
965
+ resolveUser,
966
+ MESSAGE_TYPES,
967
+ messages,
968
+ messagesSeen,
969
+ dialog,
970
+ answerDialog,
971
+ ADMIN_PAGES,
972
+ adminRoute,
973
+ adminUser,
974
+ requireAdminSession,
975
+ openAdmin,
976
+ grid,
977
+ gridColumns,
978
+ gridColumnIndex,
979
+ gridRows,
980
+ gridSeen,
981
+ clearGrid,
982
+ actAndSaveGridState,
983
+ searchGrid,
984
+ filterGrid,
985
+ selectGridRows,
986
+ runGridAction,
987
+ openGridRow,
988
+ formField,
989
+ formControl,
990
+ setFormField,
991
+ toggleFormSection,
992
+ };