@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,856 @@
1
+ 'use strict';
2
+
3
+ // Admin panel step definitions: the session (log in by account handle, log
4
+ // out, who is logged in), named pages and the page title, the menu, the access
5
+ // denied page, the grids (keyword search, filters, sorting, paging, row
6
+ // selection, actions, cell values), the forms (fields by label, switches,
7
+ // sections, tabs, field errors, save) and the page buttons.
8
+ //
9
+ // Content-specific steps (catalog, orders, customers, configuration, cache and
10
+ // index, clean-up) are in magento-admin-content.steps.js.
11
+ //
12
+ // The selectors come from the pages as a browser shows them; see
13
+ // exploration/01…05 in the repository.
14
+
15
+ const { Given, When, Then } = require('@cucumber/cucumber');
16
+ const { friendly } = require('webship-js/tests/step-definitions/webship');
17
+ const {
18
+ budget,
19
+ clean,
20
+ literal,
21
+ exactly,
22
+ quoted,
23
+ adminUrl,
24
+ settle,
25
+ open,
26
+ actAndSettle,
27
+ actOrExplain,
28
+ assertPresence,
29
+ assertValue,
30
+ resolveUser,
31
+ adminRoute,
32
+ adminUser,
33
+ requireAdminSession,
34
+ openAdmin,
35
+ grid,
36
+ gridColumnIndex,
37
+ gridRows,
38
+ gridSeen,
39
+ clearGrid,
40
+ actAndSaveGridState,
41
+ searchGrid,
42
+ filterGrid,
43
+ selectGridRows,
44
+ runGridAction,
45
+ openGridRow,
46
+ formField,
47
+ formControl,
48
+ setFormField,
49
+ toggleFormSection,
50
+ } = require('./magento-helpers');
51
+
52
+ const SESSION_HINT = 'The admin accounts are named in worldParameters.users of cucumber.js and created by the site build script. Two-factor authentication and the CAPTCHA must be off on a test site.';
53
+ const GRID_HINT = 'Open the list page first (`When I go to the "products" admin page`); a grid opened by that step starts without filters.';
54
+
55
+ // ---------------------------------------------------------------------------
56
+ // Session
57
+ // ---------------------------------------------------------------------------
58
+
59
+ /**
60
+ * Sign in on the admin sign-in form with a username and a password, without
61
+ * asserting the result.
62
+ *
63
+ * @param {object} world
64
+ * @param {string} username
65
+ * @param {string} password
66
+ */
67
+ async function submitAdminLogin(world, username, password) {
68
+ const page = world.page;
69
+ await open(world, adminUrl(world, ''));
70
+ const current = await adminUser(world);
71
+ if (current) {
72
+ await open(world, adminUrl(world, 'admin/auth/logout'));
73
+ }
74
+ await actOrExplain('fill in the admin sign-in form', username, async () => {
75
+ await page.locator('#username').fill(username, { timeout: budget(world) });
76
+ await page.locator('#login').fill(password);
77
+ }, 'The sign-in form (`#username`, `#login`) did not show: check `adminPath` in cucumber.js against the admin address of the site.');
78
+ await actAndSettle(world, () => page.locator('.action-login').click({ noWaitAfter: true }));
79
+ // The sign-in ends in one of two ways: the admin header, or an error on the form.
80
+ await page.locator('.admin-user .admin-user-account-text, .login-content .messages .message').first().waitFor({ state: 'visible', timeout: budget(world) }).catch(() => {});
81
+ }
82
+
83
+ /**
84
+ * Log in to the admin panel as an account of the users registry in cucumber.js
85
+ * (`worldParameters.users`), by its handle. A session of the same user is
86
+ * reused; another user is logged out first. The step ends when the admin
87
+ * header shows the username: an account with a restricted role does not land
88
+ * on the Dashboard.
89
+ *
90
+ * Example #1: Given I am logged in to the admin panel as "admin"
91
+ * Example #2: Given I am logged in to the admin panel as "sales"
92
+ * Example #3: When I log in to the admin panel as "admin"
93
+ * Example #4: Given we are logged in to the admin panel as "admin"
94
+ * Example #5: When we log in to the admin panel as "sales"
95
+ *
96
+ */
97
+ Given(/^(?:(?:I am |we are )+logged in|(?:I |we )*log in) to the admin panel as "([^"]*)"$/, async function (handle) {
98
+ const account = resolveUser(this, handle, 'admin');
99
+ await open(this, adminUrl(this, ''));
100
+ if ((await adminUser(this)) === account.login) return;
101
+ await submitAdminLogin(this, account.login, account.password);
102
+ const name = await adminUser(this);
103
+ if (name !== account.login) {
104
+ const error = clean(await this.page.locator('.message-error').first().innerText().catch(() => ''));
105
+ throw friendly({
106
+ message: `Could not log in to the admin panel as "${handle}" (${account.login}).` + (error ? ` The page says: "${error}".` : ''),
107
+ hint: SESSION_HINT,
108
+ });
109
+ }
110
+ });
111
+
112
+ /**
113
+ * Submit the admin sign-in form with a username and a password, for the
114
+ * scenarios that check a refused sign-in. Nothing is asserted: follow it with a
115
+ * message or a session assertion.
116
+ *
117
+ * Example #1: When I log in to the admin panel with the username "admin" and the password "wrong-password"
118
+ * Example #2: When I log in to the admin panel with the username "nobody" and the password "Secret123456789!"
119
+ * Example #3: And I log in to the admin panel with the username "sales" and the password "wrong"
120
+ * Example #4: When we log in to the admin panel with the username "admin" and the password "wrong-password"
121
+ * Example #5: When log in to the admin panel with the username "admin" and the password ""
122
+ *
123
+ */
124
+ When(/^(I |we )*log in to the admin panel with the username "([^"]*)" and the password "([^"]*)"$/, async function (pronounCase, username, password) {
125
+ await submitAdminLogin(this, username, password);
126
+ });
127
+
128
+ /**
129
+ * Log out of the admin panel through the account menu of the header.
130
+ *
131
+ * Example #1: When I log out of the admin panel
132
+ * Example #2: And I log out of the admin panel
133
+ * Example #3: When we log out of the admin panel
134
+ * Example #4: When log out of the admin panel
135
+ * Example #5: And we log out of the admin panel
136
+ *
137
+ */
138
+ When(/^(I |we )*log out of the admin panel$/, async function (pronounCase) {
139
+ const page = this.page;
140
+ if (!(await adminUser(this))) {
141
+ await open(this, adminUrl(this, ''));
142
+ if (!(await adminUser(this))) {
143
+ throw friendly({ message: 'Nobody is logged in to the admin panel, so there is nothing to log out of.', hint: 'Log in first: `Given I am logged in to the admin panel as "admin"`.' });
144
+ }
145
+ }
146
+ await actOrExplain('log out of', 'the admin panel', async () => {
147
+ await page.locator('.admin-user .admin__action-dropdown').click();
148
+ await actAndSettle(this, () => page.locator('.admin-user a.account-signout').click({ noWaitAfter: true }));
149
+ }, 'The account menu of the admin header (`.admin-user`) holds the "Sign Out" link.');
150
+ });
151
+
152
+ /**
153
+ * Make sure nobody is logged in to the admin panel (logs out when somebody
154
+ * is).
155
+ *
156
+ * Example #1: Given I am not logged in to the admin panel
157
+ * Example #2: Given we are not logged in to the admin panel
158
+ * Example #3: And I am not logged in to the admin panel
159
+ * Example #4: Given am not logged in to the admin panel
160
+ * Example #5: And we are not logged in to the admin panel
161
+ *
162
+ */
163
+ Given(/^(I |we )*(?:am|are) not logged in to the admin panel$/, async function (pronounCase) {
164
+ await open(this, adminUrl(this, ''));
165
+ if (await adminUser(this)) await open(this, adminUrl(this, 'admin/auth/logout'));
166
+ });
167
+
168
+ /**
169
+ * Assert somebody is (or nobody is) logged in to the admin panel, optionally
170
+ * which account of the users registry.
171
+ *
172
+ * Example #1: Then I should be logged in to the admin panel
173
+ * Example #2: Then I should not be logged in to the admin panel
174
+ * Example #3: Then I should be logged in to the admin panel as "admin"
175
+ * Example #4: Then we should be logged in to the admin panel as "sales"
176
+ * Example #5: And I should not be logged in to the admin panel as "sales"
177
+ *
178
+ */
179
+ Then(/^(I |we )*should( not)* be logged in to the admin panel(?: as "([^"]*)")?$/, async function (pronounCase, notCase, handle) {
180
+ await settle(this);
181
+ const name = await adminUser(this);
182
+ const wanted = handle ? resolveUser(this, handle, 'admin').login : null;
183
+ const holds = wanted ? name === wanted : name !== '';
184
+ if (holds === Boolean(notCase)) {
185
+ throw friendly({
186
+ message: notCase
187
+ ? `Expected ${wanted ? `"${wanted}" not to be logged in` : 'nobody to be logged in'} to the admin panel, but the header shows "${name}".`
188
+ : `Expected ${wanted ? `"${wanted}"` : 'somebody'} to be logged in to the admin panel, but ${name ? `the header shows "${name}"` : 'nobody is (the page has no admin header)'}.`,
189
+ hint: 'The admin header shows the username in `.admin-user-account-text`. ' + SESSION_HINT,
190
+ });
191
+ }
192
+ });
193
+
194
+ // ---------------------------------------------------------------------------
195
+ // Pages, title, menu, access denied
196
+ // ---------------------------------------------------------------------------
197
+
198
+ /**
199
+ * Open an admin page by the name of its menu item ("products", "orders",
200
+ * "customers", "cart price rules", "pages", "cache management", …) or by its
201
+ * route ("sales/order"). A grid on the page starts without the filters the
202
+ * admin user left behind.
203
+ *
204
+ * Example #1: When I go to the "products" admin page
205
+ * Example #2: Given I am on the "orders" admin page
206
+ * Example #3: When I go to the "cart price rules" admin page
207
+ * Example #4: When we go to the "cache management" admin page
208
+ * Example #5: Given we are on the "sales/invoice" admin page
209
+ *
210
+ */
211
+ Given(/^(?:(?:I am |we are )+on|(?:I |we )*go to) the "([^"]*)" admin page$/, async function (name) {
212
+ await openAdmin(this, adminRoute(name), name);
213
+ if (await this.page.locator('.admin__data-grid-outer-wrap:visible, table.data-grid:visible').count()) {
214
+ await clearGrid(this);
215
+ }
216
+ });
217
+
218
+ /**
219
+ * Assert the heading of the admin page (`h1.page-title`): "Products",
220
+ * "New Product", "#000000003".
221
+ *
222
+ * Example #1: Then the admin page title should be "Products"
223
+ * Example #2: Then the admin page title should be "New Product"
224
+ * Example #3: And the admin page title should be "Cache Management"
225
+ * Example #4: Then the admin page title should not be "Dashboard"
226
+ * Example #5: Then the admin page title should be "Customers"
227
+ *
228
+ */
229
+ Then(/^the admin page title should( not)* be "([^"]*)"$/, async function (notCase, title) {
230
+ await settle(this);
231
+ await requireAdminSession(this, title);
232
+ await assertValue(this, () => this.page.locator('h1.page-title').first().innerText(), title, {
233
+ label: 'the admin page title',
234
+ notCase,
235
+ hint: 'The title is the `h1.page-title` of the page. On the access denied page it is "Magento Admin" only in the browser tab; assert `I should see the access denied page` there.',
236
+ });
237
+ });
238
+
239
+ /**
240
+ * The top-level entry of the admin menu with a name.
241
+ *
242
+ * @param {object} world
243
+ * @param {string} name
244
+ * @returns {import('playwright').Locator}
245
+ */
246
+ function menuTop(world, name) {
247
+ return world.page.locator('nav.admin__menu li.level-0').filter({ has: world.page.locator(':scope > a', { hasText: exactly(name) }) });
248
+ }
249
+
250
+ /**
251
+ * Assert a top-level entry (or, with a path "Sales > Orders", an item) is, or
252
+ * is not, in the admin menu. The menu holds only what the role of the user
253
+ * allows.
254
+ *
255
+ * Example #1: Then I should see the "Sales" admin menu
256
+ * Example #2: Then I should not see the "Catalog" admin menu
257
+ * Example #3: Then I should see the "Sales > Orders" admin menu
258
+ * Example #4: And I should not see the "Stores > Configuration" admin menu
259
+ * Example #5: Then we should see the "Catalog > Products" admin menu
260
+ *
261
+ */
262
+ Then(/^(I |we )*should( not)* see the "([^"]*)" admin menu$/, async function (pronounCase, notCase, path) {
263
+ await settle(this);
264
+ await requireAdminSession(this, 'the admin menu');
265
+ const parts = path.split('>').map(clean);
266
+ const top = menuTop(this, parts[0]);
267
+ let found = (await top.count()) > 0;
268
+ if (found && parts.length > 1) {
269
+ // The items of a closed panel are in the DOM but not rendered: read them by text content.
270
+ const items = await top.first().locator('.submenu a').evaluateAll((links) => links.map((link) => (link.textContent || '').replace(/\s+/g, ' ').trim()));
271
+ found = items.some((item) => item.toLowerCase() === parts[parts.length - 1].toLowerCase());
272
+ }
273
+ if (found === Boolean(notCase)) {
274
+ const tops = await this.page.locator('nav.admin__menu li.level-0 > a').evaluateAll((links) => links.map((link) => (link.textContent || '').replace(/\s+/g, ' ').trim()));
275
+ throw friendly({
276
+ message: notCase ? `Expected the admin menu not to hold "${path}", but it does.` : `Expected the admin menu to hold "${path}". Its top-level entries: ${tops.join(', ') || '(none)'}.`,
277
+ hint: 'The menu shows what the role of the logged-in user allows. Write an item as "Sales > Orders".',
278
+ });
279
+ }
280
+ });
281
+
282
+ /**
283
+ * Open an item of the admin menu the way a person does: click the top-level
284
+ * entry, then the item of its panel ("Catalog > Products",
285
+ * "Marketing > Cart Price Rules"). "Dashboard" is a direct link.
286
+ *
287
+ * Example #1: When I open the "Catalog > Products" admin menu item
288
+ * Example #2: When I open the "Sales > Orders" admin menu item
289
+ * Example #3: And I open the "Customers > All Customers" admin menu item
290
+ * Example #4: When we open the "Content > Pages" admin menu item
291
+ * Example #5: When I open the "Dashboard" admin menu item
292
+ *
293
+ */
294
+ When(/^(I |we )*open the "([^"]*)" admin menu item$/, async function (pronounCase, path) {
295
+ await settle(this);
296
+ await requireAdminSession(this, 'the admin menu');
297
+ const parts = path.split('>').map(clean);
298
+ const top = menuTop(this, parts[0]).first();
299
+ await actOrExplain('open the admin menu item', path, async () => {
300
+ await top.waitFor({ state: 'visible', timeout: budget(this) });
301
+ if (parts.length === 1) {
302
+ await actAndSettle(this, () => top.locator(':scope > a').click({ noWaitAfter: true }));
303
+ return;
304
+ }
305
+ await top.locator(':scope > a').click();
306
+ const item = top.locator('.submenu a').filter({ hasText: exactly(parts[parts.length - 1]) }).first();
307
+ await item.waitFor({ state: 'visible', timeout: budget(this) });
308
+ await actAndSettle(this, () => item.click({ noWaitAfter: true }));
309
+ }, 'Write the path as the menu shows it: "Catalog > Products". The menu holds only what the role of the user allows.');
310
+ });
311
+
312
+ /**
313
+ * Assert the admin panel shows (or does not show) its access denied page
314
+ * ("Sorry, you need permissions to view this content."), which it serves with
315
+ * the status 403 to a user whose role does not allow the page.
316
+ *
317
+ * Example #1: Then I should see the access denied page
318
+ * Example #2: Then I should not see the access denied page
319
+ * Example #3: And I should see the access denied page
320
+ * Example #4: Then we should see the access denied page
321
+ * Example #5: And we should not see the access denied page
322
+ *
323
+ */
324
+ Then(/^(I |we )*should( not)* see the access denied page$/, async function (pronounCase, notCase) {
325
+ await settle(this);
326
+ await requireAdminSession(this, 'the page');
327
+ await assertPresence(this.page.locator('.access-denied-page'), notCase, {
328
+ label: 'the access denied page',
329
+ hint: 'The admin panel shows `.access-denied-page` ("Sorry, you need permissions to view this content.") when the role of the user does not allow the page.',
330
+ timeout: notCase ? 3000 : budget(this),
331
+ found: async () => `the page "${clean(await this.page.locator('h1.page-title, h1').first().innerText().catch(() => ''))}"`,
332
+ });
333
+ });
334
+
335
+ /**
336
+ * Click a button of the page's action bar (`.page-main-actions`: "Add New
337
+ * Page", "Hold", "Delete", "Flush Cache Storage") or of the bar above the
338
+ * category tree ("Add Subcategory") and wait for what follows.
339
+ *
340
+ * Example #1: When I click the "Add New Page" page action
341
+ * Example #2: When I click the "Hold" page action
342
+ * Example #3: And I click the "Add Subcategory" page action
343
+ * Example #4: When we click the "Flush Cache Storage" page action
344
+ * Example #5: When I click the "Back" page action
345
+ *
346
+ */
347
+ When(/^(I |we )*click the "([^"]*)" page action$/, async function (pronounCase, name) {
348
+ await settle(this);
349
+ // The action bar of the page, and the buttons above the category tree ("Add Subcategory").
350
+ const bar = this.page.locator('.page-main-actions:visible, .sidebar-actions:visible');
351
+ const button = bar.locator('button:visible').filter({ hasText: exactly(name) }).first();
352
+ if (!(await button.count())) {
353
+ const all = await bar.locator('button:visible').allInnerTexts().catch(() => []);
354
+ throw friendly({
355
+ message: `The page has no "${name}" action button. Its buttons: ${all.map(clean).filter(Boolean).join(', ') || '(none)'}.`,
356
+ hint: 'The buttons depend on the state of the record (an invoiced order has no "Invoice" button) and on the role of the user.',
357
+ });
358
+ }
359
+ await actAndSettle(this, () => button.click({ noWaitAfter: true }));
360
+ });
361
+
362
+ // ---------------------------------------------------------------------------
363
+ // Grids
364
+ // ---------------------------------------------------------------------------
365
+
366
+ /**
367
+ * Search the grid of the page by keyword (the "Search by keyword" box of a
368
+ * list such as products, orders, customers or pages).
369
+ *
370
+ * Example #1: When I search the grid for "Joust Duffle Bag"
371
+ * Example #2: When I search the grid for "24-MB01"
372
+ * Example #3: And I search the grid for "customer@example.com"
373
+ * Example #4: When we search the grid for "000000003"
374
+ * Example #5: When search the grid for "Home Page"
375
+ *
376
+ */
377
+ When(/^(I |we )*search the grid for "([^"]*)"$/, async function (pronounCase, keyword) {
378
+ await searchGrid(this, keyword);
379
+ });
380
+
381
+ /**
382
+ * Filter the grid by one field: a field of the "Filters" panel by its label
383
+ * (a text or an option of a select), or, in an older grid, the filter under
384
+ * the column title.
385
+ *
386
+ * Example #1: When I filter the grid by "Name" with "Tank"
387
+ * Example #2: When I filter the grid by "Type" with "Configurable Product"
388
+ * Example #3: And I filter the grid by "Status" with "Enabled"
389
+ * Example #4: When we filter the grid by "Rule" with "20% OFF"
390
+ * Example #5: When I filter the grid by "SKU" with "24-MB01"
391
+ *
392
+ */
393
+ When(/^(I |we )*filter the grid by "([^"]*)" with "([^"]*)"$/, async function (pronounCase, label, value) {
394
+ await filterGrid(this, label, value);
395
+ });
396
+
397
+ /**
398
+ * Remove every filter of the grid, the keyword included ("Clear all", or
399
+ * "Reset Filter" in an older grid).
400
+ *
401
+ * Example #1: When I clear the grid filters
402
+ * Example #2: And I clear the grid filters
403
+ * Example #3: When we clear the grid filters
404
+ * Example #4: When clear the grid filters
405
+ * Example #5: And we clear the grid filters
406
+ *
407
+ */
408
+ When(/^(I |we )*clear the grid filters$/, async function (pronounCase) {
409
+ await clearGrid(this);
410
+ });
411
+
412
+ /**
413
+ * Assert how many records the grid found ("19 records found" in its toolbar),
414
+ * over all its pages.
415
+ *
416
+ * Example #1: Then the grid should show 19 records
417
+ * Example #2: Then the grid should show 1 record
418
+ * Example #3: And the grid should show 0 records
419
+ * Example #4: Then the grid should show 2040 records
420
+ * Example #5: Then the grid should show 4 records
421
+ *
422
+ */
423
+ Then(/^the grid should show (\d+) records?$/, async function (count) {
424
+ const g = await grid(this);
425
+ await assertValue(this, async () => {
426
+ const text = clean(await g.header.innerText());
427
+ const match = text.match(/(\d+)\s+records? found/i);
428
+ return match ? match[1] : `no "records found" text (toolbar: ${text.slice(0, 80)})`;
429
+ }, String(count), { label: 'the number of records the grid found', hint: GRID_HINT });
430
+ });
431
+
432
+ /**
433
+ * Assert how many rows the grid shows on the current page.
434
+ *
435
+ * Example #1: Then the grid should have 20 rows
436
+ * Example #2: Then the grid should have 1 row
437
+ * Example #3: And the grid should have 50 rows
438
+ * Example #4: Then the grid should have 0 rows
439
+ * Example #5: Then the grid should have 19 rows
440
+ *
441
+ */
442
+ Then(/^the grid should have (\d+) rows?$/, async function (count) {
443
+ const g = await grid(this);
444
+ await assertValue(this, async () => String(await g.rows.count()), String(count), { label: 'the number of rows on this page of the grid', hint: GRID_HINT });
445
+ });
446
+
447
+ /**
448
+ * Assert a row with a text is (or is not) in the grid, on the current page.
449
+ *
450
+ * Example #1: Then I should see the "Joust Duffle Bag" grid row
451
+ * Example #2: Then I should not see the "MCP Round Bag" grid row
452
+ * Example #3: And I should see the "customer@example.com" grid row
453
+ * Example #4: Then we should see the "000000003" grid row
454
+ * Example #5: Then should not see the "Test Rule" grid row
455
+ *
456
+ */
457
+ Then(/^(I |we )*should( not)* see the "([^"]*)" grid row$/, async function (pronounCase, notCase, text) {
458
+ const g = await grid(this);
459
+ await assertPresence(gridRows(g, text), notCase, {
460
+ label: `a grid row with "${text}"`,
461
+ hint: GRID_HINT + ' Search or filter the grid for the row: it shows 20 rows a page.',
462
+ timeout: notCase ? 3000 : budget(this),
463
+ found: () => gridSeen(g),
464
+ });
465
+ });
466
+
467
+ /**
468
+ * Assert the value of a column in the row that contains a text.
469
+ *
470
+ * Example #1: Then the "Status" column of the "Joust Duffle Bag" grid row should be "Enabled"
471
+ * Example #2: Then the "Price" column of the "24-MB01" grid row should be "$34.00"
472
+ * Example #3: And the "Status" column of the "000000003" grid row should be "Pending"
473
+ * Example #4: Then the "Group" column of the "customer@example.com" grid row should be "General"
474
+ * Example #5: Then the "Status" column of the "Configuration" grid row should not be "INVALIDATED"
475
+ *
476
+ */
477
+ Then(/^the "([^"]*)" column of the "([^"]*)" grid row should( not)* be "([^"]*)"$/, async function (column, text, notCase, value) {
478
+ const g = await grid(this);
479
+ const index = await gridColumnIndex(g, column);
480
+ const row = gridRows(g, text).first();
481
+ if (!(await row.count())) {
482
+ throw friendly({ message: `The grid has no row with "${text}". It shows ${await gridSeen(g)}.`, hint: GRID_HINT });
483
+ }
484
+ await assertValue(this, () => row.locator(':scope > td').nth(index).innerText(), value, {
485
+ label: `the "${column}" column of the "${text}" row`,
486
+ notCase,
487
+ hint: 'The value is compared with the whole text of the cell.',
488
+ });
489
+ });
490
+
491
+ /**
492
+ * Sort the grid by a column: one click sorts ascending, a click on the sorted
493
+ * column reverses it. The step clicks until the column has the direction asked
494
+ * for.
495
+ *
496
+ * Example #1: When I sort the grid by "Name" ascending
497
+ * Example #2: When I sort the grid by "Name" descending
498
+ * Example #3: And I sort the grid by "ID" ascending
499
+ * Example #4: When we sort the grid by "Price" descending
500
+ * Example #5: When sort the grid by "SKU" ascending
501
+ *
502
+ */
503
+ When(/^(I |we )*sort the grid by "([^"]*)" (ascending|descending)$/, async function (pronounCase, column, direction) {
504
+ const g = await grid(this);
505
+ const index = await gridColumnIndex(g, column);
506
+ const head = g.table.locator('thead tr').first().locator('th').nth(index);
507
+ const wanted = direction === 'ascending' ? '_ascend' : '_descend';
508
+ for (let click = 0; click < 3; click += 1) {
509
+ if (new RegExp(`(^|\\s)${wanted}(\\s|$)`).test((await head.getAttribute('class')) || '')) return;
510
+ if (g.kind === 'ui') await actAndSaveGridState(this, () => head.click());
511
+ else await actAndSettle(this, () => head.click({ noWaitAfter: true }));
512
+ }
513
+ throw friendly({
514
+ message: `The "${column}" column did not sort ${direction}.`,
515
+ hint: 'Only a column with the sort arrows (`th._sortable`) can be sorted.',
516
+ });
517
+ });
518
+
519
+ /**
520
+ * Assert the values of a column on the current page are in order.
521
+ *
522
+ * Example #1: Then the grid should be sorted by "Name" ascending
523
+ * Example #2: Then the grid should be sorted by "Name" descending
524
+ * Example #3: And the grid should be sorted by "SKU" ascending
525
+ * Example #4: Then the grid should be sorted by "ID" descending
526
+ * Example #5: Then the grid should be sorted by "Price" ascending
527
+ *
528
+ */
529
+ Then(/^the grid should be sorted by "([^"]*)" (ascending|descending)$/, async function (column, direction) {
530
+ const g = await grid(this);
531
+ const index = await gridColumnIndex(g, column);
532
+ const values = (await g.rows.evaluateAll((rows, i) => rows.map((row) => (row.children[i] ? row.children[i].innerText : '')), index)).map(clean);
533
+ const key = (value) => {
534
+ const number = Number(value.replace(/[$,\s]/g, ''));
535
+ return value !== '' && !Number.isNaN(number) ? number : value.toLowerCase();
536
+ };
537
+ for (let i = 1; i < values.length; i += 1) {
538
+ const a = key(values[i - 1]);
539
+ const b = key(values[i]);
540
+ const ordered = typeof a === 'number' && typeof b === 'number' ? (direction === 'ascending' ? a <= b : a >= b) : (direction === 'ascending' ? String(a).localeCompare(String(b)) <= 0 : String(a).localeCompare(String(b)) >= 0);
541
+ if (!ordered) {
542
+ throw friendly({
543
+ message: `The "${column}" column is not sorted ${direction}: "${values[i - 1]}" comes before "${values[i]}" (rows ${i} and ${i + 1}).`,
544
+ hint: 'Sort the grid first: `When I sort the grid by "…" ascending`.',
545
+ });
546
+ }
547
+ }
548
+ if (values.length < 2) {
549
+ throw friendly({ message: `The grid shows ${values.length} row(s): an order cannot be read from it.`, hint: 'Remove the filters so the grid shows several rows.' });
550
+ }
551
+ });
552
+
553
+ /**
554
+ * Go to a page of the grid: the next one, the previous one or a page by its
555
+ * number.
556
+ *
557
+ * Example #1: When I go to the next page of the grid
558
+ * Example #2: When I go to the previous page of the grid
559
+ * Example #3: When I go to page 5 of the grid
560
+ * Example #4: And we go to page 2 of the grid
561
+ * Example #5: When we go to the next page of the grid
562
+ *
563
+ */
564
+ When(/^(I |we )*go to (?:the (next|previous) page|page (\d+)) of the grid$/, async function (pronounCase, direction, number) {
565
+ const g = await grid(this);
566
+ const pager = g.header.locator('.admin__data-grid-pager').first();
567
+ if (direction) {
568
+ const button = pager.locator(direction === 'next' ? '.action-next' : '.action-previous');
569
+ if (await button.isDisabled()) {
570
+ throw friendly({ message: `The grid has no ${direction} page.`, hint: 'The pager button is disabled on the first or the last page.' });
571
+ }
572
+ await actAndSettle(this, () => button.click({ noWaitAfter: true }));
573
+ return;
574
+ }
575
+ const input = pager.locator('input').first();
576
+ await input.fill(String(number));
577
+ if (g.kind === 'ui') await actAndSaveGridState(this, () => input.press('Enter'));
578
+ else await actAndSettle(this, () => input.press('Enter'));
579
+ });
580
+
581
+ /**
582
+ * Assert the page number the grid is on.
583
+ *
584
+ * Example #1: Then the grid should be on page 2
585
+ * Example #2: Then the grid should be on page 1
586
+ * Example #3: And the grid should be on page 5
587
+ * Example #4: Then the grid should be on page 4
588
+ * Example #5: Then the grid should be on page 3
589
+ *
590
+ */
591
+ Then(/^the grid should be on page (\d+)$/, async function (number) {
592
+ const g = await grid(this);
593
+ await assertValue(this, () => g.header.locator('.admin__data-grid-pager input').first().inputValue(), String(number), { label: 'the page of the grid', hint: GRID_HINT });
594
+ });
595
+
596
+ /**
597
+ * Set how many rows the grid shows on a page (20, 30, 50, 100 or 200). The
598
+ * grid remembers it for the admin user: set it back at the end of a scenario.
599
+ *
600
+ * Example #1: When I show 50 grid rows per page
601
+ * Example #2: When I show 20 grid rows per page
602
+ * Example #3: And I show 100 grid rows per page
603
+ * Example #4: When we show 30 grid rows per page
604
+ * Example #5: When show 200 grid rows per page
605
+ *
606
+ */
607
+ When(/^(I |we )*show (\d+) grid rows per page$/, async function (pronounCase, size) {
608
+ const g = await grid(this);
609
+ if (g.kind !== 'ui') {
610
+ throw friendly({ message: 'This step sets the page size of a list with the "per page" menu; this grid is of the older kind.', hint: 'Filter the older grid by a column instead, so the row is on its first page.' });
611
+ }
612
+ const menu = g.header.locator('.selectmenu').first();
613
+ await menu.locator('.selectmenu-toggle').click();
614
+ const item = menu.locator('button.selectmenu-item-action').filter({ hasText: exactly(String(size)) }).first();
615
+ if (!(await item.count())) {
616
+ throw friendly({ message: `The grid has no "${size}" rows per page choice.`, hint: 'The choices are 20, 30, 50, 100 and 200.' });
617
+ }
618
+ // The grid keeps the page size for the admin user: wait until it is saved.
619
+ await actAndSaveGridState(this, () => item.click());
620
+ });
621
+
622
+ /**
623
+ * Tick the checkbox of the row (or rows) that contain a text, for a grid
624
+ * action.
625
+ *
626
+ * Example #1: When I select the "Joust Duffle Bag" grid row
627
+ * Example #2: When I select the "TEST-SKU-1" grid row
628
+ * Example #3: And I select the "customer@example.com" grid row
629
+ * Example #4: When we select the "000000003" grid row
630
+ * Example #5: When select the "Test review" grid row
631
+ *
632
+ */
633
+ When(/^(I |we )*select the "([^"]*)" grid row$/, async function (pronounCase, text) {
634
+ const count = await selectGridRows(this, text);
635
+ if (!count) {
636
+ const g = await grid(this);
637
+ throw friendly({ message: `The grid has no row with "${text}" to select. It shows ${await gridSeen(g)}.`, hint: GRID_HINT });
638
+ }
639
+ });
640
+
641
+ /**
642
+ * Run an action of the grid's "Actions" control on the selected rows
643
+ * ("Delete", "Change status > Disable", "Cancel", "Hold"). An action that asks
644
+ * for a confirmation opens a dialog: follow it with `I confirm the action`.
645
+ *
646
+ * Example #1: When I run the "Delete" grid action
647
+ * Example #2: When I run the "Change status > Disable" grid action
648
+ * Example #3: And I run the "Change status > Enable" grid action
649
+ * Example #4: When we run the "Hold" grid action
650
+ * Example #5: When I run the "Unsubscribe" grid action
651
+ *
652
+ */
653
+ When(/^(I |we )*run the "([^"]*)" grid action$/, async function (pronounCase, action) {
654
+ await runGridAction(this, action);
655
+ });
656
+
657
+ /**
658
+ * Open the grid row that contains a text: its "Edit" or "View" link, the
659
+ * "Edit" entry of its "Select" menu, or the row itself in an older grid.
660
+ *
661
+ * Example #1: When I open the "Joust Duffle Bag" grid row
662
+ * Example #2: When I open the "000000003" grid row
663
+ * Example #3: And I open the "customer@example.com" grid row
664
+ * Example #4: When we open the "Home Page" grid row
665
+ * Example #5: When I open the "Test Rule" grid row
666
+ *
667
+ */
668
+ When(/^(I |we )*open the "([^"]*)" grid row$/, async function (pronounCase, text) {
669
+ await openGridRow(this, text);
670
+ });
671
+
672
+ // ---------------------------------------------------------------------------
673
+ // Forms
674
+ // ---------------------------------------------------------------------------
675
+
676
+ /**
677
+ * Fill a field of an admin form, found by its label: a text field, a text
678
+ * area, or a select (the value is the option text; several options of a
679
+ * multi-select are separated by commas). The value is read back, so a field
680
+ * the form did not take fails here and not at Save.
681
+ *
682
+ * Example #1: When I set the "Product Name" form field to "Test Bag"
683
+ * Example #2: When I set the "SKU" form field to "TEST-SKU-1"
684
+ * Example #3: And I set the "Visibility" form field to "Catalog"
685
+ * Example #4: When we set the "Customer Groups" form field to "NOT LOGGED IN, General"
686
+ * Example #5: When I set the "Price" form field to "12.50"
687
+ *
688
+ */
689
+ When(/^(I |we )*set the "([^"]*)" form field to "([^"]*)"$/, async function (pronounCase, label, value) {
690
+ await setFormField(this, label, value);
691
+ });
692
+
693
+ /**
694
+ * Turn a switch of an admin form on or off ("Enable Product", "Enable Page",
695
+ * "Active").
696
+ *
697
+ * Example #1: When I turn the "Enable Product" form switch off
698
+ * Example #2: When I turn the "Enable Product" form switch on
699
+ * Example #3: And I turn the "Enable Page" form switch off
700
+ * Example #4: When we turn the "Active" form switch on
701
+ * Example #5: When I turn the "Include in Menu" form switch off
702
+ *
703
+ */
704
+ When(/^(I |we )*turn the "([^"]*)" form switch (on|off)$/, async function (pronounCase, label, state) {
705
+ await setFormField(this, label, state === 'on' ? 'yes' : 'no');
706
+ });
707
+
708
+ /**
709
+ * Assert the value of a field of an admin form: the text of a text field, the
710
+ * selected option of a select, "on" or "off" for a switch.
711
+ *
712
+ * Example #1: Then the "SKU" form field should be "TEST-SKU-1"
713
+ * Example #2: Then the "Visibility" form field should be "Catalog, Search"
714
+ * Example #3: And the "Enable Product" form field should be "on"
715
+ * Example #4: Then the "Price" form field should not be "0.00"
716
+ * Example #5: Then the "First Name" form field should be "Casey"
717
+ *
718
+ */
719
+ Then(/^the "([^"]*)" form field should( not)* be "([^"]*)"$/, async function (label, notCase, value) {
720
+ const field = await formField(this, label);
721
+ const control = formControl(field);
722
+ await assertValue(this, async () => control.evaluate((el) => {
723
+ if (el.tagName === 'SELECT') return [...el.selectedOptions].map((option) => option.textContent.replace(/\s+/g, ' ').trim()).join(', ');
724
+ if (el.type === 'checkbox' || el.type === 'radio') return el.checked ? 'on' : 'off';
725
+ return el.value;
726
+ }), value, { label: `the "${label}" form field`, notCase, hint: 'A switch reads "on" or "off"; a select reads the text of its selected option.' });
727
+ });
728
+
729
+ /**
730
+ * Choose an entry in a searchable tree field of an admin form (the
731
+ * "Categories" field of a product): open it, type the name, tick the entry,
732
+ * press Done.
733
+ *
734
+ * Example #1: When I choose "Bags" in the "Categories" form field
735
+ * Example #2: When I choose "Gear" in the "Categories" form field
736
+ * Example #3: And I choose "Watches" in the "Categories" form field
737
+ * Example #4: When we choose "Tops" in the "Categories" form field
738
+ * Example #5: When choose "Sale" in the "Categories" form field
739
+ *
740
+ */
741
+ When(/^(I |we )*choose "([^"]*)" in the "([^"]*)" form field$/, async function (pronounCase, option, label) {
742
+ const field = await formField(this, label);
743
+ const select = field.locator('.admin__action-multiselect-wrap').first();
744
+ if (!(await select.count())) {
745
+ throw friendly({ message: `The "${label}" field is not a searchable select.`, hint: 'Use `I set the "…" form field to "…"` for a plain field.' });
746
+ }
747
+ await actOrExplain('choose', `${option} in ${label}`, async () => {
748
+ if (!/(^|\s)_active(\s|$)/.test((await select.getAttribute('class')) || '')) {
749
+ await select.locator('[data-role="advanced-select"]').click();
750
+ }
751
+ const search = select.locator('input[data-role="advanced-select-text"]');
752
+ if (await search.count()) await search.fill(option);
753
+ // The typed text replaces the tree with a result list (name + path); the
754
+ // collapsed tree nodes stay in the DOM, hidden: only a visible label counts.
755
+ const target = select.locator('.action-menu label.admin__action-multiselect-label:visible')
756
+ .filter({ has: this.page.locator(`span:not(.admin__action-multiselect-item-path):text-is(${quoted(option)})`) }).first();
757
+ await target.waitFor({ state: 'visible', timeout: budget(this) });
758
+ await target.click();
759
+ const done = select.locator('button[data-action="close-advanced-select"]');
760
+ if (await done.count() && await done.first().isVisible()) await done.first().click();
761
+ }, 'Type the name as the tree shows it; the result list shows the name and its path.');
762
+ await assertPresence(select.locator('.admin__action-multiselect-crumb, .admin__action-multiselect-text').filter({ hasText: literal(option) }), null, {
763
+ label: `"${option}" as a chosen entry of "${label}"`,
764
+ hint: 'The chosen entries show as chips in the field.',
765
+ timeout: budget(this),
766
+ });
767
+ });
768
+
769
+ /**
770
+ * Open (or close) a collapsible section of an admin form by its title
771
+ * ("Content", "Images And Videos", "Search Engine Optimization", "Actions").
772
+ *
773
+ * Example #1: When I open the "Images And Videos" form section
774
+ * Example #2: When I open the "Search Engine Optimization" form section
775
+ * Example #3: And I open the "Actions" form section
776
+ * Example #4: When we open the "Content" form section
777
+ * Example #5: When I close the "Content" form section
778
+ *
779
+ */
780
+ When(/^(I |we )*(open|close) the "([^"]*)" form section$/, async function (pronounCase, verb, title) {
781
+ await toggleFormSection(this, title, verb === 'open');
782
+ });
783
+
784
+ /**
785
+ * Open a tab of an admin page by its name: the tabs of an order ("Invoices",
786
+ * "Shipments", "Credit Memos") or of a customer ("Account Information",
787
+ * "Addresses", "Orders").
788
+ *
789
+ * Example #1: When I open the "Invoices" admin tab
790
+ * Example #2: When I open the "Addresses" admin tab
791
+ * Example #3: And I open the "Account Information" admin tab
792
+ * Example #4: When we open the "Shipments" admin tab
793
+ * Example #5: When I open the "Credit Memos" admin tab
794
+ *
795
+ */
796
+ When(/^(I |we )*open the "([^"]*)" admin tab$/, async function (pronounCase, name) {
797
+ await settle(this);
798
+ // The link also holds hidden tooltips ("Changes have been made to this section…"): the name is its first span.
799
+ const item = this.page.locator('.admin__page-nav-item:visible').filter({ has: this.page.locator('a.admin__page-nav-link > span:first-child', { hasText: exactly(name) }) }).first();
800
+ if (!(await item.count())) {
801
+ const tabs = await this.page.locator('.admin__page-nav-item:visible a.admin__page-nav-link > span:first-child').allInnerTexts().catch(() => []);
802
+ throw friendly({ message: `The page has no "${name}" tab. Its tabs: ${tabs.map(clean).filter(Boolean).join(', ') || '(none)'}.`, hint: 'Use the tab name as the page shows it.' });
803
+ }
804
+ await actAndSettle(this, () => item.locator('a').first().click({ noWaitAfter: true }));
805
+ await assertValue(this, async () => ((await item.getAttribute('class')) || '').match(/_active|ui-tabs-active/) ? 'active' : 'inactive', 'active', {
806
+ label: `the "${name}" tab`,
807
+ hint: 'The active tab carries `_active` or `ui-tabs-active`.',
808
+ });
809
+ });
810
+
811
+ /**
812
+ * Assert a field of an admin form shows (or does not show) a validation error
813
+ * ("This is a required field.").
814
+ *
815
+ * Example #1: Then I should see the form error "This is a required field." for the "Product Name" field
816
+ * Example #2: Then I should see the form error "This is a required field." for the "SKU" field
817
+ * Example #3: And I should not see the form error "This is a required field." for the "Price" field
818
+ * Example #4: Then we should see the form error "This is a required field." for the "Rule Name" field
819
+ * Example #5: Then I should see the form error "This is a required field." for the "Page Title" field
820
+ *
821
+ */
822
+ Then(/^(I |we )*should( not)* see the form error "([^"]*)" for the "([^"]*)" field$/, async function (pronounCase, notCase, text, label) {
823
+ const field = await formField(this, label);
824
+ await assertPresence(field.locator('.admin__field-error, label.mage-error, div.mage-error').filter({ hasText: literal(text) }), notCase, {
825
+ label: `the error "${text}" under the "${label}" field`,
826
+ hint: 'The form validates when it is saved. A field that holds a value on screen but shows "required" was not read by the form: fill it with `I set the "…" form field to "…"`.',
827
+ timeout: notCase ? 3000 : budget(this),
828
+ found: async () => {
829
+ const errors = await this.page.locator('.admin__field-error:visible, label.mage-error:visible').allInnerTexts().catch(() => []);
830
+ return errors.length ? `the errors ${errors.map((error) => `"${clean(error)}"`).join(', ')}` : 'no field error';
831
+ },
832
+ });
833
+ });
834
+
835
+ /**
836
+ * Save the admin form with its main Save button ("Save", "Save Customer",
837
+ * "Save Config", "Save Review") and wait for the result. Follow it with a
838
+ * message or a form error assertion.
839
+ *
840
+ * Example #1: When I save the form
841
+ * Example #2: And I save the form
842
+ * Example #3: When we save the form
843
+ * Example #4: When save the form
844
+ * Example #5: And we save the form
845
+ *
846
+ */
847
+ When(/^(I |we )*save the form$/, async function (pronounCase) {
848
+ await settle(this);
849
+ const page = this.page;
850
+ const button = page.locator('.page-main-actions:visible').first().locator('#save-button, #save, #save_button, button.save.primary, button.primary[data-ui-id*="save"]').first();
851
+ if (!(await button.count())) {
852
+ const all = await page.locator('.page-main-actions:visible').first().locator('button:visible').allInnerTexts().catch(() => []);
853
+ throw friendly({ message: `The page has no Save button. Its buttons: ${all.map(clean).filter(Boolean).join(', ') || '(none)'}.`, hint: 'Open a form first (a new or an existing record).' });
854
+ }
855
+ await actAndSettle(this, () => button.click({ noWaitAfter: true }));
856
+ });