@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,818 @@
1
+ 'use strict';
2
+
3
+ // Admin panel content step definitions: products (the gallery, a product by
4
+ // SKU), the category tree, orders (open, status, comments, hold, invoice, ship,
5
+ // credit memo, cancel), customers, the configuration, the cache and index
6
+ // state, and the clean-up of what a scenario created.
7
+ //
8
+ // The generic admin steps (session, pages, menu, grids, forms) are in
9
+ // magento-admin.steps.js.
10
+ //
11
+ // The selectors come from the pages as a browser shows them; see
12
+ // exploration/03…05 in the repository.
13
+
14
+ const path = require('path');
15
+ const fs = require('fs');
16
+ const { spawn } = require('child_process');
17
+ const { Given, When, Then } = require('@cucumber/cucumber');
18
+ const { friendly } = require('webship-js/tests/step-definitions/webship');
19
+ const {
20
+ budget,
21
+ clean,
22
+ literal,
23
+ exactly,
24
+ settle,
25
+ actAndSettle,
26
+ actOrExplain,
27
+ assertPresence,
28
+ assertValue,
29
+ messages,
30
+ messagesSeen,
31
+ dialog,
32
+ answerDialog,
33
+ adminRoute,
34
+ openAdmin,
35
+ requireAdminSession,
36
+ grid,
37
+ gridRows,
38
+ gridSeen,
39
+ clearGrid,
40
+ searchGrid,
41
+ filterGrid,
42
+ selectGridRows,
43
+ runGridAction,
44
+ openGridRow,
45
+ } = require('./magento-helpers');
46
+
47
+ // ---------------------------------------------------------------------------
48
+ // Products
49
+ // ---------------------------------------------------------------------------
50
+
51
+ /**
52
+ * Open the edit form of a product by its SKU: the products grid is searched
53
+ * for the SKU and the row is opened.
54
+ *
55
+ * Example #1: When I open the product "24-MB01" in the admin panel
56
+ * Example #2: When I open the product "TEST-SKU-1" in the admin panel
57
+ * Example #3: And I open the product "WS12" in the admin panel
58
+ * Example #4: When we open the product "24-MB01" in the admin panel
59
+ * Example #5: When open the product "24-WG080" in the admin panel
60
+ *
61
+ */
62
+ When(/^(I |we )*open the product "([^"]*)" in the admin panel$/, async function (pronounCase, sku) {
63
+ await openAdmin(this, adminRoute('products'), 'products');
64
+ await clearGrid(this);
65
+ await searchGrid(this, sku);
66
+ const g = await grid(this);
67
+ const index = (await g.table.locator('thead tr').first().locator('th').allInnerTexts()).map(clean).indexOf('SKU');
68
+ const count = await g.rows.count();
69
+ for (let i = 0; i < count; i += 1) {
70
+ if (clean(await g.rows.nth(i).locator(':scope > td').nth(index).innerText()) === sku) {
71
+ await actAndSettle(this, () => g.rows.nth(i).locator('td.data-grid-actions-cell a').first().click({ noWaitAfter: true }));
72
+ // The keyword must not stay behind for the next visit of the grid.
73
+ return;
74
+ }
75
+ }
76
+ throw friendly({
77
+ message: `The products grid has no product with the SKU "${sku}". The search shows ${await gridSeen(g)}.`,
78
+ hint: 'Check the SKU. A product a scenario creates must be saved before it can be opened.',
79
+ });
80
+ });
81
+
82
+ /**
83
+ * Upload an image file to the gallery of the product form ("Images And
84
+ * Videos"). The file is looked up in `tests/fixtures/` of the project, then of
85
+ * this pack.
86
+ *
87
+ * Example #1: When I add the image "pixel.png" to the product gallery
88
+ * Example #2: And I add the image "pixel.png" to the product gallery
89
+ * Example #3: When we add the image "pixel.png" to the product gallery
90
+ * Example #4: When I add the image "photo.jpg" to the product gallery
91
+ * Example #5: When add the image "pixel.png" to the product gallery
92
+ *
93
+ */
94
+ When(/^(I |we )*add the image "([^"]*)" to the product gallery$/, async function (pronounCase, file) {
95
+ const candidates = [path.resolve(process.cwd(), 'tests', 'fixtures', file), path.resolve(__dirname, '..', 'fixtures', file), path.resolve(process.cwd(), file)];
96
+ const source = candidates.find((candidate) => fs.existsSync(candidate));
97
+ if (!source) {
98
+ throw friendly({ message: `The image "${file}" was not found.`, hint: `Put it in tests/fixtures/ of the project. Looked in: ${candidates.join(', ')}.` });
99
+ }
100
+ const gallery = this.page.locator('#media_gallery_content');
101
+ if (!(await gallery.isVisible().catch(() => false))) {
102
+ throw friendly({ message: 'The product gallery is not open.', hint: 'Open its section first: `When I open the "Images And Videos" form section`.' });
103
+ }
104
+ const before = await gallery.locator('.image.item:visible').count();
105
+ await gallery.locator('input[type="file"]').first().setInputFiles(source);
106
+ await assertValue(this, async () => String(await gallery.locator('.image.item:visible').count()), String(before + 1), {
107
+ label: 'the number of images in the product gallery',
108
+ hint: 'The upload goes to the admin gallery upload address; a refused file shows a dialog with the reason.',
109
+ });
110
+ await settle(this);
111
+ });
112
+
113
+ /**
114
+ * Assert how many images the gallery of the product form holds.
115
+ *
116
+ * Example #1: Then the product gallery should have 1 image
117
+ * Example #2: Then the product gallery should have 0 images
118
+ * Example #3: And the product gallery should have 2 images
119
+ * Example #4: Then the product gallery should have 3 images
120
+ * Example #5: Then the product gallery should have 5 images
121
+ *
122
+ */
123
+ Then(/^the product gallery should have (\d+) images?$/, async function (count) {
124
+ const gallery = this.page.locator('#media_gallery_content');
125
+ if (!(await gallery.isVisible().catch(() => false))) {
126
+ throw friendly({ message: 'The product gallery is not open.', hint: 'Open its section first: `When I open the "Images And Videos" form section`.' });
127
+ }
128
+ await assertValue(this, async () => String(await gallery.locator('.image.item:visible').count()), String(count), {
129
+ label: 'the number of images in the product gallery',
130
+ hint: 'The images are the `.image.item` tiles of `#media_gallery_content`.',
131
+ });
132
+ });
133
+
134
+ // ---------------------------------------------------------------------------
135
+ // Categories
136
+ // ---------------------------------------------------------------------------
137
+
138
+ /**
139
+ * The node of the category tree with a name. The tree prints a node as
140
+ * "Gear (ID: 3) (46)": the name is what comes before " (ID:".
141
+ *
142
+ * @param {object} world
143
+ * @param {string} name
144
+ * @returns {import('playwright').Locator}
145
+ */
146
+ function categoryNode(world, name) {
147
+ const pattern = new RegExp('^\\s*' + String(name).replace(/[.*+?^${}()|[\]\\]/g, '\\$&') + '\\s+\\(ID: \\d+\\)');
148
+ return world.page.locator('#tree-div a.jstree-anchor').filter({ hasText: pattern });
149
+ }
150
+
151
+ /**
152
+ * Make sure the category tree is on the page and every level is open.
153
+ *
154
+ * @param {object} world
155
+ */
156
+ async function openCategoryTree(world) {
157
+ const page = world.page;
158
+ if (!(await page.locator('#tree-div').count())) {
159
+ await openAdmin(world, adminRoute('categories'), 'categories');
160
+ }
161
+ await settle(world);
162
+ await page.locator('#tree-div a.jstree-anchor').first().waitFor({ state: 'visible', timeout: budget(world) });
163
+ const expand = page.locator('#expandAll');
164
+ if (await expand.count()) {
165
+ await expand.click();
166
+ await assertValue(world, async () => String(await page.locator('#tree-div li.jstree-closed').count()), '0', {
167
+ label: 'the number of closed nodes of the category tree',
168
+ hint: '"Expand All" opens every level of the tree.',
169
+ });
170
+ }
171
+ }
172
+
173
+ /**
174
+ * Select a category in the tree of the Categories page by its name; its form
175
+ * opens on the right.
176
+ *
177
+ * Example #1: When I select the "Gear" category in the tree
178
+ * Example #2: When I select the "Bags" category in the tree
179
+ * Example #3: And I select the "Default Category" category in the tree
180
+ * Example #4: When we select the "Women" category in the tree
181
+ * Example #5: When select the "Sale" category in the tree
182
+ *
183
+ */
184
+ When(/^(I |we )*select the "([^"]*)" category in the tree$/, async function (pronounCase, name) {
185
+ await openCategoryTree(this);
186
+ const node = categoryNode(this, name).first();
187
+ if (!(await node.count())) {
188
+ const all = await this.page.locator('#tree-div a.jstree-anchor').allInnerTexts();
189
+ throw friendly({ message: `The category tree has no "${name}". It holds: ${all.map((text) => clean(text).replace(/\s+\(ID:.*$/, '')).join(', ')}.`, hint: 'Use the category name without its "(ID: n)" suffix.' });
190
+ }
191
+ await actAndSettle(this, () => node.click({ noWaitAfter: true }));
192
+ await assertValue(this, () => this.page.locator('h1.page-title').first().innerText(), new RegExp('^' + name.replace(/[.*+?^${}()|[\]\\]/g, '\\$&') + ' \\(ID: \\d+\\)$'), {
193
+ label: 'the title of the category form',
194
+ hint: 'The form of the selected category shows its name and id as the page title.',
195
+ });
196
+ });
197
+
198
+ /**
199
+ * Assert a category is (or is not) in the tree of the Categories page.
200
+ *
201
+ * Example #1: Then I should see the "Gear" category in the tree
202
+ * Example #2: Then I should not see the "Test Category" category in the tree
203
+ * Example #3: And I should see the "Bags" category in the tree
204
+ * Example #4: Then we should see the "Women" category in the tree
205
+ * Example #5: Then should not see the "Old Stuff" category in the tree
206
+ *
207
+ */
208
+ Then(/^(I |we )*should( not)* see the "([^"]*)" category in the tree$/, async function (pronounCase, notCase, name) {
209
+ await openCategoryTree(this);
210
+ await assertPresence(categoryNode(this, name), notCase, {
211
+ label: `the category "${name}" in the tree`,
212
+ hint: 'The tree is `#tree-div`; a new category shows under its parent once it is saved.',
213
+ timeout: notCase ? 3000 : budget(this),
214
+ });
215
+ });
216
+
217
+ // ---------------------------------------------------------------------------
218
+ // Orders
219
+ // ---------------------------------------------------------------------------
220
+
221
+ /**
222
+ * The order number a step refers to: a literal number, or the one the last
223
+ * `I place the order` step of the scenario read from the success page.
224
+ *
225
+ * @param {object} world
226
+ * @param {string|undefined} number
227
+ * @returns {string}
228
+ */
229
+ function orderNumber(world, number) {
230
+ if (number) return number;
231
+ if (!world.lastOrderNumber) {
232
+ throw friendly({ message: 'No order was placed in this scenario, so there is no "last placed order".', hint: 'Place one first (`When I place the order`), or name the order: `the order "000000003"`.' });
233
+ }
234
+ return world.lastOrderNumber;
235
+ }
236
+
237
+ /**
238
+ * Open the view page of an order in the admin panel: the orders grid is
239
+ * searched for the order number and its "View" link is followed. "The last
240
+ * placed order" is the one the scenario placed on the storefront.
241
+ *
242
+ * Example #1: When I open the order "000000003" in the admin panel
243
+ * Example #2: When I open the last placed order in the admin panel
244
+ * Example #3: And I open the order "000000001" in the admin panel
245
+ * Example #4: When we open the last placed order in the admin panel
246
+ * Example #5: When open the order "000000002" in the admin panel
247
+ *
248
+ */
249
+ When(/^(I |we )*open (?:the order "([^"]*)"|the last placed order) in the admin panel$/, async function (pronounCase, number) {
250
+ const wanted = orderNumber(this, number);
251
+ await openAdmin(this, adminRoute('orders'), 'orders');
252
+ await clearGrid(this);
253
+ await searchGrid(this, wanted);
254
+ const g = await grid(this);
255
+ if (!(await gridRows(g, wanted).count())) {
256
+ throw friendly({ message: `The orders grid has no order "${wanted}". The search shows ${await gridSeen(g)}.`, hint: 'The order number is the one of the checkout success page.' });
257
+ }
258
+ await openGridRow(this, wanted);
259
+ await assertValue(this, () => this.page.locator('h1.page-title').first().innerText(), '#' + wanted, { label: 'the title of the order page', hint: 'The order view shows "#<number>" as its title.' });
260
+ });
261
+
262
+ /**
263
+ * Assert the last placed order is (or is not) in the orders grid of the admin
264
+ * panel: the round trip from the storefront checkout to the back office.
265
+ *
266
+ * Example #1: Then I should see the last placed order in the orders grid
267
+ * Example #2: And I should see the last placed order in the orders grid
268
+ * Example #3: Then we should see the last placed order in the orders grid
269
+ * Example #4: Then I should not see the last placed order in the orders grid
270
+ * Example #5: Then should see the last placed order in the orders grid
271
+ *
272
+ */
273
+ Then(/^(I |we )*should( not)* see the last placed order in the orders grid$/, async function (pronounCase, notCase) {
274
+ const wanted = orderNumber(this);
275
+ await openAdmin(this, adminRoute('orders'), 'orders');
276
+ await clearGrid(this);
277
+ await searchGrid(this, wanted);
278
+ const g = await grid(this);
279
+ await assertPresence(gridRows(g, wanted), notCase, {
280
+ label: `the order "${wanted}" in the orders grid`,
281
+ hint: 'The orders grid is filled when an order is placed (asynchronous grid indexing must be off on a test site).',
282
+ timeout: notCase ? 3000 : budget(this),
283
+ found: () => gridSeen(g),
284
+ });
285
+ });
286
+
287
+ /**
288
+ * Assert the status of the order on its view page ("Pending", "Processing",
289
+ * "Complete", "Closed", "Canceled", "On Hold").
290
+ *
291
+ * Example #1: Then the order status should be "Pending"
292
+ * Example #2: Then the order status should be "Processing"
293
+ * Example #3: And the order status should be "Complete"
294
+ * Example #4: Then the order status should not be "Canceled"
295
+ * Example #5: Then the order status should be "On Hold"
296
+ *
297
+ */
298
+ Then(/^the order status should( not)* be "([^"]*)"$/, async function (notCase, status) {
299
+ await settle(this);
300
+ if (!(await this.page.locator('#order_status').count())) {
301
+ throw friendly({ message: 'This is not the view page of an order.', hint: 'Open the order first: `When I open the last placed order in the admin panel`.' });
302
+ }
303
+ await assertValue(this, () => this.page.locator('#order_status').innerText(), status, { label: 'the order status', notCase, hint: 'The status is `#order_status` of the order view.' });
304
+ });
305
+
306
+ /**
307
+ * Add a comment to the order ("Notes for this Order" on the Information tab)
308
+ * and wait for it to show in the list.
309
+ *
310
+ * Example #1: When I add the order comment "Checked by the test suite"
311
+ * Example #2: And I add the order comment "Customer called"
312
+ * Example #3: When we add the order comment "Waiting for stock"
313
+ * Example #4: When I add the order comment "Packed"
314
+ * Example #5: When add the order comment "Second note"
315
+ *
316
+ */
317
+ When(/^(I |we )*add the order comment "([^"]*)"$/, async function (pronounCase, text) {
318
+ await settle(this);
319
+ const box = this.page.locator('#history_comment');
320
+ await actOrExplain('add the order comment', text, async () => {
321
+ await box.fill(text, { timeout: budget(this) });
322
+ await this.page.locator('#order_history_block button.action-save').click();
323
+ await this.page.locator('#order_history_block .note-list li').filter({ hasText: literal(text) }).first().waitFor({ state: 'visible', timeout: budget(this) });
324
+ }, 'The comment box is on the Information tab of the order view (`#history_comment`).');
325
+ await settle(this);
326
+ });
327
+
328
+ /**
329
+ * Assert a comment is (or is not) in the notes of the order.
330
+ *
331
+ * Example #1: Then I should see the order comment "Checked by the test suite"
332
+ * Example #2: Then I should not see the order comment "Something else"
333
+ * Example #3: And I should see the order comment "Customer called"
334
+ * Example #4: Then we should see the order comment "Packed"
335
+ * Example #5: Then should see the order comment "Waiting for stock"
336
+ *
337
+ */
338
+ Then(/^(I |we )*should( not)* see the order comment "([^"]*)"$/, async function (pronounCase, notCase, text) {
339
+ await assertPresence(this.page.locator('#order_history_block .note-list li').filter({ hasText: literal(text) }), notCase, {
340
+ label: `the order comment "${text}"`,
341
+ hint: 'The notes are listed under "Notes for this Order" on the Information tab.',
342
+ timeout: notCase ? 3000 : budget(this),
343
+ found: async () => `the notes "${clean(await this.page.locator('#order_history_block .note-list').innerText().catch(() => ''))}"`,
344
+ });
345
+ });
346
+
347
+ // The order operations: the button of the order view, the submit button of the
348
+ // page it opens (if any), whether it asks for a confirmation, and the message.
349
+ const ORDER_OPERATIONS = {
350
+ 'invoice': { button: '#order_invoice', submit: 'button.submit-button', message: 'The invoice has been created.' },
351
+ 'ship': { button: '#order_ship', submit: 'button.submit-button', message: 'The shipment has been created.' },
352
+ 'refund': { button: '#order_creditmemo', submit: 'button.submit-button', message: 'You created the credit memo.' },
353
+ 'hold': { button: '#order-view-hold-button', message: 'You put the order on hold.' },
354
+ 'unhold': { button: '#order-view-unhold-button', message: 'You released the order from holding status.' },
355
+ 'cancel': { button: '#order-view-cancel-button', confirm: true, message: 'You canceled the order.' },
356
+ };
357
+
358
+ /**
359
+ * Run an operation of the order view and wait for its message.
360
+ *
361
+ * @param {object} world
362
+ * @param {string} name
363
+ */
364
+ async function orderOperation(world, name) {
365
+ const page = world.page;
366
+ const operation = ORDER_OPERATIONS[name];
367
+ await settle(world);
368
+ const button = page.locator(operation.button);
369
+ if (!(await button.count())) {
370
+ const all = await page.locator('.page-main-actions:visible').first().locator('button:visible').allInnerTexts().catch(() => []);
371
+ throw friendly({
372
+ message: `The order cannot be ${name === 'ship' ? 'shipped' : name === 'hold' ? 'put on hold' : name + (name.endsWith('e') ? 'd' : 'ed')} now. Its buttons: ${all.map(clean).filter(Boolean).join(', ') || '(none; is this an order view?)'}.`,
373
+ hint: 'The buttons follow the state of the order: an invoice is needed before a credit memo, a shipped and invoiced order is complete.',
374
+ });
375
+ }
376
+ await actAndSettle(world, () => button.click({ noWaitAfter: true }));
377
+ if (operation.confirm) await answerDialog(world, true);
378
+ if (operation.submit) {
379
+ const submit = page.locator(operation.submit).first();
380
+ await submit.waitFor({ state: 'visible', timeout: budget(world) });
381
+ await settle(world);
382
+ await actAndSettle(world, () => submit.click({ noWaitAfter: true }));
383
+ }
384
+ await assertPresence(messages(world, 'success', operation.message), null, {
385
+ label: `the message "${operation.message}"`,
386
+ hint: 'The operation did not finish: read the message the page shows.',
387
+ timeout: budget(world),
388
+ found: () => messagesSeen(world),
389
+ });
390
+ }
391
+
392
+ /**
393
+ * Create the invoice, the shipment or the offline credit memo of the open
394
+ * order with the default values of its form, and wait for the success message
395
+ * ("The invoice has been created.", "The shipment has been created.", "You
396
+ * created the credit memo.").
397
+ *
398
+ * Example #1: When I invoice the order
399
+ * Example #2: When I ship the order
400
+ * Example #3: When I refund the order
401
+ * Example #4: And we invoice the order
402
+ * Example #5: When we ship the order
403
+ *
404
+ */
405
+ When(/^(I |we )*(invoice|ship|refund) the order$/, async function (pronounCase, name) {
406
+ await orderOperation(this, name);
407
+ });
408
+
409
+ /**
410
+ * Put the open order on hold, release it, or cancel it (the confirmation is
411
+ * accepted), and wait for the success message.
412
+ *
413
+ * Example #1: When I put the order on hold
414
+ * Example #2: When I release the order from hold
415
+ * Example #3: When I cancel the order
416
+ * Example #4: And we put the order on hold
417
+ * Example #5: When we cancel the order
418
+ *
419
+ */
420
+ When(/^(I |we )*(put the order on hold|release the order from hold|cancel the order)$/, async function (pronounCase, phrase) {
421
+ await orderOperation(this, phrase === 'put the order on hold' ? 'hold' : phrase === 'cancel the order' ? 'cancel' : 'unhold');
422
+ });
423
+
424
+ // ---------------------------------------------------------------------------
425
+ // Customers
426
+ // ---------------------------------------------------------------------------
427
+
428
+ /**
429
+ * Open the edit page of a customer by email: the customers grid is searched
430
+ * and the row is opened.
431
+ *
432
+ * Example #1: When I open the customer "customer@example.com" in the admin panel
433
+ * Example #2: When I open the customer "shopper@example.com" in the admin panel
434
+ * Example #3: And I open the customer "customer@example.com" in the admin panel
435
+ * Example #4: When we open the customer "roni_cost@example.com" in the admin panel
436
+ * Example #5: When open the customer "customer@example.com" in the admin panel
437
+ *
438
+ */
439
+ When(/^(I |we )*open the customer "([^"]*)" in the admin panel$/, async function (pronounCase, email) {
440
+ await openAdmin(this, adminRoute('customers'), 'customers');
441
+ await clearGrid(this);
442
+ await searchGrid(this, email);
443
+ const g = await grid(this);
444
+ if (!(await gridRows(g, email).count())) {
445
+ throw friendly({ message: `The customers grid has no customer "${email}". The search shows ${await gridSeen(g)}.`, hint: 'The customers of the suite are created by the site build script.' });
446
+ }
447
+ await openGridRow(this, email);
448
+ });
449
+
450
+ // ---------------------------------------------------------------------------
451
+ // Configuration
452
+ // ---------------------------------------------------------------------------
453
+
454
+ /**
455
+ * Open a section of Stores > Configuration by its code ("general", "web",
456
+ * "catalog", "customer", "sales", "checkout", "contact").
457
+ *
458
+ * Example #1: When I go to the "general" configuration section
459
+ * Example #2: When I go to the "contact" configuration section
460
+ * Example #3: And I go to the "catalog" configuration section
461
+ * Example #4: When we go to the "checkout" configuration section
462
+ * Example #5: Given I am on the "general" configuration section
463
+ *
464
+ */
465
+ Given(/^(?:(?:I am |we are )+on|(?:I |we )*go to) the "([a-z_]+)" configuration section$/, async function (section) {
466
+ await openAdmin(this, 'admin/system_config/edit/section/' + section, `the "${section}" configuration section`);
467
+ if (!(await this.page.locator('#config-edit-form, .access-denied-page').count())) {
468
+ throw friendly({ message: `"${section}" is not a configuration section.`, hint: 'Use the code of the section, the last part of its address: general, web, catalog, customer, sales, checkout, contact, …' });
469
+ }
470
+ });
471
+
472
+ /**
473
+ * The group of the open configuration section with a title.
474
+ *
475
+ * @param {object} world
476
+ * @param {string} title
477
+ * @returns {Promise<import('playwright').Locator>}
478
+ */
479
+ async function configGroup(world, title) {
480
+ const page = world.page;
481
+ const group = page.locator('#config-edit-form .section-config').filter({ has: page.locator(':scope > .entry-edit-head > a', { hasText: exactly(title) }) }).first();
482
+ if (!(await group.count())) {
483
+ const all = await page.locator('#config-edit-form .section-config > .entry-edit-head > a').allInnerTexts().catch(() => []);
484
+ throw friendly({ message: `This configuration section has no "${title}" group. Its groups: ${all.map(clean).join(', ') || '(none; is a configuration section open?)'}.`, hint: 'Open the section first: `When I go to the "general" configuration section`.' });
485
+ }
486
+ const head = group.locator(':scope > .entry-edit-head > a');
487
+ if (!/(^|\s)open(\s|$)/.test((await head.getAttribute('class')) || '')) {
488
+ await head.click();
489
+ await group.locator('tr').first().waitFor({ state: 'visible', timeout: budget(world) });
490
+ }
491
+ return group;
492
+ }
493
+
494
+ /**
495
+ * The control of a configuration field, by group title and field label.
496
+ *
497
+ * @param {object} world
498
+ * @param {string} groupTitle
499
+ * @param {string} label
500
+ * @returns {Promise<import('playwright').Locator>}
501
+ */
502
+ async function configControl(world, groupTitle, label) {
503
+ const group = await configGroup(world, groupTitle);
504
+ const row = group.locator('tr').filter({ has: world.page.locator(':scope > td.label', { hasText: exactly(label) }) }).first();
505
+ if (!(await row.count())) {
506
+ const all = await group.locator('tr > td.label').allInnerTexts().catch(() => []);
507
+ throw friendly({ message: `The "${groupTitle}" group has no "${label}" field. Its fields: ${all.map(clean).filter(Boolean).join(', ')}.`, hint: 'Use the label as the configuration page shows it.' });
508
+ }
509
+ return row.locator('td.value').locator('input:not([type="hidden"]), select, textarea').first();
510
+ }
511
+
512
+ /**
513
+ * Set a field of the open configuration section, in a group, by its label: a
514
+ * text, or the option text of a select. The group is expanded when it is
515
+ * closed. Follow it with `I save the form`.
516
+ *
517
+ * Example #1: When I set the "Store Name" configuration field of "Store Information" to "Test Store"
518
+ * Example #2: When I set the "Store Phone Number" configuration field of "Store Information" to "555-0100"
519
+ * Example #3: And I set the "Store Name" configuration field of "Store Information" to ""
520
+ * Example #4: When we set the "Enable Contact Us" configuration field of "Contact Us" to "Yes"
521
+ * Example #5: When I set the "Store Hours of Operation" configuration field of "Store Information" to "9 to 5"
522
+ *
523
+ */
524
+ When(/^(I |we )*set the "([^"]*)" configuration field of "([^"]*)" to "([^"]*)"$/, async function (pronounCase, label, groupTitle, value) {
525
+ const control = await configControl(this, groupTitle, label);
526
+ if (await control.isDisabled()) {
527
+ throw friendly({ message: `The "${label}" configuration field is disabled.`, hint: 'It inherits its value ("Use system value" is ticked) or is locked in the environment configuration.' });
528
+ }
529
+ if ((await control.evaluate((el) => el.tagName)) === 'SELECT') await control.selectOption({ label: value });
530
+ else await control.fill(value);
531
+ });
532
+
533
+ /**
534
+ * Assert the value of a field of the open configuration section.
535
+ *
536
+ * Example #1: Then the "Store Name" configuration field of "Store Information" should be "Test Store"
537
+ * Example #2: Then the "Store Name" configuration field of "Store Information" should be ""
538
+ * Example #3: And the "Store Phone Number" configuration field of "Store Information" should be "555-0100"
539
+ * Example #4: Then the "Enable Contact Us" configuration field of "Contact Us" should be "Yes"
540
+ * Example #5: Then the "Store Name" configuration field of "Store Information" should not be "Test Store"
541
+ *
542
+ */
543
+ Then(/^the "([^"]*)" configuration field of "([^"]*)" should( not)* be "([^"]*)"$/, async function (label, groupTitle, notCase, value) {
544
+ const control = await configControl(this, groupTitle, label);
545
+ await assertValue(this, () => control.evaluate((el) => (el.tagName === 'SELECT' ? [...el.selectedOptions].map((option) => option.textContent.replace(/\s+/g, ' ').trim()).join(', ') : el.value)), value, {
546
+ label: `the "${label}" configuration field`,
547
+ notCase,
548
+ hint: 'A select reads the text of its selected option.',
549
+ });
550
+ });
551
+
552
+ // ---------------------------------------------------------------------------
553
+ // Cache and index
554
+ // ---------------------------------------------------------------------------
555
+
556
+ /**
557
+ * Read the rows of a status grid as [name, status].
558
+ *
559
+ * @param {object} world
560
+ * @param {string} page
561
+ * @param {string} nameColumn
562
+ * @returns {Promise<Array<{name: string, status: string}>>}
563
+ */
564
+ async function statusRows(world, page, nameColumn) {
565
+ await openAdmin(world, adminRoute(page), page);
566
+ const g = await grid(world);
567
+ const columns = (await g.table.locator('thead tr').first().locator('th').allInnerTexts()).map(clean);
568
+ const nameIndex = columns.indexOf(nameColumn);
569
+ const statusIndex = columns.indexOf('Status');
570
+ return g.rows.evaluateAll((rows, [n, s]) => rows.map((row) => ({
571
+ name: (row.children[n].innerText || '').replace(/\s+/g, ' ').trim(),
572
+ status: (row.children[s].innerText || '').replace(/\s+/g, ' ').trim(),
573
+ })), [nameIndex, statusIndex]);
574
+ }
575
+
576
+ /**
577
+ * Assert, on Cache Management, that no cache type is invalidated, or that some
578
+ * are (after a configuration change, before the cache is flushed).
579
+ *
580
+ * Example #1: Then no cache type should be invalidated
581
+ * Example #2: Then some cache types should be invalidated
582
+ * Example #3: And no cache type should be invalidated
583
+ * Example #4: And some cache types should be invalidated
584
+ * Example #5: Then no cache types should be invalidated
585
+ *
586
+ */
587
+ Then(/^(no|some) cache types? should be invalidated$/, async function (quantity) {
588
+ const rows = await statusRows(this, 'cache management', 'Cache Type');
589
+ const invalid = rows.filter((row) => /INVALIDATED/i.test(row.status)).map((row) => row.name);
590
+ if (quantity === 'no' && invalid.length) {
591
+ throw friendly({ message: `Expected no invalidated cache type, but these are: ${invalid.join(', ')}.`, hint: 'Flush the cache: `When I flush the cache`.' });
592
+ }
593
+ if (quantity === 'some' && !invalid.length) {
594
+ throw friendly({ message: 'Expected some invalidated cache types, but every cache type is valid.', hint: 'A saved configuration change invalidates "Configuration" and "Page Cache".' });
595
+ }
596
+ });
597
+
598
+ /**
599
+ * Flush the cache on Cache Management ("Flush Magento Cache") and wait for the
600
+ * success message. It is how a suite deals with invalidated cache types.
601
+ *
602
+ * Example #1: When I flush the cache
603
+ * Example #2: And I flush the cache
604
+ * Example #3: When we flush the cache
605
+ * Example #4: When flush the cache
606
+ * Example #5: And we flush the cache
607
+ *
608
+ */
609
+ When(/^(I |we )*flush the cache$/, async function (pronounCase) {
610
+ await openAdmin(this, adminRoute('cache management'), 'cache management');
611
+ await actAndSettle(this, () => this.page.locator('#flush_magento').click({ noWaitAfter: true }));
612
+ await assertPresence(messages(this, 'success', 'cache storage has been flushed'), null, {
613
+ label: 'the message that the cache was flushed',
614
+ hint: 'The button is "Flush Magento Cache" (`#flush_magento`).',
615
+ timeout: budget(this),
616
+ found: () => messagesSeen(this),
617
+ });
618
+ });
619
+
620
+ /**
621
+ * Assert, on Index Management, that every index is ready ("READY"), none asks
622
+ * for a reindex.
623
+ *
624
+ * Example #1: Then every index should be ready
625
+ * Example #2: And every index should be ready
626
+ * Example #3: Then every search index should be ready
627
+ * Example #4: And every search index should be ready
628
+ * Example #5: Then every index should be ready now
629
+ *
630
+ */
631
+ Then(/^every (?:search )?index should be ready(?: now)?$/, async function () {
632
+ const rows = await statusRows(this, 'index management', 'Indexer');
633
+ const invalid = rows.filter((row) => !/^READY$/i.test(row.status)).map((row) => `${row.name} (${row.status})`);
634
+ if (invalid.length || !rows.length) {
635
+ throw friendly({
636
+ message: rows.length ? `Expected every index to be ready, but these are not: ${invalid.join(', ')}.` : 'The Index Management grid is empty.',
637
+ hint: 'The admin panel has no reindex button: use `When I rebuild the invalid indexes` (it runs the reindex command of cucumber.js). Deleting or moving a category invalidates "Category Products" and "Catalog Search".',
638
+ });
639
+ }
640
+ });
641
+
642
+ /**
643
+ * Rebuild the invalid indexes. The admin panel can only read the state of the
644
+ * indexes and change their mode: it has no "reindex" button, and deleting or
645
+ * moving a category leaves "Category Products" and "Catalog Search" on
646
+ * "REINDEX REQUIRED" even with the indexers on "Update on Save". A suite deals
647
+ * with it through the command line: the step runs `reindexCommand` of
648
+ * cucumber.js (`worldParameters`) in `siteDir` and then expects every index to
649
+ * be ready on Index Management.
650
+ *
651
+ * Example #1: When I rebuild the invalid indexes
652
+ * Example #2: And I rebuild the invalid indexes
653
+ * Example #3: When we rebuild the invalid indexes
654
+ * Example #4: Given I rebuild the invalid indexes
655
+ * Example #5: And we rebuild the invalid indexes
656
+ *
657
+ */
658
+ When(/^(I |we )*rebuild the invalid indexes$/, async function (pronounCase) {
659
+ const command = (this.parameters && this.parameters.reindexCommand) || '';
660
+ const cwd = path.resolve(process.cwd(), (this.parameters && this.parameters.siteDir) || '.');
661
+ if (!command) {
662
+ throw friendly({ message: 'No reindex command is configured.', hint: "Set worldParameters.reindexCommand in cucumber.js (for a DDEV site: 'ddev exec php bin/magento indexer:reindex') and worldParameters.siteDir (the project folder)." });
663
+ }
664
+ if (!fs.existsSync(cwd)) {
665
+ throw friendly({ message: `The site folder "${cwd}" does not exist.`, hint: 'Set SITE_DIR, or worldParameters.siteDir in cucumber.js, to the folder the reindex command runs in.' });
666
+ }
667
+ const result = await new Promise((resolve) => {
668
+ // stdin is closed: `ddev exec` waits for ever on an open pipe.
669
+ const child = spawn(command, { cwd, shell: true, stdio: ['ignore', 'pipe', 'pipe'] });
670
+ let output = '';
671
+ child.stdout.on('data', (chunk) => { output += chunk; });
672
+ child.stderr.on('data', (chunk) => { output += chunk; });
673
+ const timer = setTimeout(() => child.kill('SIGKILL'), 40000);
674
+ child.on('close', (code) => { clearTimeout(timer); resolve({ code, output }); });
675
+ child.on('error', (error) => { clearTimeout(timer); resolve({ code: -1, output: String(error) }); });
676
+ });
677
+ if (result.code !== 0) {
678
+ throw friendly({ message: `The reindex command "${command}" failed (exit ${result.code}) in ${cwd}: ${clean(result.output).slice(-300)}`, hint: 'Run the command by hand in the site folder.' });
679
+ }
680
+ const rows = await statusRows(this, 'index management', 'Indexer');
681
+ const invalid = rows.filter((row) => !/^READY$/i.test(row.status)).map((row) => `${row.name} (${row.status})`);
682
+ if (invalid.length) {
683
+ throw friendly({ message: `After the reindex these indexes are still not ready: ${invalid.join(', ')}.`, hint: 'Read the output of the reindex command.' });
684
+ }
685
+ });
686
+
687
+ // ---------------------------------------------------------------------------
688
+ // Clean-up
689
+ // ---------------------------------------------------------------------------
690
+
691
+ // How each kind of record is found and deleted in the admin panel.
692
+ const RECORDS = {
693
+ 'product': { page: 'products', find: 'search', remove: 'mass', action: 'Delete' },
694
+ 'customer': { page: 'customers', find: 'search', remove: 'mass', action: 'Delete' },
695
+ 'page': { page: 'pages', find: 'search', remove: 'row' },
696
+ 'block': { page: 'blocks', find: 'search', remove: 'row' },
697
+ 'cart price rule': { page: 'cart price rules', find: 'Rule', remove: 'form' },
698
+ 'review': { page: 'reviews', find: 'Title', remove: 'mass', action: 'Delete' },
699
+ 'newsletter subscriber': { page: 'newsletter subscribers', find: 'Email', remove: 'mass', action: 'Delete' },
700
+ };
701
+
702
+ /**
703
+ * Delete every record of a kind that matches a text, through the admin
704
+ * panel, when there is one.
705
+ *
706
+ * @param {object} world
707
+ * @param {string} kind
708
+ * @param {string} text
709
+ * @returns {Promise<number>} how many passes deleted something
710
+ */
711
+ async function removeRecords(world, kind, text) {
712
+ const record = RECORDS[kind];
713
+ const page = world.page;
714
+ let removed = 0;
715
+ for (let pass = 0; pass < 5; pass += 1) {
716
+ await openAdmin(world, adminRoute(record.page), record.page);
717
+ await clearGrid(world);
718
+ if (record.find === 'search') await searchGrid(world, text);
719
+ else await filterGrid(world, record.find, text);
720
+ const g = await grid(world);
721
+ const rows = gridRows(g, text);
722
+ if (!(await rows.count())) break;
723
+ if (record.remove === 'mass') {
724
+ await selectGridRows(world, text);
725
+ await runGridAction(world, record.action);
726
+ await answerDialog(world, true);
727
+ } else if (record.remove === 'row') {
728
+ const row = rows.first();
729
+ await row.locator('button.action-select').click();
730
+ await row.locator('a[data-action="item-delete"]').click();
731
+ await answerDialog(world, true);
732
+ } else {
733
+ await openGridRow(world, text);
734
+ await actAndSettle(world, () => page.locator('.page-main-actions:visible').first().locator('#delete').click({ noWaitAfter: true }));
735
+ await answerDialog(world, true);
736
+ }
737
+ await messages(world, 'success').first().waitFor({ state: 'visible', timeout: budget(world) }).catch(async () => {
738
+ throw friendly({ message: `Deleting the ${kind} "${text}" did not end with a success message. The page shows ${await messagesSeen(world)}.`, hint: 'A record in use cannot always be deleted: read the message.' });
739
+ });
740
+ removed += 1;
741
+ }
742
+ await openAdmin(world, adminRoute(record.page), record.page);
743
+ await clearGrid(world);
744
+ return removed;
745
+ }
746
+
747
+ /**
748
+ * Make sure no record of a kind matches a text: a product (by SKU or name), a
749
+ * customer (by email), a page or a block (by title), a cart price rule (by
750
+ * name), a review (by its summary) or a newsletter subscriber (by email). What
751
+ * is found is deleted through the admin panel. It is the clean-up of what a
752
+ * scenario creates: use it before the scenario (a failed run may have left the
753
+ * record behind) and at its end. Needs a logged-in admin user.
754
+ *
755
+ * Example #1: Given there is no product "TEST-SKU-1"
756
+ * Example #2: Given there is no customer "new.customer@example.com"
757
+ * Example #3: And there is no page "Test Page"
758
+ * Example #4: Given there is no cart price rule "Test Rule"
759
+ * Example #5: And there is no review "Test review summary"
760
+ *
761
+ */
762
+ Given(/^there is no (product|customer|page|block|cart price rule|review|newsletter subscriber) "([^"]*)"$/, async function (kind, text) {
763
+ if (!clean(text)) {
764
+ throw friendly({ message: `An empty text would match every ${kind}.`, hint: 'Name the record to delete.' });
765
+ }
766
+ await removeRecords(this, kind, text);
767
+ });
768
+
769
+ /**
770
+ * Make sure no category has a name: when the tree holds it, it is selected and
771
+ * deleted (with its sub-categories). The clean-up of a category a scenario
772
+ * creates. Needs a logged-in admin user.
773
+ *
774
+ * Example #1: Given there is no category "Test Category"
775
+ * Example #2: And there is no category "Test Category"
776
+ * Example #3: Given there is no category "Round Trip"
777
+ * Example #4: And there is no category "Old Stuff"
778
+ * Example #5: Given there is no category "Temporary"
779
+ *
780
+ */
781
+ Given(/^there is no category "([^"]*)"$/, async function (name) {
782
+ for (let pass = 0; pass < 5; pass += 1) {
783
+ await openAdmin(this, adminRoute('categories'), 'categories');
784
+ await openCategoryTree(this);
785
+ const node = categoryNode(this, name).first();
786
+ if (!(await node.count())) return;
787
+ await actAndSettle(this, () => node.click({ noWaitAfter: true }));
788
+ await actAndSettle(this, () => this.page.locator('.page-main-actions:visible').first().locator('#delete').click({ noWaitAfter: true }));
789
+ await answerDialog(this, true);
790
+ await assertPresence(messages(this, 'success', 'You deleted the category.'), null, {
791
+ label: 'the message "You deleted the category."',
792
+ hint: 'A root category in use by a store cannot be deleted.',
793
+ timeout: budget(this),
794
+ found: () => messagesSeen(this),
795
+ });
796
+ }
797
+ });
798
+
799
+ /**
800
+ * Assert the open confirmation dialog is gone and the page is the admin page it
801
+ * was opened from. Kept with the clean-up steps: a dismissed delete leaves the
802
+ * record in place.
803
+ *
804
+ * Example #1: Then the confirmation should be closed
805
+ * Example #2: And the confirmation should be closed
806
+ * Example #3: Then the confirmation dialog should be closed
807
+ * Example #4: And the confirmation dialog should be closed
808
+ * Example #5: Then the confirmation should be closed now
809
+ *
810
+ */
811
+ Then(/^the confirmation(?: dialog)? should be closed(?: now)?$/, async function () {
812
+ await requireAdminSession(this, 'the page');
813
+ await assertPresence(dialog(this), 'not', {
814
+ label: 'a confirmation dialog',
815
+ hint: 'Press Cancel or OK in the dialog first.',
816
+ timeout: budget(this),
817
+ });
818
+ });