@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,1797 @@
1
+ 'use strict';
2
+
3
+ // Storefront step definitions (the default theme): the customer session, the
4
+ // top menu and the breadcrumbs, the product list of a category or a search
5
+ // (amount, sorting, direction, list and grid, paging, layered navigation), the
6
+ // search box and its suggestions, the product page (options, quantity, add to
7
+ // cart), the mini cart, the cart (quantity, remove, coupon, shipping estimate,
8
+ // totals), the checkout through to the order number, the customer account
9
+ // (orders, address book), the wish list, the comparison list, reviews, the
10
+ // newsletter and the field errors.
11
+ //
12
+ // The storefront renders late: a page is "complete" long before its components
13
+ // work. Every step waits for the settled signal (see settle() in
14
+ // magento-helpers.js), never for a fixed time.
15
+ //
16
+ // The selectors come from the pages as a browser shows them; see
17
+ // exploration/10 and 11 in the repository.
18
+
19
+ const { Given, When, Then } = require('@cucumber/cucumber');
20
+ const { friendly } = require('webship-js/tests/step-definitions/webship');
21
+ const {
22
+ budget,
23
+ clean,
24
+ literal,
25
+ exactly,
26
+ escapeRegExp,
27
+ siteRoot,
28
+ siteUrl,
29
+ settle,
30
+ open,
31
+ actAndSettle,
32
+ actOrExplain,
33
+ assertPresence,
34
+ assertValue,
35
+ resolveUser,
36
+ messages,
37
+ messagesSeen,
38
+ answerDialog,
39
+ } = require('./magento-helpers');
40
+
41
+ const LIST_HINT = 'The product list is on a category page or on a search result page (`.products.wrapper`).';
42
+ const CART_HINT = 'Open the cart first: `When I go to the cart`.';
43
+ const CHECKOUT_HINT = 'Open the checkout first (`When I go to the checkout`); it needs a product in the cart.';
44
+
45
+ // ---------------------------------------------------------------------------
46
+ // Customer session
47
+ // ---------------------------------------------------------------------------
48
+
49
+ /**
50
+ * Whether a customer is signed in: the header holds the customer menu.
51
+ *
52
+ * @param {object} world
53
+ * @returns {Promise<boolean>}
54
+ */
55
+ async function customerSignedIn(world) {
56
+ return (await world.page.locator('.page-header .customer-welcome').count()) > 0;
57
+ }
58
+
59
+ /**
60
+ * Submit the sign-in form of the storefront. The page holds two forms with the
61
+ * same ids (the hidden sign-in popup comes first) and the "Password" label of
62
+ * the page form points at the popup's field: the form is scoped to
63
+ * `.login-container` and its fields are found by name.
64
+ *
65
+ * @param {object} world
66
+ * @param {string} email
67
+ * @param {string} password
68
+ */
69
+ async function submitCustomerLogin(world, email, password) {
70
+ const page = world.page;
71
+ await open(world, siteUrl(world, 'customer/account/login/'));
72
+ if (await customerSignedIn(world)) {
73
+ await open(world, siteUrl(world, 'customer/account/logout/'));
74
+ await open(world, siteUrl(world, 'customer/account/login/'));
75
+ }
76
+ const form = page.locator('.login-container');
77
+ await actOrExplain('fill in the sign-in form', email, async () => {
78
+ await form.locator('input[name="login[username]"]').fill(email, { timeout: budget(world) });
79
+ await form.locator('input[name="login[password]"]').fill(password);
80
+ }, 'The sign-in form is `.login-container` on /customer/account/login/.');
81
+ await actAndSettle(world, () => form.locator('button.login').click({ noWaitAfter: true }));
82
+ // The sign-in ends in one of two ways: the customer menu of the header, or a message.
83
+ await page.locator('.page-header .customer-welcome, .page.messages .message').first().waitFor({ state: 'visible', timeout: budget(world) }).catch(() => {});
84
+ }
85
+
86
+ /**
87
+ * Log in to the store as a customer of the users registry in cucumber.js
88
+ * (`worldParameters.users`, an entry with an `email`), by its handle. A session
89
+ * of another customer is ended first.
90
+ *
91
+ * Example #1: Given I am logged in as the customer "customer"
92
+ * Example #2: Given I am logged in as the customer "shopper"
93
+ * Example #3: When I log in as the customer "customer"
94
+ * Example #4: Given we are logged in as the customer "customer"
95
+ * Example #5: When we log in as the customer "shopper"
96
+ *
97
+ */
98
+ Given(/^(?:(?:I am |we are )+logged in|(?:I |we )*log in) as the customer "([^"]*)"$/, async function (handle) {
99
+ const account = resolveUser(this, handle, 'customer');
100
+ await submitCustomerLogin(this, account.login, account.password);
101
+ if (!(await customerSignedIn(this))) {
102
+ throw friendly({
103
+ message: `Could not log in to the store as the customer "${handle}" (${account.login}). The page shows ${await messagesSeen(this)}.`,
104
+ hint: 'The customers are named in worldParameters.users of cucumber.js and created by the site build script. The customer CAPTCHA must be off on a test site.',
105
+ });
106
+ }
107
+ });
108
+
109
+ /**
110
+ * Submit the sign-in form of the store with an email and a password, for the
111
+ * scenarios that check a refused sign-in. Nothing is asserted.
112
+ *
113
+ * Example #1: When I log in to the store with the email "customer@example.com" and the password "wrong"
114
+ * Example #2: When I log in to the store with the email "nobody@example.com" and the password "Secret123456789!"
115
+ * Example #3: And I log in to the store with the email "customer@example.com" and the password ""
116
+ * Example #4: When we log in to the store with the email "shopper@example.com" and the password "wrong"
117
+ * Example #5: When log in to the store with the email "customer@example.com" and the password "wrong-password"
118
+ *
119
+ */
120
+ When(/^(I |we )*log in to the store with the email "([^"]*)" and the password "([^"]*)"$/, async function (pronounCase, email, password) {
121
+ await submitCustomerLogin(this, email, password);
122
+ });
123
+
124
+ /**
125
+ * Log out of the store through the customer menu of the header. The store
126
+ * shows "You are signed out" and goes to the home page by itself five seconds
127
+ * later: the step waits for that redirect, so the next step is not interrupted
128
+ * by it.
129
+ *
130
+ * Example #1: When I log out of the store
131
+ * Example #2: And I log out of the store
132
+ * Example #3: When we log out of the store
133
+ * Example #4: When log out of the store
134
+ * Example #5: And we log out of the store
135
+ *
136
+ */
137
+ When(/^(I |we )*log out of the store$/, async function (pronounCase) {
138
+ const page = this.page;
139
+ await settle(this);
140
+ if (!(await customerSignedIn(this))) {
141
+ throw friendly({ message: 'No customer is logged in to the store, so there is nothing to log out of.', hint: 'Log in first: `Given I am logged in as the customer "customer"`.' });
142
+ }
143
+ await actOrExplain('log out of', 'the store', async () => {
144
+ await page.locator('.page-header button[data-action="customer-menu-toggle"]').first().click();
145
+ await page.locator('.page-header .customer-menu .authorization-link a').first().click();
146
+ await page.waitForURL(/customer\/account\/logoutSuccess/, { timeout: budget(this) });
147
+ await page.waitForURL((url) => url.toString().replace(/\/+$/, '') === siteRoot(this), { timeout: budget(this) });
148
+ }, 'The customer menu of the header (`.customer-welcome`) holds "Sign Out"; the store then redirects to the home page after five seconds.');
149
+ await settle(this);
150
+ });
151
+
152
+ /**
153
+ * Assert a customer is (or is not) logged in to the store, optionally by the
154
+ * name the header greets ("Welcome, Casey Customer!").
155
+ *
156
+ * Example #1: Then I should be logged in to the store
157
+ * Example #2: Then I should not be logged in to the store
158
+ * Example #3: Then I should be logged in to the store as "Casey Customer"
159
+ * Example #4: Then we should be logged in to the store as "Sam Shopper"
160
+ * Example #5: And I should not be logged in to the store
161
+ *
162
+ */
163
+ Then(/^(I |we )*should( not)* be logged in to the store(?: as "([^"]*)")?$/, async function (pronounCase, notCase, name) {
164
+ await settle(this);
165
+ if (name) {
166
+ await assertValue(this, () => this.page.locator('.page-header .greet.welcome').first().innerText(), `Welcome, ${name}!`, {
167
+ label: 'the greeting of the header',
168
+ notCase,
169
+ hint: 'The greeting is filled from the customer data the page loads after it is shown.',
170
+ });
171
+ return;
172
+ }
173
+ const signedIn = await customerSignedIn(this);
174
+ if (signedIn === Boolean(notCase)) {
175
+ throw friendly({
176
+ message: notCase ? 'Expected no customer to be logged in to the store, but the header holds the customer menu.' : 'Expected a customer to be logged in to the store, but the header holds no customer menu.',
177
+ hint: 'A logged-in customer has the customer menu (`.customer-welcome`) in the header; a guest has "Sign In" and "Create an Account".',
178
+ });
179
+ }
180
+ });
181
+
182
+ // ---------------------------------------------------------------------------
183
+ // Menu, breadcrumbs
184
+ // ---------------------------------------------------------------------------
185
+
186
+ /**
187
+ * Open an entry of the top menu of the store. A sub-entry is written as a path
188
+ * ("Gear > Bags"): the parent is hovered, the panel opens, the entry is
189
+ * clicked.
190
+ *
191
+ * Example #1: When I open the "Gear > Bags" store menu item
192
+ * Example #2: When I open the "Sale" store menu item
193
+ * Example #3: And I open the "Women > Tops" store menu item
194
+ * Example #4: When we open the "Gear > Watches" store menu item
195
+ * Example #5: When I open the "What's New" store menu item
196
+ *
197
+ */
198
+ When(/^(I |we )*open the "([^"]*)" store menu item$/, async function (pronounCase, path) {
199
+ await settle(this);
200
+ const parts = path.split('>').map(clean);
201
+ let scope = this.page.locator('nav.navigation > ul');
202
+ await actOrExplain('open the store menu item', path, async () => {
203
+ for (let i = 0; i < parts.length; i += 1) {
204
+ const item = scope.locator(':scope > li').filter({ has: this.page.locator(':scope > a', { hasText: exactly(parts[i]) }) }).first();
205
+ const link = item.locator(':scope > a');
206
+ await link.waitFor({ state: 'visible', timeout: budget(this) });
207
+ if (i === parts.length - 1) {
208
+ await actAndSettle(this, () => link.click({ noWaitAfter: true }));
209
+ } else {
210
+ await link.hover();
211
+ scope = item.locator(':scope > ul.submenu');
212
+ await scope.waitFor({ state: 'visible', timeout: budget(this) });
213
+ }
214
+ }
215
+ }, 'Write the path as the menu shows it: "Gear > Bags". On a narrow viewport the menu is behind the menu button.');
216
+ });
217
+
218
+ /**
219
+ * Assert the breadcrumbs of the page, written as a path ("Home > Gear >
220
+ * Bags").
221
+ *
222
+ * Example #1: Then the breadcrumbs should be "Home > Gear > Bags"
223
+ * Example #2: Then the breadcrumbs should be "Home > Joust Duffle Bag"
224
+ * Example #3: And the breadcrumbs should be "Home > Gear"
225
+ * Example #4: Then the breadcrumbs should be "Home > Search results for: 'yoga'"
226
+ * Example #5: Then the breadcrumbs should be "Home > About us"
227
+ *
228
+ */
229
+ Then(/^the breadcrumbs should be "([^"]*)"$/, async function (path) {
230
+ const wanted = path.split('>').map(clean).join(' > ');
231
+ await assertValue(this, async () => (await this.page.locator('.breadcrumbs .items > li').allInnerTexts()).map(clean).join(' > '), wanted, {
232
+ label: 'the breadcrumbs',
233
+ hint: 'The breadcrumbs are `.breadcrumbs .items > li`; on a product page they are filled by a script after the page is shown.',
234
+ });
235
+ });
236
+
237
+ // ---------------------------------------------------------------------------
238
+ // Product list (category and search results)
239
+ // ---------------------------------------------------------------------------
240
+
241
+ /**
242
+ * The first toolbar of the product list (the page has one above and one below
243
+ * the list).
244
+ *
245
+ * @param {object} world
246
+ * @returns {Promise<import('playwright').Locator>}
247
+ */
248
+ async function listToolbar(world) {
249
+ await settle(world);
250
+ const toolbar = world.page.locator('.toolbar-products:visible').first();
251
+ if (!(await toolbar.count())) {
252
+ throw friendly({ message: 'There is no product list on this page.', hint: LIST_HINT });
253
+ }
254
+ return toolbar;
255
+ }
256
+
257
+ /**
258
+ * Assert how many products the list found, over all its pages (the "Items 1-12
259
+ * of 15" or "6 Items" of the toolbar).
260
+ *
261
+ * Example #1: Then the product list should have 15 products
262
+ * Example #2: Then the product list should have 6 products
263
+ * Example #3: And the product list should have 1 product
264
+ * Example #4: Then the product list should have 30 products
265
+ * Example #5: Then the product list should have 9 products
266
+ *
267
+ */
268
+ Then(/^the product list should have (\d+) products?$/, async function (count) {
269
+ const toolbar = await listToolbar(this);
270
+ await assertValue(this, async () => {
271
+ const text = clean(await toolbar.locator('.toolbar-amount').innerText());
272
+ const match = text.match(/of (\d+)$/) || text.match(/^(\d+) Items?$/i);
273
+ return match ? match[1] : `the amount "${text}"`;
274
+ }, String(count), { label: 'the number of products of the list', hint: LIST_HINT });
275
+ });
276
+
277
+ /**
278
+ * Assert a product is (or is not) on the current page of the product list, by
279
+ * its name.
280
+ *
281
+ * Example #1: Then I should see the product "Joust Duffle Bag" in the product list
282
+ * Example #2: Then I should not see the product "Test Bag" in the product list
283
+ * Example #3: And I should see the product "Push It Messenger Bag" in the product list
284
+ * Example #4: Then we should see the product "Cronus Yoga Pant" in the product list
285
+ * Example #5: Then should not see the product "Hidden Product" in the product list
286
+ *
287
+ */
288
+ Then(/^(I |we )*should( not)* see the product "([^"]*)" in the product list$/, async function (pronounCase, notCase, name) {
289
+ await settle(this);
290
+ await assertPresence(this.page.locator('.products.wrapper .product-item-link').filter({ hasText: exactly(name) }), notCase, {
291
+ label: `the product "${name}" in the product list`,
292
+ hint: LIST_HINT + ' The list shows one page at a time.',
293
+ timeout: notCase ? 3000 : budget(this),
294
+ found: async () => {
295
+ const names = await this.page.locator('.products.wrapper .product-item-link').allInnerTexts().catch(() => []);
296
+ return names.length ? `the products ${names.slice(0, 8).map((text) => `"${clean(text)}"`).join(', ')}${names.length > 8 ? ', …' : ''}` : 'no product';
297
+ },
298
+ });
299
+ });
300
+
301
+ /**
302
+ * Open a product from the product list by its name.
303
+ *
304
+ * Example #1: When I open the product "Joust Duffle Bag" from the product list
305
+ * Example #2: When I open the product "Radiant Tee" from the product list
306
+ * Example #3: And I open the product "Aim Analog Watch" from the product list
307
+ * Example #4: When we open the product "Push It Messenger Bag" from the product list
308
+ * Example #5: When open the product "Cronus Yoga Pant" from the product list
309
+ *
310
+ */
311
+ When(/^(I |we )*open the product "([^"]*)" from the product list$/, async function (pronounCase, name) {
312
+ await settle(this);
313
+ const link = this.page.locator('.products.wrapper .product-item-link').filter({ hasText: exactly(name) }).first();
314
+ await actOrExplain('open the product', name, async () => {
315
+ await link.waitFor({ state: 'visible', timeout: budget(this) });
316
+ await actAndSettle(this, () => link.click({ noWaitAfter: true }));
317
+ }, LIST_HINT + ' The product must be on the current page of the list.');
318
+ });
319
+
320
+ /**
321
+ * Sort the product list by one of the choices of its "Sort By" select
322
+ * ("Position", "Product Name", "Price"). The page reloads with the new order.
323
+ *
324
+ * Example #1: When I sort the product list by "Price"
325
+ * Example #2: When I sort the product list by "Product Name"
326
+ * Example #3: And I sort the product list by "Position"
327
+ * Example #4: When we sort the product list by "Price"
328
+ * Example #5: When sort the product list by "Product Name"
329
+ *
330
+ */
331
+ When(/^(I |we )*sort the product list by "([^"]*)"$/, async function (pronounCase, choice) {
332
+ const toolbar = await listToolbar(this);
333
+ const select = toolbar.locator('select[data-role="sorter"]');
334
+ const current = clean(await select.evaluate((el) => el.selectedOptions[0].textContent));
335
+ if (current.toLowerCase() === clean(choice).toLowerCase()) return;
336
+ await actOrExplain('sort the product list by', choice, async () => {
337
+ const before = this.page.url();
338
+ await select.selectOption({ label: choice }, { timeout: budget(this) });
339
+ await this.page.waitForURL((url) => url.toString() !== before, { timeout: budget(this) });
340
+ }, 'The choices of "Sort By" are the sortable attributes of the catalog: Position, Product Name, Price.');
341
+ await settle(this);
342
+ });
343
+
344
+ /**
345
+ * Set the direction of the product list order.
346
+ *
347
+ * Example #1: When I set the product list direction to descending
348
+ * Example #2: When I set the product list direction to ascending
349
+ * Example #3: And I set the product list direction to descending
350
+ * Example #4: When we set the product list direction to ascending
351
+ * Example #5: When set the product list direction to descending
352
+ *
353
+ */
354
+ When(/^(I |we )*set the product list direction to (ascending|descending)$/, async function (pronounCase, direction) {
355
+ const toolbar = await listToolbar(this);
356
+ const switcher = toolbar.locator('a[data-role="direction-switcher"]');
357
+ const isDescending = /sort-desc/.test((await switcher.getAttribute('class')) || '');
358
+ if (isDescending === (direction === 'descending')) return;
359
+ const before = this.page.url();
360
+ await switcher.click();
361
+ await this.page.waitForURL((url) => url.toString() !== before, { timeout: budget(this) });
362
+ await settle(this);
363
+ });
364
+
365
+ /**
366
+ * Assert the products on the current page of the list are ordered by price or
367
+ * by name.
368
+ *
369
+ * Example #1: Then the product list should be ordered by price ascending
370
+ * Example #2: Then the product list should be ordered by price descending
371
+ * Example #3: And the product list should be ordered by name ascending
372
+ * Example #4: Then the product list should be ordered by name descending
373
+ * Example #5: Then the product list should be ordered by price ascending
374
+ *
375
+ */
376
+ Then(/^the product list should be ordered by (price|name) (ascending|descending)$/, async function (what, direction) {
377
+ await settle(this);
378
+ const values = await this.page.locator('.products.wrapper .product-item').evaluateAll((items, key) => items.map((item) => {
379
+ if (key === 'name') return (item.querySelector('.product-item-link') || {}).textContent || '';
380
+ const price = item.querySelector('.price-box [data-price-type="finalPrice"] .price, .price-box [data-price-type="minPrice"] .price, .price-box .price');
381
+ return price ? price.textContent : '';
382
+ }), what);
383
+ const keys = values.map((value) => (what === 'price' ? Number(clean(value).replace(/[^0-9.]/g, '')) : clean(value).toLowerCase()));
384
+ if (keys.length < 2) {
385
+ throw friendly({ message: `The product list shows ${keys.length} product(s): an order cannot be read from it.`, hint: LIST_HINT });
386
+ }
387
+ for (let i = 1; i < keys.length; i += 1) {
388
+ const ordered = what === 'price' ? (direction === 'ascending' ? keys[i - 1] <= keys[i] : keys[i - 1] >= keys[i]) : (direction === 'ascending' ? keys[i - 1].localeCompare(keys[i]) <= 0 : keys[i - 1].localeCompare(keys[i]) >= 0);
389
+ if (!ordered) {
390
+ throw friendly({
391
+ message: `The product list is not ordered by ${what} ${direction}: "${clean(values[i - 1])}" comes before "${clean(values[i])}" (products ${i} and ${i + 1}).`,
392
+ hint: 'Sort the list first: `When I sort the product list by "Price"` and `When I set the product list direction to …`.',
393
+ });
394
+ }
395
+ }
396
+ });
397
+
398
+ /**
399
+ * Show the product list as a list or as a grid.
400
+ *
401
+ * Example #1: When I view the product list as a list
402
+ * Example #2: When I view the product list as a grid
403
+ * Example #3: And I view the product list as a list
404
+ * Example #4: When we view the product list as a grid
405
+ * Example #5: When view the product list as a list
406
+ *
407
+ */
408
+ When(/^(I |we )*view the product list as a (list|grid)$/, async function (pronounCase, mode) {
409
+ const toolbar = await listToolbar(this);
410
+ const button = toolbar.locator(`.modes-mode.mode-${mode}`);
411
+ if (/(^|\s)active(\s|$)/.test((await button.getAttribute('class')) || '')) return;
412
+ const before = this.page.url();
413
+ await button.click();
414
+ await this.page.waitForURL((url) => url.toString() !== before, { timeout: budget(this) });
415
+ await settle(this);
416
+ });
417
+
418
+ /**
419
+ * Assert the product list is shown as a list or as a grid.
420
+ *
421
+ * Example #1: Then the product list should be shown as a list
422
+ * Example #2: Then the product list should be shown as a grid
423
+ * Example #3: And the product list should be shown as a list
424
+ * Example #4: And the product list should be shown as a grid
425
+ * Example #5: Then the product list should be shown as a list
426
+ *
427
+ */
428
+ Then(/^the product list should be shown as a (list|grid)$/, async function (mode) {
429
+ await assertValue(this, async () => (/(^|\s)products-list(\s|$)/.test((await this.page.locator('.products.wrapper').first().getAttribute('class')) || '') ? 'list' : 'grid'), mode, {
430
+ label: 'the mode of the product list',
431
+ hint: LIST_HINT + ' The wrapper carries `products-list` or `products-grid`.',
432
+ });
433
+ });
434
+
435
+ /**
436
+ * Go to a page of the product list: the next one, the previous one or a page
437
+ * by its number.
438
+ *
439
+ * Example #1: When I go to the next page of the product list
440
+ * Example #2: When I go to the previous page of the product list
441
+ * Example #3: When I go to page 2 of the product list
442
+ * Example #4: And we go to page 3 of the product list
443
+ * Example #5: When we go to the next page of the product list
444
+ *
445
+ */
446
+ When(/^(I |we )*go to (?:the (next|previous) page|page (\d+)) of the product list$/, async function (pronounCase, direction, number) {
447
+ await settle(this);
448
+ const pager = this.page.locator('.pages:visible').first();
449
+ const link = direction
450
+ ? pager.locator(direction === 'next' ? 'a.next' : 'a.previous')
451
+ : pager.locator('a.page').filter({ has: this.page.locator('span:last-child', { hasText: exactly(String(number)) }) });
452
+ if (!(await link.count())) {
453
+ throw friendly({ message: `The product list has no ${direction ? direction + ' page' : 'page ' + number}.`, hint: 'The pager shows only when the list has more products than fit on a page.' });
454
+ }
455
+ await actAndSettle(this, () => link.first().click({ noWaitAfter: true }));
456
+ });
457
+
458
+ /**
459
+ * Assert the page number the product list is on.
460
+ *
461
+ * Example #1: Then the product list should be on page 2
462
+ * Example #2: Then the product list should be on page 1
463
+ * Example #3: And the product list should be on page 3
464
+ * Example #4: Then the product list should be on page 4
465
+ * Example #5: Then the product list should be on page 5
466
+ *
467
+ */
468
+ Then(/^the product list should be on page (\d+)$/, async function (number) {
469
+ await assertValue(this, async () => {
470
+ const current = this.page.locator('.pages:visible').first().locator('li.current .page span:last-child');
471
+ return (await current.count()) ? current.first().innerText() : '1';
472
+ }, String(number), { label: 'the page of the product list', hint: LIST_HINT });
473
+ });
474
+
475
+ /**
476
+ * Filter the product list with the layered navigation ("Shopping Options"):
477
+ * the filter is expanded and the option is followed.
478
+ *
479
+ * Example #1: When I filter the product list by "Activity" with "Yoga"
480
+ * Example #2: When I filter the product list by "Style" with "Backpack"
481
+ * Example #3: And I filter the product list by "Material" with "Nylon"
482
+ * Example #4: When we filter the product list by "Color" with "Blue"
483
+ * Example #5: When filter the product list by "Activity" with "Gym"
484
+ *
485
+ */
486
+ When(/^(I |we )*filter the product list by "([^"]*)" with "([^"]*)"$/, async function (pronounCase, filter, option) {
487
+ await settle(this);
488
+ const block = this.page.locator('.block.filter');
489
+ const title = block.locator('.filter-options-title').filter({ hasText: exactly(filter) }).first();
490
+ if (!(await title.count())) {
491
+ const all = await block.locator('.filter-options-title').evaluateAll((titles) => titles.map((el) => el.textContent.replace(/\s+/g, ' ').trim())).catch(() => []);
492
+ throw friendly({ message: `The product list has no "${filter}" filter. Its filters: ${all.join(', ') || '(none)'}.`, hint: 'The filters are the "Shopping Options" of the page; a filter in use moves to "Now Shopping by".' });
493
+ }
494
+ await actOrExplain('filter the product list by', `${filter}: ${option}`, async () => {
495
+ if ((await title.getAttribute('aria-expanded')) !== 'true') await title.click();
496
+ const link = title.locator('xpath=following-sibling::*[1]').locator('a').filter({ hasText: new RegExp('^\\s*' + escapeRegExp(option) + '(\\s|$)') }).first();
497
+ await link.waitFor({ state: 'visible', timeout: budget(this) });
498
+ await actAndSettle(this, () => link.click({ noWaitAfter: true }));
499
+ }, 'Use the option text as the filter shows it, without its count.');
500
+ });
501
+
502
+ /**
503
+ * Assert the product list is (or is not) filtered by a filter with a value
504
+ * (the "Now Shopping by" list).
505
+ *
506
+ * Example #1: Then the product list should be filtered by "Activity" with "Yoga"
507
+ * Example #2: Then the product list should not be filtered by "Activity" with "Yoga"
508
+ * Example #3: And the product list should be filtered by "Style" with "Backpack"
509
+ * Example #4: Then the product list should be filtered by "Color" with "Blue"
510
+ * Example #5: Then the product list should not be filtered by "Material" with "Nylon"
511
+ *
512
+ */
513
+ Then(/^the product list should( not)* be filtered by "([^"]*)" with "([^"]*)"$/, async function (notCase, filter, option) {
514
+ await settle(this);
515
+ const item = this.page.locator('.filter-current li.item')
516
+ .filter({ has: this.page.locator('.filter-label', { hasText: exactly(filter) }) })
517
+ .filter({ has: this.page.locator('.filter-value', { hasText: exactly(option) }) });
518
+ const found = (await item.count()) > 0;
519
+ if (found === Boolean(notCase)) {
520
+ const current = await this.page.locator('.filter-current li.item').evaluateAll((items) => items.map((el) => (el.querySelector('.filter-label').textContent + ': ' + el.querySelector('.filter-value').textContent).replace(/\s+/g, ' ').trim())).catch(() => []);
521
+ throw friendly({
522
+ message: notCase ? `Expected the product list not to be filtered by ${filter}: ${option}, but it is.` : `Expected the product list to be filtered by ${filter}: ${option}. Filters in use: ${current.join(', ') || '(none)'}.`,
523
+ hint: 'The filters in use are listed under "Now Shopping by" (`.filter-current`).',
524
+ });
525
+ }
526
+ });
527
+
528
+ /**
529
+ * Remove every filter of the layered navigation ("Clear All").
530
+ *
531
+ * Example #1: When I clear the product list filters
532
+ * Example #2: And I clear the product list filters
533
+ * Example #3: When we clear the product list filters
534
+ * Example #4: When clear the product list filters
535
+ * Example #5: And we clear the product list filters
536
+ *
537
+ */
538
+ When(/^(I |we )*clear the product list filters$/, async function (pronounCase) {
539
+ await settle(this);
540
+ const clear = this.page.locator('.block.filter a.filter-clear').first();
541
+ if (!(await clear.count())) {
542
+ throw friendly({ message: 'The product list has no filter in use, so there is no "Clear All".', hint: 'Filter the list first: `When I filter the product list by "Activity" with "Yoga"`.' });
543
+ }
544
+ await actAndSettle(this, () => clear.click({ noWaitAfter: true }));
545
+ });
546
+
547
+ // ---------------------------------------------------------------------------
548
+ // Search
549
+ // ---------------------------------------------------------------------------
550
+
551
+ /**
552
+ * Search the store with the search box of the header and wait for the result
553
+ * page.
554
+ *
555
+ * Example #1: When I search the store for "yoga"
556
+ * Example #2: When I search the store for "bag"
557
+ * Example #3: And I search the store for "Joust Duffle Bag"
558
+ * Example #4: When we search the store for "24-MB01"
559
+ * Example #5: When search the store for "zzzqqqxxx"
560
+ *
561
+ */
562
+ When(/^(I |we )*search the store for "([^"]*)"$/, async function (pronounCase, text) {
563
+ await settle(this);
564
+ const box = this.page.locator('#search');
565
+ await actOrExplain('search the store for', text, async () => {
566
+ await box.fill(text, { timeout: budget(this) });
567
+ await box.press('Enter');
568
+ await this.page.waitForURL(/catalogsearch\/result/, { timeout: budget(this) });
569
+ }, 'The search box is `#search` in the header. A text shorter than the minimum query length is not searched.');
570
+ await settle(this);
571
+ });
572
+
573
+ /**
574
+ * Type a text in the search box of the header the way a person does, key by
575
+ * key, without submitting: the store answers with suggestions.
576
+ *
577
+ * Example #1: When I type "yog" in the store search
578
+ * Example #2: When I type "bag" in the store search
579
+ * Example #3: And I type "tee" in the store search
580
+ * Example #4: When we type "yoga" in the store search
581
+ * Example #5: When type "wat" in the store search
582
+ *
583
+ */
584
+ When(/^(I |we )*type "([^"]*)" in the store search$/, async function (pronounCase, text) {
585
+ await settle(this);
586
+ const box = this.page.locator('#search');
587
+ await box.click();
588
+ await box.fill('');
589
+ await box.pressSequentially(text, { delay: 60 });
590
+ await settle(this);
591
+ });
592
+
593
+ /**
594
+ * Assert the search box shows (or does not show) a suggestion. Suggestions are
595
+ * the terms earlier searches used.
596
+ *
597
+ * Example #1: Then I should see the search suggestion "yoga"
598
+ * Example #2: Then I should not see the search suggestion "zzz"
599
+ * Example #3: And I should see the search suggestion "bag"
600
+ * Example #4: Then we should see the search suggestion "tee"
601
+ * Example #5: Then should not see the search suggestion "nothing"
602
+ *
603
+ */
604
+ Then(/^(I |we )*should( not)* see the search suggestion "([^"]*)"$/, async function (pronounCase, notCase, text) {
605
+ await assertPresence(this.page.locator('#search_autocomplete [role="option"] .qs-option-name').filter({ hasText: exactly(text) }), notCase, {
606
+ label: `the search suggestion "${text}"`,
607
+ hint: 'Suggestions show while a person types (`When I type "…" in the store search`) and come from the search terms the store has recorded.',
608
+ timeout: notCase ? 3000 : budget(this),
609
+ found: async () => {
610
+ const all = await this.page.locator('#search_autocomplete [role="option"] .qs-option-name').allInnerTexts().catch(() => []);
611
+ return all.length ? `the suggestions ${all.map((item) => `"${clean(item)}"`).join(', ')}` : 'no suggestion';
612
+ },
613
+ });
614
+ });
615
+
616
+ // ---------------------------------------------------------------------------
617
+ // Product page
618
+ // ---------------------------------------------------------------------------
619
+
620
+ /**
621
+ * The option group (swatches) of the product page with a label.
622
+ *
623
+ * @param {object} world
624
+ * @param {string} label
625
+ * @returns {Promise<import('playwright').Locator>}
626
+ */
627
+ async function optionGroup(world, label) {
628
+ await settle(world);
629
+ const group = world.page.locator('.product-options-wrapper .swatch-attribute').filter({ has: world.page.locator('.swatch-attribute-label', { hasText: exactly(label) }) }).first();
630
+ if (!(await group.count())) {
631
+ const all = await world.page.locator('.product-options-wrapper .swatch-attribute-label').allInnerTexts().catch(() => []);
632
+ throw friendly({ message: `The product has no "${label}" option. Its options: ${all.map(clean).join(', ') || '(none; is this a configurable product?)'}.`, hint: 'The options of a configurable product show as swatches above the quantity.' });
633
+ }
634
+ return group;
635
+ }
636
+
637
+ /**
638
+ * Choose a value of an option of a configurable product by clicking its
639
+ * swatch ("Size" "M", "Color" "Blue").
640
+ *
641
+ * Example #1: When I choose the "Size" option "M"
642
+ * Example #2: When I choose the "Color" option "Blue"
643
+ * Example #3: And I choose the "Size" option "XL"
644
+ * Example #4: When we choose the "Color" option "Orange"
645
+ * Example #5: When choose the "Size" option "S"
646
+ *
647
+ */
648
+ When(/^(I |we )*choose the "([^"]*)" option "([^"]*)"$/, async function (pronounCase, label, value) {
649
+ const group = await optionGroup(this, label);
650
+ const swatch = group.locator(`.swatch-option[data-option-label="${value.replace(/"/g, '\\"')}"]`).first();
651
+ if (!(await swatch.count())) {
652
+ const all = await group.locator('.swatch-option').evaluateAll((options) => options.map((el) => el.getAttribute('data-option-label')));
653
+ throw friendly({ message: `The "${label}" option has no "${value}". Its values: ${all.join(', ')}.`, hint: 'Use the value as the swatch names it.' });
654
+ }
655
+ if ((await swatch.getAttribute('aria-checked')) !== 'true') await swatch.click();
656
+ await assertValue(this, () => swatch.getAttribute('aria-checked'), 'true', { label: `the state of the "${value}" swatch of "${label}"`, hint: 'A value that is out of stock for the other chosen options cannot be selected.' });
657
+ });
658
+
659
+ /**
660
+ * Assert a value of an option is (or is not) the selected one.
661
+ *
662
+ * Example #1: Then the "Size" option should be "M"
663
+ * Example #2: Then the "Color" option should be "Blue"
664
+ * Example #3: And the "Size" option should not be "XL"
665
+ * Example #4: Then the "Color" option should be "Orange"
666
+ * Example #5: Then the "Size" option should be "S"
667
+ *
668
+ */
669
+ Then(/^the "([^"]*)" option should( not)* be "([^"]*)"$/, async function (label, notCase, value) {
670
+ const group = await optionGroup(this, label);
671
+ await assertValue(this, async () => clean(await group.locator('.swatch-attribute-selected-option').first().textContent().catch(() => '')), value, {
672
+ label: `the selected value of the "${label}" option`,
673
+ notCase,
674
+ hint: 'The selected value shows next to the option label.',
675
+ });
676
+ });
677
+
678
+ /**
679
+ * Set the quantity of the product page.
680
+ *
681
+ * Example #1: When I set the product quantity to 2
682
+ * Example #2: When I set the product quantity to 1
683
+ * Example #3: And I set the product quantity to 3
684
+ * Example #4: When we set the product quantity to 10
685
+ * Example #5: When set the product quantity to 5
686
+ *
687
+ */
688
+ When(/^(I |we )*set the product quantity to (\d+)$/, async function (pronounCase, quantity) {
689
+ await settle(this);
690
+ await actOrExplain('set the product quantity to', String(quantity), () => this.page.locator('#qty').fill(String(quantity), { timeout: budget(this) }), 'The quantity field of a product page is `#qty`.');
691
+ });
692
+
693
+ /**
694
+ * Press "Add to Cart" on a product page and wait until the store has answered:
695
+ * the button goes "Adding…", "Added" and back, and the mini cart reloads. A
696
+ * refused add (a required option not chosen) ends the step as well: follow it
697
+ * with a message or a field error assertion.
698
+ *
699
+ * Example #1: When I add the product to the cart
700
+ * Example #2: And I add the product to the cart
701
+ * Example #3: When we add the product to the cart
702
+ * Example #4: When add the product to the cart
703
+ * Example #5: And we add the product to the cart
704
+ *
705
+ */
706
+ When(/^(I |we )*add the product to the cart$/, async function (pronounCase) {
707
+ await settle(this);
708
+ const page = this.page;
709
+ const button = page.locator('#product-addtocart-button');
710
+ await actOrExplain('add the product to', 'the cart', async () => {
711
+ await button.waitFor({ state: 'visible', timeout: budget(this) });
712
+ await button.click();
713
+ const limit = Date.now() + budget(this);
714
+ // The request starts a moment after the click: wait for the button to turn
715
+ // busy (or for a field error), then for it to come back.
716
+ let started = false;
717
+ while (Date.now() < limit) {
718
+ const state = await page.evaluate(() => {
719
+ const el = document.querySelector('#product-addtocart-button');
720
+ const counter = document.querySelector('.minicart-wrapper .counter');
721
+ return {
722
+ busy: !el || el.classList.contains('disabled') || (counter && counter.classList.contains('_block-content-loading')),
723
+ error: [...document.querySelectorAll('.product-add-form div.mage-error, .page.messages .message-error, .page.messages .message-success')].some((node) => node.getClientRects().length),
724
+ };
725
+ }).catch(() => ({ busy: true, error: false }));
726
+ if (state.busy) started = true;
727
+ if (!state.busy && (started || state.error)) break;
728
+ await page.waitForTimeout(100);
729
+ }
730
+ }, 'The button is `#product-addtocart-button`; it is disabled until the page scripts are ready.');
731
+ await settle(this);
732
+ });
733
+
734
+ /**
735
+ * Assert the price the product page shows.
736
+ *
737
+ * Example #1: Then the product price should be "$34.00"
738
+ * Example #2: Then the product price should be "$22.00"
739
+ * Example #3: And the product price should be "$12.50"
740
+ * Example #4: Then the product price should be "$45.00"
741
+ * Example #5: Then the product price should be "$59.00"
742
+ *
743
+ */
744
+ Then(/^the product price should be "([^"]*)"$/, async function (price) {
745
+ await assertValue(this, () => this.page.locator('.product-info-main .price-box .price').first().innerText(), price, {
746
+ label: 'the product price',
747
+ hint: 'The price of a configurable product follows the chosen options.',
748
+ });
749
+ });
750
+
751
+ /**
752
+ * Open a tab of the product page by its name ("Details", "More Information",
753
+ * "Reviews"; the review counter after the name is not part of it). The reviews
754
+ * are fetched when their tab is opened for the first time: the step waits for
755
+ * them.
756
+ *
757
+ * Example #1: When I open the "Reviews" product tab
758
+ * Example #2: When I open the "Details" product tab
759
+ * Example #3: And I open the "More Information" product tab
760
+ * Example #4: When we open the "Reviews" product tab
761
+ * Example #5: When open the "Details" product tab
762
+ *
763
+ */
764
+ When(/^(I |we )*open the "([^"]*)" product tab$/, async function (pronounCase, name) {
765
+ await settle(this);
766
+ const tabs = this.page.locator('.product.data.items > .data.item.title');
767
+ const tab = tabs.filter({ hasText: new RegExp('^\\s*' + escapeRegExp(name) + '(\\s+\\d+)?\\s*$', 'i') }).first();
768
+ if (!(await tab.count())) {
769
+ const all = await tabs.allInnerTexts().catch(() => []);
770
+ throw friendly({ message: `The product page has no "${name}" tab. Its tabs: ${all.map(clean).join(', ') || '(none)'}.`, hint: 'Use the tab name without the counter ("Reviews", not "Reviews 4").' });
771
+ }
772
+ if ((await tab.getAttribute('aria-expanded')) !== 'true') {
773
+ await actAndSettle(this, () => tab.locator('a.data.switch').click({ noWaitAfter: true }));
774
+ }
775
+ await assertValue(this, () => tab.getAttribute('aria-expanded'), 'true', { label: `the state of the "${name}" tab`, hint: 'The open tab carries `aria-expanded="true"`.' });
776
+ await settle(this);
777
+ });
778
+
779
+ // ---------------------------------------------------------------------------
780
+ // Mini cart
781
+ // ---------------------------------------------------------------------------
782
+
783
+ /**
784
+ * Assert the number the mini cart of the header shows, or that it is empty.
785
+ *
786
+ * Example #1: Then the mini cart should show 1 item
787
+ * Example #2: Then the mini cart should show 2 items
788
+ * Example #3: And the mini cart should show 0 items
789
+ * Example #4: Then the mini cart should show 3 items
790
+ * Example #5: Then the mini cart should show 5 items
791
+ *
792
+ */
793
+ Then(/^the mini cart should show (\d+) items?$/, async function (count) {
794
+ await assertValue(this, async () => {
795
+ await settle(this);
796
+ const text = clean(await this.page.locator('.minicart-wrapper .counter-number').first().textContent());
797
+ return text === '' ? '0' : text;
798
+ }, String(count), {
799
+ label: 'the number of the mini cart',
800
+ hint: 'The mini cart counts the quantities; it is filled from the cart data the page loads after it is shown.',
801
+ });
802
+ });
803
+
804
+ /**
805
+ * Open the mini cart of the header.
806
+ *
807
+ * Example #1: When I open the mini cart
808
+ * Example #2: And I open the mini cart
809
+ * Example #3: When we open the mini cart
810
+ * Example #4: When open the mini cart
811
+ * Example #5: And we open the mini cart
812
+ *
813
+ */
814
+ When(/^(I |we )*open the mini cart$/, async function (pronounCase) {
815
+ await settle(this);
816
+ const wrapper = this.page.locator('.minicart-wrapper');
817
+ if (!/(^|\s)active(\s|$)/.test((await wrapper.getAttribute('class')) || '')) {
818
+ await wrapper.locator('a.showcart').click();
819
+ }
820
+ await this.page.locator('#minicart-content-wrapper').waitFor({ state: 'visible', timeout: budget(this) });
821
+ await settle(this);
822
+ });
823
+
824
+ /**
825
+ * Assert the open mini cart holds (or does not hold) a product.
826
+ *
827
+ * Example #1: Then the mini cart should contain "Joust Duffle Bag"
828
+ * Example #2: Then the mini cart should not contain "Radiant Tee"
829
+ * Example #3: And the mini cart should contain "Aim Analog Watch"
830
+ * Example #4: Then the mini cart should contain "Radiant Tee"
831
+ * Example #5: Then the mini cart should not contain "Test Bag"
832
+ *
833
+ */
834
+ Then(/^the mini cart should( not)* contain "([^"]*)"$/, async function (notCase, name) {
835
+ if (!(await this.page.locator('#minicart-content-wrapper').isVisible().catch(() => false))) {
836
+ throw friendly({ message: 'The mini cart is not open.', hint: 'Open it first: `When I open the mini cart`.' });
837
+ }
838
+ await assertPresence(this.page.locator('#minicart-content-wrapper .product-item-name').filter({ hasText: exactly(name) }), notCase, {
839
+ label: `"${name}" in the mini cart`,
840
+ hint: 'The mini cart lists the product names of the cart.',
841
+ timeout: notCase ? 3000 : budget(this),
842
+ found: async () => `the mini cart "${clean(await this.page.locator('#minicart-content-wrapper').innerText().catch(() => '')).slice(0, 160)}"`,
843
+ });
844
+ });
845
+
846
+ // ---------------------------------------------------------------------------
847
+ // Cart
848
+ // ---------------------------------------------------------------------------
849
+
850
+ /**
851
+ * The lines of the cart page that hold a product name.
852
+ *
853
+ * @param {object} world
854
+ * @param {string} [name]
855
+ * @returns {import('playwright').Locator}
856
+ */
857
+ function cartLines(world, name) {
858
+ const lines = world.page.locator('#shopping-cart-table tbody.cart.item');
859
+ return name ? lines.filter({ has: world.page.locator('.product-item-name', { hasText: exactly(name) }) }) : lines;
860
+ }
861
+
862
+ /**
863
+ * Fail when the page is not the cart.
864
+ *
865
+ * @param {object} world
866
+ */
867
+ async function requireCart(world) {
868
+ await settle(world);
869
+ if (!(await world.page.locator('body.checkout-cart-index').count())) {
870
+ throw friendly({ message: 'This is not the cart page.', hint: CART_HINT });
871
+ }
872
+ }
873
+
874
+ /**
875
+ * Open the cart page or the checkout.
876
+ *
877
+ * Example #1: When I go to the cart
878
+ * Example #2: When I go to the checkout
879
+ * Example #3: Given I am on the cart
880
+ * Example #4: Given we are on the checkout
881
+ * Example #5: And we go to the cart
882
+ *
883
+ */
884
+ Given(/^(?:(?:I am |we are )+on|(?:I |we )*go to) the (cart|checkout)$/, async function (page) {
885
+ await open(this, siteUrl(this, page === 'cart' ? 'checkout/cart/' : 'checkout/'));
886
+ if (page === 'checkout' && !(await this.page.locator('body.checkout-index-index').count())) {
887
+ throw friendly({ message: 'The store did not open the checkout: it showed the cart instead.', hint: 'The checkout needs a product in the cart.' });
888
+ }
889
+ });
890
+
891
+ /**
892
+ * Empty the cart of the session: every line is removed. For a logged-in
893
+ * customer, whose cart is kept between visits, it is the clean start of a
894
+ * scenario.
895
+ *
896
+ * Example #1: Given my cart is empty
897
+ * Example #2: And my cart is empty
898
+ * Example #3: Given our cart is empty
899
+ * Example #4: And our cart is empty
900
+ * Example #5: Given my cart is empty now
901
+ *
902
+ */
903
+ Given(/^(?:my|our) cart is empty(?: now)?$/, async function () {
904
+ await open(this, siteUrl(this, 'checkout/cart/'));
905
+ for (let i = 0; i < 50; i += 1) {
906
+ const line = cartLines(this).first();
907
+ if (!(await line.count())) return;
908
+ await actAndSettle(this, () => line.locator('a.action-delete').click({ noWaitAfter: true }));
909
+ }
910
+ throw friendly({ message: 'The cart still holds products after 50 removals.', hint: 'Remove the lines by hand and check what refuses to go.' });
911
+ });
912
+
913
+ /**
914
+ * Assert the cart page holds (or does not hold) a product.
915
+ *
916
+ * Example #1: Then the cart should contain "Joust Duffle Bag"
917
+ * Example #2: Then the cart should not contain "Radiant Tee"
918
+ * Example #3: And the cart should contain "Aim Analog Watch"
919
+ * Example #4: Then the cart should contain "Radiant Tee"
920
+ * Example #5: Then the cart should not contain "Test Bag"
921
+ *
922
+ */
923
+ Then(/^the cart should( not)* contain "([^"]*)"$/, async function (notCase, name) {
924
+ await requireCart(this);
925
+ await assertPresence(cartLines(this, name), notCase, {
926
+ label: `"${name}" in the cart`,
927
+ hint: CART_HINT,
928
+ timeout: notCase ? 3000 : budget(this),
929
+ found: async () => {
930
+ const names = await this.page.locator('#shopping-cart-table .product-item-name').allInnerTexts().catch(() => []);
931
+ return names.length ? `the products ${names.map((text) => `"${clean(text)}"`).join(', ')}` : 'an empty cart';
932
+ },
933
+ });
934
+ });
935
+
936
+ /**
937
+ * Change the quantity of a line of the cart and press "Update Shopping Cart".
938
+ *
939
+ * Example #1: When I change the cart quantity of "Joust Duffle Bag" to 3
940
+ * Example #2: When I change the cart quantity of "Radiant Tee" to 1
941
+ * Example #3: And I change the cart quantity of "Aim Analog Watch" to 2
942
+ * Example #4: When we change the cart quantity of "Joust Duffle Bag" to 5
943
+ * Example #5: When change the cart quantity of "Radiant Tee" to 4
944
+ *
945
+ */
946
+ When(/^(I |we )*change the cart quantity of "([^"]*)" to (\d+)$/, async function (pronounCase, name, quantity) {
947
+ await requireCart(this);
948
+ const line = cartLines(this, name).first();
949
+ await actOrExplain('change the cart quantity of', name, async () => {
950
+ await line.locator('input[data-role="cart-item-qty"]').fill(String(quantity), { timeout: budget(this) });
951
+ await actAndSettle(this, () => this.page.locator('.cart.main.actions button.action.update').click({ noWaitAfter: true }));
952
+ }, CART_HINT + ' The product must be in the cart.');
953
+ });
954
+
955
+ /**
956
+ * Assert the quantity of a line of the cart.
957
+ *
958
+ * Example #1: Then the cart quantity of "Joust Duffle Bag" should be 3
959
+ * Example #2: Then the cart quantity of "Radiant Tee" should be 1
960
+ * Example #3: And the cart quantity of "Aim Analog Watch" should be 2
961
+ * Example #4: Then the cart quantity of "Joust Duffle Bag" should be 5
962
+ * Example #5: Then the cart quantity of "Radiant Tee" should be 4
963
+ *
964
+ */
965
+ Then(/^the cart quantity of "([^"]*)" should be (\d+)$/, async function (name, quantity) {
966
+ await requireCart(this);
967
+ await assertValue(this, () => cartLines(this, name).first().locator('input[data-role="cart-item-qty"]').inputValue({ timeout: 2000 }), String(quantity), {
968
+ label: `the cart quantity of "${name}"`,
969
+ hint: CART_HINT + ' The product must be in the cart.',
970
+ });
971
+ });
972
+
973
+ /**
974
+ * Remove a line from the cart ("Remove item").
975
+ *
976
+ * Example #1: When I remove "Joust Duffle Bag" from the cart
977
+ * Example #2: When I remove "Radiant Tee" from the cart
978
+ * Example #3: And I remove "Aim Analog Watch" from the cart
979
+ * Example #4: When we remove "Joust Duffle Bag" from the cart
980
+ * Example #5: When remove "Radiant Tee" from the cart
981
+ *
982
+ */
983
+ When(/^(I |we )*remove "([^"]*)" from the cart$/, async function (pronounCase, name) {
984
+ await requireCart(this);
985
+ const line = cartLines(this, name).first();
986
+ await actOrExplain('remove from the cart', name, async () => {
987
+ await line.locator('a.action-delete').waitFor({ state: 'visible', timeout: budget(this) });
988
+ await actAndSettle(this, () => line.locator('a.action-delete').click({ noWaitAfter: true }));
989
+ }, CART_HINT + ' The product must be in the cart.');
990
+ });
991
+
992
+ /**
993
+ * Assert a total of the cart page: "subtotal", "shipping", "discount", "tax"
994
+ * or "order total".
995
+ *
996
+ * Example #1: Then the cart subtotal should be "$34.00"
997
+ * Example #2: Then the cart order total should be "$39.00"
998
+ * Example #3: And the cart shipping should be "$5.00"
999
+ * Example #4: Then the cart discount should be "-$3.40"
1000
+ * Example #5: Then the cart order total should be "$30.60"
1001
+ *
1002
+ */
1003
+ Then(/^the cart (subtotal|shipping|discount|tax|order total) should be "([^"]*)"$/, async function (total, amount) {
1004
+ await requireCart(this);
1005
+ await assertValue(this, async () => {
1006
+ const rows = await this.page.locator('#cart-totals tr').evaluateAll((trs) => trs.map((tr) => ({
1007
+ name: ((tr.querySelector('th') || {}).textContent || '').replace(/\s+/g, ' ').trim().toLowerCase(),
1008
+ amount: ((tr.querySelector('td .price') || tr.querySelector('td') || {}).textContent || '').replace(/\s+/g, ' ').trim(),
1009
+ })));
1010
+ const row = rows.find((item) => item.name.startsWith(total));
1011
+ return row ? row.amount : `no "${total}" line (totals: ${rows.map((item) => item.name).join(', ') || 'none yet'})`;
1012
+ }, amount, { label: `the cart ${total}`, hint: 'The totals are computed by a request after the page is shown; shipping shows once a shipping estimate is chosen, discount once a coupon applies.' });
1013
+ });
1014
+
1015
+ /**
1016
+ * Apply a discount code on the cart page ("Apply Discount Code"). Follow it
1017
+ * with a message assertion: a code that does not apply answers with an error.
1018
+ *
1019
+ * Example #1: When I apply the coupon "TEST10"
1020
+ * Example #2: When I apply the coupon "NOPE"
1021
+ * Example #3: And I apply the coupon "H20"
1022
+ * Example #4: When we apply the coupon "SAVE5"
1023
+ * Example #5: When apply the coupon "TEST10"
1024
+ *
1025
+ */
1026
+ When(/^(I |we )*apply the coupon "([^"]*)"$/, async function (pronounCase, code) {
1027
+ await requireCart(this);
1028
+ const field = this.page.locator('#coupon_code');
1029
+ await actOrExplain('apply the coupon', code, async () => {
1030
+ if (!(await field.isVisible())) await this.page.locator('#block-discount-heading').click();
1031
+ await field.fill(code, { timeout: budget(this) });
1032
+ await actAndSettle(this, () => this.page.locator('#discount-coupon-form button.action.apply').click({ noWaitAfter: true }));
1033
+ }, CART_HINT + ' A coupon that is already applied must be cancelled first.');
1034
+ });
1035
+
1036
+ /**
1037
+ * Cancel the coupon of the cart ("Cancel Coupon").
1038
+ *
1039
+ * Example #1: When I cancel the coupon
1040
+ * Example #2: And I cancel the coupon
1041
+ * Example #3: When we cancel the coupon
1042
+ * Example #4: When cancel the coupon
1043
+ * Example #5: And we cancel the coupon
1044
+ *
1045
+ */
1046
+ When(/^(I |we )*cancel the coupon$/, async function (pronounCase) {
1047
+ await requireCart(this);
1048
+ const cancel = this.page.locator('#discount-coupon-form button.action.cancel');
1049
+ if (!(await cancel.count())) {
1050
+ throw friendly({ message: 'The cart has no coupon to cancel.', hint: 'Apply one first: `When I apply the coupon "…"`.' });
1051
+ }
1052
+ if (!(await cancel.isVisible())) await this.page.locator('#block-discount-heading').click();
1053
+ await actAndSettle(this, () => cancel.click({ noWaitAfter: true }));
1054
+ });
1055
+
1056
+ /**
1057
+ * Fill the shipping estimate of the cart page ("Estimate Shipping and Tax")
1058
+ * with a country, a state or province and a postal code, and wait for the
1059
+ * shipping methods.
1060
+ *
1061
+ * Example #1: When I estimate shipping to "United States", "Texas", "78701"
1062
+ * Example #2: When I estimate shipping to "United States", "California", "94105"
1063
+ * Example #3: And I estimate shipping to "United States", "New York", "10001"
1064
+ * Example #4: When we estimate shipping to "United States", "Texas", "75001"
1065
+ * Example #5: When estimate shipping to "United States", "Florida", "33101"
1066
+ *
1067
+ */
1068
+ When(/^(I |we )*estimate shipping to "([^"]*)", "([^"]*)", "([^"]*)"$/, async function (pronounCase, country, region, postcode) {
1069
+ await requireCart(this);
1070
+ const form = this.page.locator('#block-summary');
1071
+ await actOrExplain('estimate shipping to', `${country}, ${region}, ${postcode}`, async () => {
1072
+ if (!(await form.isVisible())) await this.page.locator('#block-shipping-heading').click();
1073
+ await form.locator('select[name="country_id"]').selectOption({ label: country }, { timeout: budget(this) });
1074
+ await settle(this);
1075
+ await form.locator('select[name="region_id"]').selectOption({ label: region }, { timeout: budget(this) });
1076
+ const zip = form.locator('input[name="postcode"]');
1077
+ await zip.fill(postcode);
1078
+ await zip.press('Tab');
1079
+ await settle(this);
1080
+ await this.page.locator('#co-shipping-method-form input[type="radio"]').first().waitFor({ state: 'visible', timeout: budget(this) });
1081
+ }, 'Use the country and the state as the selects name them.');
1082
+ });
1083
+
1084
+ /**
1085
+ * Choose a shipping method: by its carrier title in the estimate of the cart
1086
+ * page or in the shipping step of the checkout ("Flat Rate", "Free Shipping",
1087
+ * "Best Way").
1088
+ *
1089
+ * Example #1: When I choose the "Flat Rate" shipping method
1090
+ * Example #2: When I choose the "Free Shipping" shipping method
1091
+ * Example #3: And I choose the "Best Way" shipping method
1092
+ * Example #4: When we choose the "Flat Rate" shipping method
1093
+ * Example #5: When choose the "Free Shipping" shipping method
1094
+ *
1095
+ */
1096
+ When(/^(I |we )*choose the "([^"]*)" shipping method$/, async function (pronounCase, carrier) {
1097
+ await settle(this);
1098
+ const page = this.page;
1099
+ let radio;
1100
+ let titles;
1101
+ if (await page.locator('body.checkout-index-index').count()) {
1102
+ const rows = page.locator('#checkout-shipping-method-load tbody tr.row');
1103
+ await rows.first().waitFor({ state: 'visible', timeout: budget(this) });
1104
+ radio = rows.filter({ has: page.locator('td.col-carrier', { hasText: exactly(carrier) }) }).first().locator('input[type="radio"]');
1105
+ titles = await rows.locator('td.col-carrier').allInnerTexts();
1106
+ } else {
1107
+ const form = page.locator('#co-shipping-method-form');
1108
+ await form.locator('input[type="radio"]').first().waitFor({ state: 'visible', timeout: budget(this) }).catch(() => {});
1109
+ radio = form.locator('dt.item-title').filter({ hasText: exactly(carrier) }).first().locator('xpath=following-sibling::dd[1]').locator('input[type="radio"]').first();
1110
+ titles = await form.locator('dt.item-title').allInnerTexts();
1111
+ }
1112
+ if (!(await radio.count())) {
1113
+ throw friendly({ message: `There is no "${carrier}" shipping method. The methods: ${titles.map(clean).join(', ') || '(none; the address may be incomplete)'}.`, hint: 'Use the carrier title. On the cart page, estimate the shipping first; in the checkout, fill in the address first.' });
1114
+ }
1115
+ await radio.check();
1116
+ await settle(this);
1117
+ });
1118
+
1119
+ // ---------------------------------------------------------------------------
1120
+ // Checkout
1121
+ // ---------------------------------------------------------------------------
1122
+
1123
+ /**
1124
+ * Fail when the page is not the checkout.
1125
+ *
1126
+ * @param {object} world
1127
+ */
1128
+ async function requireCheckout(world) {
1129
+ await settle(world);
1130
+ if (!(await world.page.locator('body.checkout-index-index').count())) {
1131
+ throw friendly({ message: 'This is not the checkout.', hint: CHECKOUT_HINT });
1132
+ }
1133
+ }
1134
+
1135
+ /**
1136
+ * Fill the email of a guest in the shipping step of the checkout and wait
1137
+ * until the store has checked whether an account uses it.
1138
+ *
1139
+ * Example #1: When I fill in the checkout email with "guest@example.com"
1140
+ * Example #2: When I fill in the checkout email with "gail.guest@example.com"
1141
+ * Example #3: And I fill in the checkout email with "buyer@example.com"
1142
+ * Example #4: When we fill in the checkout email with "guest@example.com"
1143
+ * Example #5: When fill in the checkout email with "someone@example.com"
1144
+ *
1145
+ */
1146
+ When(/^(I |we )*fill in the checkout email with "([^"]*)"$/, async function (pronounCase, email) {
1147
+ await requireCheckout(this);
1148
+ const field = this.page.locator('#customer-email');
1149
+ await actOrExplain('fill in the checkout email with', email, async () => {
1150
+ await field.fill(email, { timeout: budget(this) });
1151
+ await field.press('Tab');
1152
+ }, 'The email field shows for a guest only; a logged-in customer has none.');
1153
+ await settle(this);
1154
+ });
1155
+
1156
+ // The fields of the shipping address form of the checkout, by label.
1157
+ const CHECKOUT_FIELDS = {
1158
+ 'first name': { name: 'firstname' },
1159
+ 'last name': { name: 'lastname' },
1160
+ 'company': { name: 'company' },
1161
+ 'street address': { name: 'street[0]' },
1162
+ 'street address: line 1': { name: 'street[0]' },
1163
+ 'street address: line 2': { name: 'street[1]' },
1164
+ 'country': { name: 'country_id', select: true },
1165
+ 'state/province': { name: 'region_id', select: true },
1166
+ 'city': { name: 'city' },
1167
+ 'zip/postal code': { name: 'postcode' },
1168
+ 'phone number': { name: 'telephone' },
1169
+ };
1170
+
1171
+ /**
1172
+ * Fill the shipping address of the checkout from a table of label and value.
1173
+ * The labels are those of the form: First Name, Last Name, Company, Street
1174
+ * Address, Country, State/Province, City, Zip/Postal Code, Phone Number. The
1175
+ * shipping methods reload when the address changes: the step waits for them.
1176
+ *
1177
+ * Example #1: When I fill in the shipping address:
1178
+ * Example #2: And I fill in the shipping address:
1179
+ * Example #3: When we fill in the shipping address:
1180
+ * Example #4: When fill in the shipping address:
1181
+ * Example #5: And we fill in the shipping address:
1182
+ *
1183
+ */
1184
+ When(/^(I |we )*fill in the shipping address:$/, async function (pronounCase, table) {
1185
+ await requireCheckout(this);
1186
+ const form = this.page.locator('#shipping-new-address-form');
1187
+ if (!(await form.isVisible().catch(() => false))) {
1188
+ throw friendly({ message: 'The shipping address form is not showing.', hint: 'A logged-in customer with an address book picks a saved address instead; a guest gets the form.' });
1189
+ }
1190
+ const rows = table.raw().map(([label, value]) => [clean(label), value]);
1191
+ // The state list depends on the country: the country goes first.
1192
+ rows.sort((a, b) => Number(b[0].toLowerCase() === 'country') - Number(a[0].toLowerCase() === 'country'));
1193
+ for (const [label, value] of rows) {
1194
+ const field = CHECKOUT_FIELDS[label.toLowerCase()];
1195
+ if (!field) {
1196
+ throw friendly({ message: `"${label}" is not a field of the shipping address.`, hint: `The fields: ${Object.keys(CHECKOUT_FIELDS).join(', ')}.` });
1197
+ }
1198
+ const control = form.locator(`[name="${field.name}"]`).first();
1199
+ await actOrExplain('fill in the shipping address field', label, async () => {
1200
+ if (field.select) {
1201
+ await control.selectOption({ label: value }, { timeout: budget(this) });
1202
+ await settle(this);
1203
+ } else {
1204
+ await control.fill(value, { timeout: budget(this) });
1205
+ await control.dispatchEvent('change');
1206
+ }
1207
+ }, 'Use the country and the state as the selects name them.');
1208
+ }
1209
+ await this.page.locator('#shipping-new-address-form [name="telephone"]').blur().catch(() => {});
1210
+ await settle(this);
1211
+ });
1212
+
1213
+ /**
1214
+ * Press "Next" in the shipping step of the checkout and wait for the payment
1215
+ * step. When the form refuses (a required field is empty) the step ends on the
1216
+ * shipping step: follow it with a field error assertion.
1217
+ *
1218
+ * Example #1: When I continue to the payment step
1219
+ * Example #2: And I continue to the payment step
1220
+ * Example #3: When we continue to the payment step
1221
+ * Example #4: When continue to the payment step
1222
+ * Example #5: And we continue to the payment step
1223
+ *
1224
+ */
1225
+ When(/^(I |we )*continue to the payment step$/, async function (pronounCase) {
1226
+ await requireCheckout(this);
1227
+ const page = this.page;
1228
+ await page.locator('#shipping-method-buttons-container button.continue').click();
1229
+ const limit = Date.now() + budget(this);
1230
+ while (Date.now() < limit) {
1231
+ if (/#payment$/.test(page.url())) break;
1232
+ if (await page.locator('#checkout .field-error:visible, #checkout div.mage-error:visible, #checkout .message.notice:visible, #checkout .message.error:visible').count()) break;
1233
+ await page.waitForTimeout(100);
1234
+ }
1235
+ await settle(this);
1236
+ });
1237
+
1238
+ /**
1239
+ * Assert the step the checkout is on.
1240
+ *
1241
+ * Example #1: Then the checkout should be on the shipping step
1242
+ * Example #2: Then the checkout should be on the payment step
1243
+ * Example #3: And the checkout should be on the payment step
1244
+ * Example #4: And the checkout should be on the shipping step
1245
+ * Example #5: Then the checkout should be on the payment step
1246
+ *
1247
+ */
1248
+ Then(/^the checkout should be on the (shipping|payment) step$/, async function (step) {
1249
+ await requireCheckout(this);
1250
+ await assertValue(this, async () => (/#payment$/.test(this.page.url()) ? 'payment' : 'shipping'), step, {
1251
+ label: 'the step of the checkout',
1252
+ hint: 'The checkout moves to the payment step when the address is complete and a shipping method is chosen.',
1253
+ });
1254
+ });
1255
+
1256
+ /**
1257
+ * Choose a payment method of the payment step by its title ("Check / Money
1258
+ * order").
1259
+ *
1260
+ * Example #1: When I choose the "Check / Money order" payment method
1261
+ * Example #2: And I choose the "Check / Money order" payment method
1262
+ * Example #3: When we choose the "Check / Money order" payment method
1263
+ * Example #4: When I choose the "Cash On Delivery" payment method
1264
+ * Example #5: When I choose the "Bank Transfer Payment" payment method
1265
+ *
1266
+ */
1267
+ When(/^(I |we )*choose the "([^"]*)" payment method$/, async function (pronounCase, title) {
1268
+ await requireCheckout(this);
1269
+ const method = this.page.locator('#checkout-payment-method-load .payment-method').filter({ has: this.page.locator('.payment-method-title label', { hasText: exactly(title) }) }).first();
1270
+ if (!(await method.count())) {
1271
+ const all = await this.page.locator('#checkout-payment-method-load .payment-method-title label').allInnerTexts().catch(() => []);
1272
+ throw friendly({ message: `There is no "${title}" payment method. The methods: ${all.map(clean).join(', ') || '(none; is the checkout on the payment step?)'}.`, hint: 'The payment methods are the ones enabled in the configuration of the store.' });
1273
+ }
1274
+ // With one method only the radio is hidden and the method is chosen already: the label is what a person clicks.
1275
+ if (!/(^|\s)_active(\s|$)/.test((await method.getAttribute('class')) || '')) {
1276
+ await method.locator('.payment-method-title label').click();
1277
+ }
1278
+ await assertValue(this, async () => (/(^|\s)_active(\s|$)/.test((await method.getAttribute('class')) || '') ? 'chosen' : 'not chosen'), 'chosen', {
1279
+ label: `the "${title}" payment method`,
1280
+ hint: 'The chosen method carries `_active` and shows its "Place Order" button.',
1281
+ });
1282
+ await settle(this);
1283
+ });
1284
+
1285
+ /**
1286
+ * Press "Place Order" in the payment step and wait for the success page. The
1287
+ * order number of that page is remembered for the rest of the scenario as "the
1288
+ * last placed order".
1289
+ *
1290
+ * Example #1: When I place the order
1291
+ * Example #2: And I place the order
1292
+ * Example #3: When we place the order
1293
+ * Example #4: When place the order
1294
+ * Example #5: And we place the order
1295
+ *
1296
+ */
1297
+ When(/^(I |we )*place the order$/, async function (pronounCase) {
1298
+ await requireCheckout(this);
1299
+ const page = this.page;
1300
+ const button = page.locator('.payment-method._active button.action.primary.checkout');
1301
+ await actOrExplain('place', 'the order', async () => {
1302
+ await button.waitFor({ state: 'visible', timeout: budget(this) });
1303
+ await button.click();
1304
+ await page.waitForURL(/checkout\/onepage\/success/, { timeout: budget(this) });
1305
+ }, 'The checkout must be on the payment step with a payment method chosen. An error of the store shows as a message above the payment methods.');
1306
+ await settle(this);
1307
+ const number = clean(await page.locator('.checkout-success .order-number, .checkout-success p > span').first().innerText().catch(() => ''));
1308
+ if (!/^\d+$/.test(number)) {
1309
+ throw friendly({ message: `The success page shows no order number (found "${number}").`, hint: 'The order number is in `.checkout-success`.' });
1310
+ }
1311
+ this.lastOrderNumber = number;
1312
+ });
1313
+
1314
+ /**
1315
+ * Assert the page is the order confirmation ("Thank you for your purchase!")
1316
+ * with an order number.
1317
+ *
1318
+ * Example #1: Then I should see the order confirmation
1319
+ * Example #2: And I should see the order confirmation
1320
+ * Example #3: Then we should see the order confirmation
1321
+ * Example #4: Then should see the order confirmation
1322
+ * Example #5: And we should see the order confirmation
1323
+ *
1324
+ */
1325
+ Then(/^(I |we )*should see the order confirmation$/, async function (pronounCase) {
1326
+ await settle(this);
1327
+ await assertPresence(this.page.locator('body.checkout-onepage-success .checkout-success'), null, {
1328
+ label: 'the order confirmation',
1329
+ hint: 'The confirmation is the page /checkout/onepage/success/ that follows "Place Order".',
1330
+ timeout: budget(this),
1331
+ found: async () => `the page "${clean(await this.page.title())}"`,
1332
+ });
1333
+ await assertValue(this, () => this.page.locator('.checkout-success .order-number, .checkout-success p > span').first().innerText(), /^\d+$/, {
1334
+ label: 'the order number of the confirmation',
1335
+ hint: 'A guest sees the number as text, a customer as a link to the order.',
1336
+ });
1337
+ });
1338
+
1339
+ // ---------------------------------------------------------------------------
1340
+ // Customer account
1341
+ // ---------------------------------------------------------------------------
1342
+
1343
+ // The pages of the customer account, by the name of their entry.
1344
+ const ACCOUNT_PAGES = {
1345
+ 'account': 'customer/account/',
1346
+ 'orders': 'sales/order/history/',
1347
+ 'wish list': 'wishlist/',
1348
+ 'address book': 'customer/address/',
1349
+ 'account information': 'customer/account/edit/',
1350
+ 'product reviews': 'review/customer/',
1351
+ 'newsletter subscriptions': 'newsletter/manage/',
1352
+ };
1353
+
1354
+ /**
1355
+ * Open a page of the customer account by its name: "account", "orders", "wish
1356
+ * list", "address book", "account information", "product reviews",
1357
+ * "newsletter subscriptions". A guest is sent to the sign-in page by the
1358
+ * store.
1359
+ *
1360
+ * Example #1: When I go to my "orders" account page
1361
+ * Example #2: When I go to my "address book" account page
1362
+ * Example #3: And I go to my "wish list" account page
1363
+ * Example #4: When we go to our "account" account page
1364
+ * Example #5: Given I am on my "newsletter subscriptions" account page
1365
+ *
1366
+ */
1367
+ Given(/^(?:(?:I am |we are )+on|(?:I |we )*go to) (?:my|our) "([^"]*)" account page$/, async function (name) {
1368
+ const key = clean(name).toLowerCase();
1369
+ if (!Object.prototype.hasOwnProperty.call(ACCOUNT_PAGES, key)) {
1370
+ throw friendly({ message: `"${name}" is not a known account page.`, hint: `Use one of: ${Object.keys(ACCOUNT_PAGES).join(', ')}.` });
1371
+ }
1372
+ await open(this, siteUrl(this, ACCOUNT_PAGES[key]));
1373
+ });
1374
+
1375
+ /**
1376
+ * Assert the order history of the customer lists (or does not list) the last
1377
+ * placed order, optionally with a status.
1378
+ *
1379
+ * Example #1: Then my order history should list the last placed order
1380
+ * Example #2: Then my order history should list the last placed order as "Pending"
1381
+ * Example #3: And my order history should not list the last placed order
1382
+ * Example #4: Then our order history should list the last placed order as "Complete"
1383
+ * Example #5: Then my order history should list the last placed order as "Canceled"
1384
+ *
1385
+ */
1386
+ Then(/^(?:my|our) order history should( not)* list the last placed order(?: as "([^"]*)")?$/, async function (notCase, status) {
1387
+ if (!this.lastOrderNumber) {
1388
+ throw friendly({ message: 'No order was placed in this scenario.', hint: 'Place one first: `When I place the order`.' });
1389
+ }
1390
+ await open(this, siteUrl(this, 'sales/order/history/'));
1391
+ const row = this.page.locator('#my-orders-table tbody tr').filter({ has: this.page.locator('td.id', { hasText: exactly(this.lastOrderNumber) }) });
1392
+ await assertPresence(row, notCase, {
1393
+ label: `the order "${this.lastOrderNumber}" in the order history`,
1394
+ hint: 'The history is the "My Orders" page of the account of the customer who placed the order.',
1395
+ timeout: notCase ? 3000 : budget(this),
1396
+ found: async () => `the orders "${clean(await this.page.locator('#my-orders-table tbody').innerText().catch(() => 'none'))}"`,
1397
+ });
1398
+ if (status && !notCase) {
1399
+ await assertValue(this, () => row.first().locator('td.status').innerText(), status, { label: `the status of the order "${this.lastOrderNumber}" in the order history`, hint: 'The status follows what the back office did with the order.' });
1400
+ }
1401
+ });
1402
+
1403
+ // The fields of the address form of the address book, by label.
1404
+ const ADDRESS_FIELDS = {
1405
+ 'first name': { id: 'firstname' },
1406
+ 'last name': { id: 'lastname' },
1407
+ 'company': { id: 'company' },
1408
+ 'phone number': { id: 'telephone' },
1409
+ 'street address': { id: 'street_1' },
1410
+ 'country': { id: 'country', select: true },
1411
+ 'state/province': { id: 'region_id', select: true },
1412
+ 'city': { id: 'city' },
1413
+ 'zip/postal code': { id: 'zip' },
1414
+ };
1415
+
1416
+ /**
1417
+ * Add an address to the address book of the logged-in customer from a table of
1418
+ * label and value (First Name, Last Name, Company, Phone Number, Street
1419
+ * Address, Country, State/Province, City, Zip/Postal Code; the names are
1420
+ * prefilled). The step ends on the address book: follow it with a message
1421
+ * assertion.
1422
+ *
1423
+ * Example #1: When I add the address:
1424
+ * Example #2: And I add the address:
1425
+ * Example #3: When we add the address:
1426
+ * Example #4: When add the address:
1427
+ * Example #5: And we add the address:
1428
+ *
1429
+ */
1430
+ When(/^(I |we )*add the address:$/, async function (pronounCase, table) {
1431
+ await open(this, siteUrl(this, 'customer/address/new/'));
1432
+ const form = this.page.locator('#form-validate');
1433
+ if (!(await form.locator('#street_1').count())) {
1434
+ throw friendly({ message: 'The store did not open the new address form.', hint: 'Log in as a customer first: `Given I am logged in as the customer "customer"`.' });
1435
+ }
1436
+ const rows = table.raw().map(([label, value]) => [clean(label), value]);
1437
+ rows.sort((a, b) => Number(b[0].toLowerCase() === 'country') - Number(a[0].toLowerCase() === 'country'));
1438
+ for (const [label, value] of rows) {
1439
+ const field = ADDRESS_FIELDS[label.toLowerCase()];
1440
+ if (!field) {
1441
+ throw friendly({ message: `"${label}" is not a field of the address form.`, hint: `The fields: ${Object.keys(ADDRESS_FIELDS).join(', ')}.` });
1442
+ }
1443
+ const control = form.locator('#' + field.id);
1444
+ await actOrExplain('fill in the address field', label, async () => {
1445
+ if (field.select) await control.selectOption({ label: value }, { timeout: budget(this) });
1446
+ else await control.fill(value, { timeout: budget(this) });
1447
+ }, 'Use the country and the state as the selects name them.');
1448
+ }
1449
+ await actAndSettle(this, () => form.locator('button.action.save').click({ noWaitAfter: true }));
1450
+ });
1451
+
1452
+ /**
1453
+ * Assert the address book of the customer holds (or does not hold) an address
1454
+ * with a text (a street, a city).
1455
+ *
1456
+ * Example #1: Then my address book should contain "9 Test Road"
1457
+ * Example #2: Then my address book should not contain "9 Test Road"
1458
+ * Example #3: And my address book should contain "100 Main Street"
1459
+ * Example #4: Then our address book should contain "Dallas"
1460
+ * Example #5: Then my address book should not contain "Nowhere"
1461
+ *
1462
+ */
1463
+ Then(/^(?:my|our) address book should( not)* contain "([^"]*)"$/, async function (notCase, text) {
1464
+ if (!(await this.page.locator('body.customer-address-index').count())) await open(this, siteUrl(this, 'customer/address/'));
1465
+ await settle(this);
1466
+ await assertPresence(this.page.locator('.block-addresses-default address, #additional-addresses-table tbody tr').filter({ hasText: literal(text) }), notCase, {
1467
+ label: `an address with "${text}" in the address book`,
1468
+ hint: 'The address book lists the default addresses and, in a table, the additional ones.',
1469
+ timeout: notCase ? 3000 : budget(this),
1470
+ });
1471
+ });
1472
+
1473
+ /**
1474
+ * Delete an additional address of the address book by a text of it (its
1475
+ * street) and accept the confirmation.
1476
+ *
1477
+ * Example #1: When I delete the address "9 Test Road"
1478
+ * Example #2: And I delete the address "9 Test Road"
1479
+ * Example #3: When we delete the address "12 Side Street"
1480
+ * Example #4: When delete the address "9 Test Road"
1481
+ * Example #5: And we delete the address "Dallas"
1482
+ *
1483
+ */
1484
+ When(/^(I |we )*delete the address "([^"]*)"$/, async function (pronounCase, text) {
1485
+ if (!(await this.page.locator('body.customer-address-index').count())) await open(this, siteUrl(this, 'customer/address/'));
1486
+ await settle(this);
1487
+ const row = this.page.locator('#additional-addresses-table tbody tr').filter({ hasText: literal(text) }).first();
1488
+ if (!(await row.count())) {
1489
+ throw friendly({ message: `The address book has no additional address with "${text}".`, hint: 'Only an additional address can be deleted; a default address is changed instead.' });
1490
+ }
1491
+ await row.locator('a.delete').click();
1492
+ await answerDialog(this, true);
1493
+ });
1494
+
1495
+ /**
1496
+ * Make sure the address book of the logged-in customer has no additional
1497
+ * address with a text: every match is deleted. The clean-up of an address a
1498
+ * scenario adds.
1499
+ *
1500
+ * Example #1: Given my address book has no address "9 Test Road"
1501
+ * Example #2: And my address book has no address "9 Test Road"
1502
+ * Example #3: Given our address book has no address "12 Side Street"
1503
+ * Example #4: And my address book has no address "Dallas"
1504
+ * Example #5: Given my address book has no address "Temporary"
1505
+ *
1506
+ */
1507
+ Given(/^(?:my|our) address book has no address "([^"]*)"$/, async function (text) {
1508
+ for (let pass = 0; pass < 20; pass += 1) {
1509
+ await open(this, siteUrl(this, 'customer/address/'));
1510
+ const row = this.page.locator('#additional-addresses-table tbody tr').filter({ hasText: literal(text) }).first();
1511
+ if (!(await row.count())) return;
1512
+ await row.locator('a.delete').click();
1513
+ await answerDialog(this, true);
1514
+ }
1515
+ });
1516
+
1517
+ // ---------------------------------------------------------------------------
1518
+ // Wish list and comparison list
1519
+ // ---------------------------------------------------------------------------
1520
+
1521
+ /**
1522
+ * Press "Add to Wish List" or "Add to Compare" on a product page and wait for
1523
+ * the store to answer. The wish list needs a logged-in customer and ends on the
1524
+ * wish list page; the comparison list stays on the product page.
1525
+ *
1526
+ * Example #1: When I add the product to my wish list
1527
+ * Example #2: When I add the product to the comparison list
1528
+ * Example #3: And I add the product to my wish list
1529
+ * Example #4: When we add the product to our wish list
1530
+ * Example #5: And we add the product to the comparison list
1531
+ *
1532
+ */
1533
+ When(/^(I |we )*add the product to (?:(?:my|our) (wish) list|the comparison list)$/, async function (pronounCase, wish) {
1534
+ await settle(this);
1535
+ const link = this.page.locator(wish ? '.product-info-main a.action.towishlist' : '.product-info-main a.action.tocompare').first();
1536
+ await actOrExplain('add the product to', wish ? 'the wish list' : 'the comparison list', async () => {
1537
+ await link.waitFor({ state: 'visible', timeout: budget(this) });
1538
+ await actAndSettle(this, () => link.click({ noWaitAfter: true }));
1539
+ await messages(this).first().waitFor({ state: 'visible', timeout: budget(this) });
1540
+ }, 'The links are next to "Add to Cart" on a product page. A guest who adds to the wish list is sent to the sign-in page.');
1541
+ await settle(this);
1542
+ });
1543
+
1544
+ /**
1545
+ * Assert the wish list of the customer holds (or does not hold) a product.
1546
+ *
1547
+ * Example #1: Then my wish list should contain "Joust Duffle Bag"
1548
+ * Example #2: Then my wish list should not contain "Joust Duffle Bag"
1549
+ * Example #3: And my wish list should contain "Radiant Tee"
1550
+ * Example #4: Then our wish list should contain "Aim Analog Watch"
1551
+ * Example #5: Then my wish list should not contain "Test Bag"
1552
+ *
1553
+ */
1554
+ Then(/^(?:my|our) wish list should( not)* contain "([^"]*)"$/, async function (notCase, name) {
1555
+ if (!(await this.page.locator('body.wishlist-index-index').count())) await open(this, siteUrl(this, 'wishlist/'));
1556
+ await settle(this);
1557
+ await assertPresence(this.page.locator('.products-grid.wishlist .product-item-name').filter({ hasText: exactly(name) }), notCase, {
1558
+ label: `"${name}" in the wish list`,
1559
+ hint: 'The wish list is the "My Wish List" page of the account.',
1560
+ timeout: notCase ? 3000 : budget(this),
1561
+ });
1562
+ });
1563
+
1564
+ /**
1565
+ * Remove a product from the wish list. Its "Remove item" link shows only while
1566
+ * the pointer is over the product: the step hovers it first, as a person
1567
+ * does. It does nothing when the product is not in the list, so it can open a
1568
+ * scenario as a clean-up.
1569
+ *
1570
+ * Example #1: When I remove "Joust Duffle Bag" from my wish list
1571
+ * Example #2: And I remove "Radiant Tee" from my wish list
1572
+ * Example #3: When we remove "Aim Analog Watch" from our wish list
1573
+ * Example #4: Given I remove "Joust Duffle Bag" from my wish list
1574
+ * Example #5: When remove "Radiant Tee" from my wish list
1575
+ *
1576
+ */
1577
+ When(/^(I |we )*remove "([^"]*)" from (?:my|our) wish list$/, async function (pronounCase, name) {
1578
+ await open(this, siteUrl(this, 'wishlist/'));
1579
+ for (let pass = 0; pass < 10; pass += 1) {
1580
+ const item = this.page.locator('.products-grid.wishlist .product-item').filter({ has: this.page.locator('.product-item-name', { hasText: exactly(name) }) }).first();
1581
+ if (!(await item.count())) return;
1582
+ await item.hover();
1583
+ const remove = item.locator('a[data-role="remove"]');
1584
+ await remove.waitFor({ state: 'visible', timeout: budget(this) });
1585
+ await actAndSettle(this, () => remove.click({ noWaitAfter: true }));
1586
+ }
1587
+ });
1588
+
1589
+ /**
1590
+ * Assert the comparison list holds (or does not hold) a product.
1591
+ *
1592
+ * Example #1: Then the comparison list should contain "Joust Duffle Bag"
1593
+ * Example #2: Then the comparison list should not contain "Joust Duffle Bag"
1594
+ * Example #3: And the comparison list should contain "Radiant Tee"
1595
+ * Example #4: Then the comparison list should contain "Aim Analog Watch"
1596
+ * Example #5: Then the comparison list should not contain "Test Bag"
1597
+ *
1598
+ */
1599
+ Then(/^the comparison list should( not)* contain "([^"]*)"$/, async function (notCase, name) {
1600
+ if (!(await this.page.locator('body.catalog-product_compare-index').count())) await open(this, siteUrl(this, 'catalog/product_compare/'));
1601
+ await settle(this);
1602
+ await assertPresence(this.page.locator('#product-comparison .product-item-name').filter({ hasText: exactly(name) }), notCase, {
1603
+ label: `"${name}" in the comparison list`,
1604
+ hint: 'The comparison list is the "Compare Products" page.',
1605
+ timeout: notCase ? 3000 : budget(this),
1606
+ });
1607
+ });
1608
+
1609
+ /**
1610
+ * Remove every product from the comparison list (each removal is confirmed).
1611
+ * It does nothing when the list is empty.
1612
+ *
1613
+ * Example #1: When I empty the comparison list
1614
+ * Example #2: And I empty the comparison list
1615
+ * Example #3: When we empty the comparison list
1616
+ * Example #4: Given I empty the comparison list
1617
+ * Example #5: When empty the comparison list
1618
+ *
1619
+ */
1620
+ When(/^(I |we )*empty the comparison list$/, async function (pronounCase) {
1621
+ for (let pass = 0; pass < 20; pass += 1) {
1622
+ await open(this, siteUrl(this, 'catalog/product_compare/'));
1623
+ const remove = this.page.locator('#product-comparison a.action.delete').first();
1624
+ if (!(await remove.count())) return;
1625
+ await remove.click();
1626
+ await answerDialog(this, true);
1627
+ }
1628
+ });
1629
+
1630
+ // ---------------------------------------------------------------------------
1631
+ // Reviews, newsletter
1632
+ // ---------------------------------------------------------------------------
1633
+
1634
+ /**
1635
+ * Submit a review of the product of the page: the Reviews tab is opened, the
1636
+ * stars are set, the summary and the text are filled, and the form is sent. A
1637
+ * guest gives a nickname; a customer's is prefilled. With "without a rating"
1638
+ * the stars are left empty, for the validation scenario. Follow it with a
1639
+ * message or a field error assertion.
1640
+ *
1641
+ * Example #1: When I review the product with 4 stars, the summary "Good bag" and the text "It holds everything."
1642
+ * Example #2: When I review the product with 5 stars, the summary "Great" and the text "Would buy again." as "Gail"
1643
+ * Example #3: And I review the product with 1 star, the summary "Poor" and the text "It broke."
1644
+ * Example #4: When we review the product without a rating, the summary "No stars" and the text "Forgot the stars."
1645
+ * Example #5: When I review the product with 3 stars, the summary "Fine" and the text "It is fine." as "Sam"
1646
+ *
1647
+ */
1648
+ When(/^(I |we )*review the product (?:with (\d) stars?|without a rating), the summary "([^"]*)" and the text "([^"]*)"(?: as "([^"]*)")?$/, async function (pronounCase, stars, summary, text, nickname) {
1649
+ await settle(this);
1650
+ const page = this.page;
1651
+ const form = page.locator('#review-form');
1652
+ await actOrExplain('review', 'the product', async () => {
1653
+ if (!(await form.isVisible().catch(() => false))) {
1654
+ await page.locator('#tab-label-reviews-title').click({ timeout: budget(this) });
1655
+ await settle(this);
1656
+ }
1657
+ await form.waitFor({ state: 'visible', timeout: budget(this) });
1658
+ if (stars) {
1659
+ // The star labels lie on top of each other from the same left edge (label
1660
+ // n is n stars wide): the right end of label n is the only part of it that
1661
+ // no smaller label covers.
1662
+ const label = form.locator(`#Rating_${stars}_label`);
1663
+ await label.scrollIntoViewIfNeeded();
1664
+ const box = await label.boundingBox();
1665
+ await page.mouse.click(box.x + box.width - 6, box.y + box.height / 2);
1666
+ if (!(await form.locator(`#Rating_${stars}`).isChecked())) throw new Error(`the ${stars}-star rating did not take the click`);
1667
+ }
1668
+ if (nickname) await form.locator('#nickname_field').fill(nickname);
1669
+ await form.locator('#summary_field').fill(summary);
1670
+ await form.locator('#review_field').fill(text);
1671
+ await actAndSettle(this, () => form.locator('button.submit').click({ noWaitAfter: true }));
1672
+ }, 'The review form is in the "Reviews" tab of a product page. A guest can review when the store allows it (Stores > Configuration > Catalog > Product Reviews).');
1673
+ });
1674
+
1675
+ /**
1676
+ * Subscribe an email address to the newsletter with the form of the footer.
1677
+ * Follow it with a message or a field error assertion.
1678
+ *
1679
+ * Example #1: When I subscribe "reader@example.com" to the newsletter
1680
+ * Example #2: When I subscribe "not-an-email" to the newsletter
1681
+ * Example #3: And I subscribe "customer@example.com" to the newsletter
1682
+ * Example #4: When we subscribe "reader@example.com" to the newsletter
1683
+ * Example #5: When subscribe "another.reader@example.com" to the newsletter
1684
+ *
1685
+ */
1686
+ When(/^(I |we )*subscribe "([^"]*)" to the newsletter$/, async function (pronounCase, email) {
1687
+ await settle(this);
1688
+ const form = this.page.locator('#newsletter-validate-detail');
1689
+ await actOrExplain('subscribe to the newsletter', email, async () => {
1690
+ await form.locator('#newsletter').fill(email, { timeout: budget(this) });
1691
+ await actAndSettle(this, () => form.locator('button.subscribe').click({ noWaitAfter: true }));
1692
+ }, 'The newsletter form is in the footer of every store page.');
1693
+ });
1694
+
1695
+ // ---------------------------------------------------------------------------
1696
+ // Store forms
1697
+ // ---------------------------------------------------------------------------
1698
+
1699
+ /**
1700
+ * The visible field of a store form with a label.
1701
+ *
1702
+ * @param {object} world
1703
+ * @param {string} label
1704
+ * @returns {import('playwright').Locator}
1705
+ */
1706
+ function storeField(world, label) {
1707
+ return world.page.locator('.field:visible').filter({ has: world.page.locator(':scope > label, :scope > legend, :scope > .label', { hasText: exactly(label) }) });
1708
+ }
1709
+
1710
+ /**
1711
+ * Fill a field of a store form (registration, contact, account) found by the
1712
+ * label of its visible field. The generic `I fill in "Password" with "…"` of
1713
+ * webship-js looks a field up by its label alone, and every store page also
1714
+ * holds the hidden sign-in popup with an "Email" and a "Password" of its own:
1715
+ * this step takes the field a person sees. A select takes the option text, a
1716
+ * checkbox "yes" or "no".
1717
+ *
1718
+ * Example #1: When I fill in the "First Name" store field with "Mia"
1719
+ * Example #2: When I fill in the "Password" store field with "Secret123456789!"
1720
+ * Example #3: And I fill in the "Confirm Password" store field with "Secret123456789!"
1721
+ * Example #4: When we fill in the "Email" store field with "mia@example.com"
1722
+ * Example #5: When I fill in the "What’s on your mind?" store field with "A question."
1723
+ *
1724
+ */
1725
+ When(/^(I |we )*fill in the "([^"]*)" store field with "([^"]*)"$/, async function (pronounCase, label, value) {
1726
+ await settle(this);
1727
+ const field = storeField(this, label).first();
1728
+ if (!(await field.count())) {
1729
+ const labels = await this.page.locator('main .field:visible > label, main .field:visible > .label').allInnerTexts().catch(() => []);
1730
+ throw friendly({ message: `The page has no visible "${label}" field. Its fields: ${[...new Set(labels.map(clean).filter(Boolean))].join(', ') || '(none)'}.`, hint: 'Use the label as the form shows it, without the asterisk.' });
1731
+ }
1732
+ const control = field.locator('input:not([type="hidden"]), select, textarea').first();
1733
+ const info = await control.evaluate((el) => ({ tag: el.tagName, type: (el.getAttribute('type') || '').toLowerCase() }));
1734
+ await actOrExplain('fill in the store field', label, async () => {
1735
+ if (info.tag === 'SELECT') await control.selectOption({ label: value }, { timeout: budget(this) });
1736
+ else if (info.type === 'checkbox') await control.setChecked(/^(yes|on|true|1)$/i.test(clean(value)));
1737
+ else await control.fill(value, { timeout: budget(this) });
1738
+ }, 'A select takes the text of an option.');
1739
+ });
1740
+
1741
+ /**
1742
+ * Press a button of the main content of a store page by its text ("Create an
1743
+ * Account", "Submit", "Save", "Save Address") and wait for what follows. The
1744
+ * header and the footer hold links and buttons with the same texts ("Create an
1745
+ * Account", "Sign In"): this step takes the one of the form.
1746
+ *
1747
+ * Example #1: When I press the "Create an Account" store button
1748
+ * Example #2: When I press the "Submit" store button
1749
+ * Example #3: And I press the "Save" store button
1750
+ * Example #4: When we press the "Save Address" store button
1751
+ * Example #5: When I press the "Sign In" store button
1752
+ *
1753
+ */
1754
+ When(/^(I |we )*press the "([^"]*)" store button$/, async function (pronounCase, name) {
1755
+ await settle(this);
1756
+ const button = this.page.locator('main button:visible').filter({ hasText: exactly(name) }).first();
1757
+ if (!(await button.count())) {
1758
+ const all = await this.page.locator('main button:visible').allInnerTexts().catch(() => []);
1759
+ throw friendly({ message: `The page has no "${name}" button in its main content. Its buttons: ${[...new Set(all.map(clean).filter(Boolean))].join(', ') || '(none)'}.`, hint: 'Use the text of the button as the form shows it.' });
1760
+ }
1761
+ await actAndSettle(this, () => button.click({ noWaitAfter: true }));
1762
+ });
1763
+
1764
+ // ---------------------------------------------------------------------------
1765
+ // Field errors
1766
+ // ---------------------------------------------------------------------------
1767
+
1768
+ /**
1769
+ * Assert the store shows (or does not show) a validation error under a field:
1770
+ * of a store form (sign-in, registration, contact, review, newsletter, the
1771
+ * product options) or of the checkout. With `for "…"` the error must belong to
1772
+ * the field with that label.
1773
+ *
1774
+ * Example #1: Then I should see the field error "This is a required field."
1775
+ * Example #2: Then I should see the field error "This is a required field." for "First Name"
1776
+ * Example #3: And I should not see the field error "This is a required field." for "Email"
1777
+ * Example #4: Then we should see the field error "Please enter a valid email address (Ex: johndoe@domain.com)."
1778
+ * Example #5: Then I should see the field error "Please select one of each of the ratings above."
1779
+ *
1780
+ */
1781
+ Then(/^(I |we )*should( not)* see the field error "([^"]*)"(?: for "([^"]*)")?$/, async function (pronounCase, notCase, text, label) {
1782
+ await settle(this);
1783
+ const page = this.page;
1784
+ let errors = page.locator('div.mage-error:visible, .field-error:visible');
1785
+ if (label) {
1786
+ errors = storeField(this, label).locator('div.mage-error, .field-error');
1787
+ }
1788
+ await assertPresence(errors.filter({ hasText: literal(text) }), notCase, {
1789
+ label: `the field error "${text}"` + (label ? ` for "${label}"` : ''),
1790
+ hint: 'A store form validates when it is submitted; the error shows under its field.',
1791
+ timeout: notCase ? 3000 : budget(this),
1792
+ found: async () => {
1793
+ const all = await page.locator('div.mage-error:visible, .field-error:visible').allInnerTexts().catch(() => []);
1794
+ return all.length ? `the errors ${[...new Set(all.map(clean))].map((error) => `"${error}"`).join(', ')}` : 'no field error';
1795
+ },
1796
+ });
1797
+ });