/* * Copyright (c) 2025, Salesforce, Inc. * All rights reserved. * SPDX-License-Identifier: BSD-3-Clause * For full license text, see the LICENSE file in the repo root or https://opensource.org/licenses/BSD-3-Clause */ const {expect} = require('@playwright/test') const config = require('../config') const {getCreditCardExpiry, runAccessibilityTest} = require('../scripts/utils.js') const CHECKOUT_TRANSITION_TIMEOUT = 30000 const CHECKOUT_POLL_INTERVAL = 100 const waitForPaymentOrReadyButton = async (page, paymentHeading, continueToPayment) => { const deadline = Date.now() + CHECKOUT_TRANSITION_TIMEOUT while (Date.now() < deadline) { if (await paymentHeading.isVisible()) return 'payment' if ((await continueToPayment.isVisible()) && (await continueToPayment.isEnabled())) { return 'button' } await page.waitForTimeout(CHECKOUT_POLL_INTERVAL) } throw new Error('Timed out waiting for Payment or a ready Continue to Payment button') } export const advanceToPayment = async (page) => { const paymentHeading = page.getByRole('heading', {name: /Payment/i}) if (await paymentHeading.isVisible()) return const shippingForm = page.getByTestId('sf-checkout-shipping-options-form') const continueToPayment = shippingForm.getByRole('button', { name: /Continue to Payment/i }) const transition = await waitForPaymentOrReadyButton(page, paymentHeading, continueToPayment) if (transition === 'payment') return // Checkout may auto-submit shipping after the button becomes ready. if (await paymentHeading.isVisible()) return // Locator.click re-resolves after React renders and waits for the button to // be stable, enabled, and able to receive pointer events. try { await continueToPayment.click() } catch (error) { // The button can disappear after winning the transition wait when the // checkout auto-submits. Preserve genuine click failures. if (await paymentHeading.isVisible()) return throw error } await paymentHeading.waitFor({state: 'visible'}) } /** * Note: As a best practice, we should await the network call and assert on the network response rather than waiting for pageLoadState() * to avoid race conditions from lock in pageLoadState being released before network call resolves. * * This is a best practice for tests that are dependent on the network call. Eg.: Shopper login, registration, etc. */ /** * Give an answer to the consent tracking form. * * Note: the consent tracking form hovers over some elements in the app. This can cause a test to fail. * Run this function after a page.goto to release the form from view. * * @param {Object} page - Object that represents a tab/window in the browser provided by playwright * @param {Boolean} dnt - Do Not Track value to answer the form. False to enable tracking, True to disable tracking. */ export const answerConsentTrackingForm = async (page, dnt = false) => { const consentForm = page.locator('text=Tracking Consent') // Probe for the form: if it doesn't appear, assume the preference is // already set and return. With httpOnly cookies, auth initialization // can be slow so we allow up to 10s for it to render. try { await consentForm.waitFor({state: 'visible', timeout: 10000}) } catch { return } // The consent modal can render before the initial guest session finishes. Clicking it during // that window races setDnt() against the in-flight login: the modal closes immediately, but // the older token can win with a different dnt claim and make the modal reappear on the next // navigation. Wait until either the public-client access token or the HttpOnly companion DNT // cookie proves that auth initialization is complete. await page.waitForFunction( () => { const hasAccessToken = Object.keys(localStorage).some( (name) => name === 'access_token' || name.startsWith('access_token_') ) const hasAccessTokenDntCookie = document.cookie .split(';') .map((cookie) => cookie.trim().split('=')[0]) .some((name) => name === 'cc-at-dnt' || name.startsWith('cc-at-dnt_')) return hasAccessToken || hasAccessTokenDntCookie }, undefined, {timeout: 15000} ) const ariaLabel = dnt ? 'Decline tracking' : 'Accept tracking' const button = page.locator(`button[aria-label="${ariaLabel}"]`).and(page.locator(':visible')) // The consent modal is rendered into a chakra-portal anchored to the // bottom of the viewport. While it is visible, its inner Stack of // buttons intercepts pointer events on any element that overlaps it // (e.g. Sign In, Add Bundle to Cart). If the first dismissal click // doesn't make the modal disappear within 5s, retry once before giving // up — this is more robust than a single click + long wait, and avoids // the misleading 60s waitForResponse timeouts we see when a stale modal // intercepts a later click in the test. let dismissed = false for (let attempt = 0; attempt < 2; attempt++) { try { await button.first().click() await consentForm.waitFor({state: 'hidden', timeout: 5000}) dismissed = true break } catch { // fall through and retry } } if (!dismissed) return // onClose() runs before updateDnt() completes, so hidden is only a visual state. Wait // for both the selected cookie and the token claim to reach the requested value before // navigating. This covers public clients (JWT in localStorage) and private/HttpOnly // clients (the cc-at-dnt companion cookie). Keep this outside the dismissal retry so a // synchronization timeout is reported instead of causing another click on a hidden button. await page.waitForFunction( (expectedDnt) => { const cookies = Object.fromEntries( document.cookie.split(';').map((cookie) => { const [name, ...value] = cookie.trim().split('=') return [name, value.join('=')] }) ) const selectedDnt = cookies.dw_dnt const accessTokenDntCookie = Object.entries(cookies).find( ([name]) => name === 'cc-at-dnt' || name.startsWith('cc-at-dnt_') )?.[1] let accessTokenDnt const accessTokenKey = Object.keys(localStorage).find( (name) => name === 'access_token' || name.startsWith('access_token_') ) const accessToken = accessTokenKey ? localStorage.getItem(accessTokenKey) : null if (accessToken) { try { const payload = accessToken.split('.')[1] const base64 = payload.replace(/-/g, '+').replace(/_/g, '/') accessTokenDnt = String(JSON.parse(atob(base64)).dnt) } catch { return false } } return ( selectedDnt === expectedDnt && (accessTokenDnt === expectedDnt || accessTokenDntCookie === expectedDnt) ) }, dnt ? '1' : '0', {timeout: 15000} ) } /** * Navigates to the `Cotton Turtleneck Sweater` PDP (Product Detail Page) on mobile * with the black variant selected * * @param {Object} options.page - Object that represents a tab/window in the browser provided by playwright */ export const navigateToPDPMobile = async ({page}) => { // Home page await page.goto(config.RETAIL_APP_HOME) await answerConsentTrackingForm(page) await page.getByLabel('Menu', {exact: true}).click() // SSR nav loads top level categories as direct links so we wait till all sub-categories load in the accordion const categoryAccordion = page.locator( "#category-nav .chakra-accordion__button svg+:text('Womens')" ) await categoryAccordion.waitFor() await page.getByRole('button', {name: 'Womens'}).click() const clothingNav = page.getByRole('button', {name: 'Clothing'}) await clothingNav.waitFor() await clothingNav.click() const topsLink = page.getByLabel('Womens').getByRole('link', {name: 'Tops'}) await topsLink.click() // Wait for the nav menu to close first await topsLink.waitFor({state: 'hidden'}) await expect(page.getByRole('heading', {name: 'Tops'})).toBeVisible() // PLP const productTile = page.getByRole('link', { name: /Cotton Turtleneck Sweater/i }) await productTile.scrollIntoViewIfNeeded() // selecting swatch const productTileImg = productTile.locator('img') await productTileImg.waitFor({state: 'visible'}) const initialSrc = await productTileImg.getAttribute('src') await expect(productTile.getByText(/From \$39\.99/i)).toBeVisible() await productTile.getByLabel(/Black/, {exact: true}).click() // Make sure the image src has changed await expect(async () => { const newSrc = await productTileImg.getAttribute('src') expect(newSrc).not.toBe(initialSrc) }).toPass() await expect(productTile.getByText(/From \$39\.99/i)).toBeVisible() await productTile.click() } /** * Navigates to the `Cotton Turtleneck Sweater` PDP (Product Detail Page) on Desktop * with the black variant selected. * * @param {Object} options.page - Object that represents a tab/window in the browser provided by playwright */ export const navigateToPDPDesktop = async ({page}) => { await page.goto(config.RETAIL_APP_HOME) await answerConsentTrackingForm(page) await page.getByRole('link', {name: 'Womens'}).hover() const topsNav = await page.getByRole('link', {name: 'Tops', exact: true}) await expect(topsNav).toBeVisible() await topsNav.click() // PLP const productTile = page.getByRole('link', { name: /Cotton Turtleneck Sweater/i }) // selecting swatch const productTileImg = productTile.locator('img') await productTileImg.waitFor({state: 'visible'}) const initialSrc = await productTileImg.getAttribute('src') await expect(productTile.getByText(/From \$39\.99/i)).toBeVisible() await productTile.getByLabel(/Black/, {exact: true}).hover() // Make sure the image src has changed await expect(async () => { const newSrc = await productTileImg.getAttribute('src') expect(newSrc).not.toBe(initialSrc) }).toPass() await expect(productTile.getByText(/From \$39\.99/i)).toBeVisible() await productTile.click() } /** * Navigates to the `Cotton Turtleneck Sweater` PDP (Product Detail Page) on Desktop * with the black variant selected. * * @param {Object} options.page - Object that represents a tab/window in the browser provided by playwright */ export const navigateToPDPDesktopSocial = async ({ page, productName, productColor, productPrice }) => { await page.goto(config.EXTRA_FEATURES_E2E_RETAIL_APP_HOME) await answerConsentTrackingForm(page) await page.getByRole('link', {name: 'Womens'}).hover() const topsNav = await page.getByRole('link', {name: 'Tops', exact: true}) await expect(topsNav).toBeVisible() await topsNav.click() // PLP const productTile = page.getByRole('link', { name: RegExp(productName, 'i') }) // selecting swatch const productTileImg = productTile.locator('img') await productTileImg.waitFor({state: 'visible'}) await expect(productTile.getByText(RegExp(`From \\${productPrice}`, 'i'))).toBeVisible() await productTile.getByLabel(RegExp(productColor, 'i'), {exact: true}).hover() await productTile.click() } /** * Adds the `Cotton Turtleneck Sweater` product to the cart with the variant: * Color: Black * Size: L * * @param {Object} options.page - Object that represents a tab/window in the browser provided by playwright * @param {Boolean} options.isMobile - Flag to indicate if device type is mobile or not, defaulted to false */ export const addProductToCart = async ({page, isMobile = false}) => { // Navigate to Cotton Turtleneck Sweater with Black color variant selected if (isMobile) { await navigateToPDPMobile({page}) } else { await navigateToPDPDesktop({page}) } // PDP await expect(page.getByRole('heading', {name: /Cotton Turtleneck Sweater/i})).toBeVisible() await page.getByRole('radio', {name: 'L', exact: true}).click() await page.locator("button[data-testid='quantity-increment']").click() // Selected Size and Color texts are broken into multiple elements on the page. // So we need to look at the page URL to verify selected variants const updatedPageURL = await page.url() const params = updatedPageURL.split('?')[1] expect(params).toMatch(/size=9LG/i) expect(params).toMatch(/color=JJ169XX/i) await page.getByRole('button', {name: /Add to Cart/i}).click() const addedToCartModal = page.getByText(/2 items added to cart/i) await addedToCartModal.waitFor() await page.getByLabel('Close', {exact: true}).click() } /** * Registers a shopper with provided user credentials * * @param {Object} options.page - Object that represents a tab/window in the browser provided by playwright * @param {Object} options.userCredentials - Object containing user credentials with the following properties: * - firstName * - lastName * - email * - password * @param {Boolean} options.isMobile - flag to indicate if device type is mobile or not, defaulted to false */ export const registerShopper = async ({page, userCredentials}) => { // Create Account and Sign In await page.goto(config.RETAIL_APP_HOME + '/registration') await answerConsentTrackingForm(page) await page.waitForLoadState() // Skip registration if user is already logged in const initialUrl = page.url() if (initialUrl.includes('/account')) { return } const registrationFormHeading = page.getByText(/Let's get started!/i) try { await registrationFormHeading.waitFor({timeout: 10000}) } catch (error) { // Check if user was redirected to account page during wait const urlAfterWait = page.url() if (urlAfterWait.includes('/account')) { return } throw new Error(`Registration form not found. Current URL: ${urlAfterWait}`) } await page.locator('input#firstName').fill(userCredentials.firstName) await page.locator('input#lastName').fill(userCredentials.lastName) await page.locator('input#email').fill(userCredentials.email) await page.locator('input#password').fill(userCredentials.password) // Best Practice: await the network call and assert on the network response rather than waiting for pageLoadState() // to avoid race conditions from lock in pageLoadState being released before network call resolves const tokenResponsePromise = page.waitForResponse( '**/shopper/auth/v1/organizations/**/oauth2/token' ) await page.getByRole('button', {name: /Create Account/i}).click() const tokenResponse = await tokenResponsePromise expect(tokenResponse.status()).toBe(200) await page.waitForURL(/.*\/account.*/, {timeout: 10000}) await expect(page.getByText(userCredentials.email)).toBeVisible() } /** * Validates that the `Cotton Turtleneck Sweater` product appears in the Order History page * * @param {Object} options.page - Object that represents a tab/window in the browser provided by playwright */ export const validateOrderHistory = async ({page, a11y = {}}) => { const {checkA11y = false, snapShotName} = a11y await page.goto(config.RETAIL_APP_HOME + '/account/orders') await answerConsentTrackingForm(page) await expect(page.getByRole('heading', {name: /Order History/i})).toBeVisible() await page.getByRole('link', {name: 'View details'}).click() await expect(page.getByRole('heading', {name: /Order Details/i})).toBeVisible() await expect(page.getByRole('heading', {name: /Cotton Turtleneck Sweater/i})).toBeVisible() await expect(page.getByText(/Color: Black/i)).toBeVisible() await expect(page.getByText(/Size: L/i)).toBeVisible() if (checkA11y) { await runAccessibilityTest(page, [snapShotName, 'order-history-a11y-violations.json']) } } /** * Validates that the `Cotton Turtleneck Sweater` product appears in the Wishlist page * * @param {Object} options.page - Object that represents a tab/window in the browser provided by playwright */ export const validateWishlist = async ({page, a11y = {}}) => { const {checkA11y = false, snapShotName} = a11y await page.goto(config.RETAIL_APP_HOME + '/account/wishlist') await answerConsentTrackingForm(page) await expect(page.getByRole('heading', {name: /Wishlist/i})).toBeVisible() await expect(page.getByRole('heading', {name: /Cotton Turtleneck Sweater/i})).toBeVisible() await expect(page.getByText(/Color: Black/i)).toBeVisible() await expect(page.getByText(/Size: L/i)).toBeVisible() if (checkA11y) { await runAccessibilityTest(page, [snapShotName, 'wishlist-violations.json']) } } /** * Attempts to log in a shopper with provided user credentials. * * @param {Object} options.page - Object that represents a tab/window in the browser provided by playwright * @param {Object} options.userCredentials - Object containing user credentials with the following properties: * - firstName * - lastName * - email * - password * * @return {Boolean} - denotes whether or not login was successful */ export const loginShopper = async ({page, userCredentials}) => { let loginResponse let tokenResponse try { await page.goto(config.RETAIL_APP_HOME + '/login') await answerConsentTrackingForm(page) await page.locator('input#email').fill(userCredentials.email) await page.locator('input#password').fill(userCredentials.password) // The DNT consent modal is portaled to the bottom of the viewport. // If it is still visible when we click Sign In, its container // intercepts the click — the form never submits and waitForResponse // below times out at 60s with a misleading message. Make the failure // explicit instead. await expect(page.locator('text=Tracking Consent')).toBeHidden({timeout: 10000}) const loginResponsePromise = page.waitForResponse( '**/shopper/auth/v1/organizations/**/oauth2/login' ) const tokenResponsePromise = page.waitForResponse( '**/shopper/auth/v1/organizations/**/oauth2/token' ) await page.getByRole('button', {name: /Sign In/i}).click() loginResponse = await loginResponsePromise expect(loginResponse.status()).toBe(303) // Login returns a 303 redirect to /callback with authCode and usid tokenResponse = await tokenResponsePromise expect(tokenResponse.status()).toBe(200) await page.waitForURL(/.*\/account.*/, {timeout: 10000}) await expect(page.getByText(userCredentials.email)).toBeVisible() return true } catch (error) { const lastResponse = tokenResponse || loginResponse const responseContext = lastResponse ? ` (last SLAS response: ${lastResponse.status()} ${lastResponse.url()})` : '' console.error(`[e2e] loginShopper failed${responseContext}:`, error.message) return false } } /** * Attempts to log in a shopper with provided user credentials. * * @param {Object} options.page - Object that represents a tab/window in the browser provided by playwright * @return {Boolean} - denotes whether or not login was successful */ export const socialLoginShopper = async ({page}) => { try { await page.goto(config.EXTRA_FEATURES_E2E_RETAIL_APP_HOME + '/login') await page.getByText(/Google/i).click() await expect(page.getByText(/Sign in with Google/i)).toBeVisible({timeout: 10000}) await page.waitForSelector('input[type="email"]') // Fill in the email input await page.fill('input[type="email"]', config.PWA_E2E_USER_EMAIL) await page.click('#identifierNext') await page.waitForSelector('input[type="password"]') // Fill in the password input await page.fill('input[type="password"]', config.PWA_E2E_USER_PASSWORD) await page.click('#passwordNext') await page.waitForLoadState() await expect(page.getByRole('heading', {name: /Account Details/i})).toBeVisible({ timeout: 20000 }) await expect(page.getByText(/e2e.pwa.kit@gmail.com/i)).toBeVisible() // Password card should be hidden for social login user await expect(page.getByRole('heading', {name: /Password/i})).toBeHidden() return true } catch { return false } } /** * Search for products by query string that takes you to the PLP * * @param {Object} options.page - Object that represents a tab/window in the browser provided by playwright * @param {String} options.query - Product name other product related descriptors to search for * @param {Object} options.isMobile - Flag to indicate if device type is mobile or not, defaulted to false */ export const searchProduct = async ({page, query, isMobile = false}) => { await page.goto(config.RETAIL_APP_HOME) await answerConsentTrackingForm(page) // For accessibility reasons, we have two search bars // one for desktop and one for mobile depending on your device type const searchInputs = page.locator('input[aria-label="Search for products..."]') let searchInput = isMobile ? searchInputs.nth(1) : searchInputs.nth(0) await searchInput.fill(query) await page.waitForTimeout(1000) await searchInput.press('Enter') await page.waitForLoadState() } /** * Checkout products that are in the cart * * @param {Object} options.page - Object that represents a tab/window in the browser provided by playwright * @param {Object} options.userCredentials - Object containing user credentials with the following properties: * - firstName * - lastName * - email * - password */ export const checkoutProduct = async ({page, userCredentials, a11y = {checkA11y: false}}) => { const {checkA11y, snapShotName} = a11y await page.getByRole('link', {name: 'Proceed to Checkout'}).click() await expect(page.getByRole('heading', {name: /Contact Info/i})).toBeVisible() await page.locator('input#email').fill('test@gmail.com') if (checkA11y) { await runAccessibilityTest(page, [snapShotName, 'checkout-a11y-violations-step-0.json']) } await page.getByRole('button', {name: /Checkout as guest/i}).click() // Confirm the email input toggles to show edit button on clicking "Checkout as guest" const step0Card = page.locator("div[data-testid='sf-toggle-card-step-0']") await expect(step0Card.getByRole('button', {name: /Edit/i})).toBeVisible() await expect(page.getByRole('heading', {name: /Shipping Address/i})).toBeVisible() await page.locator('input#firstName').fill(userCredentials.firstName) await page.locator('input#lastName').fill(userCredentials.lastName) await page.locator('input#phone').fill(userCredentials.phone) await page.locator('input#address1').fill(userCredentials.address.street) await page.locator('input#city').fill(userCredentials.address.city) await page.locator('select#stateCode').selectOption(userCredentials.address.state) await page.locator('input#postalCode').fill(userCredentials.address.zipcode) if (checkA11y) { await runAccessibilityTest(page, [snapShotName, 'checkout-a11y-violations-step-1.json']) } await page.getByRole('button', {name: /Continue to Shipping Method/i}).click() // Confirm the shipping details form toggles to show edit button on clicking "Checkout as guest" const step1Card = page.locator("div[data-testid='sf-toggle-card-step-1']") await expect(step1Card.getByRole('button', {name: /Edit/i})).toBeVisible() await expect(page.getByRole('heading', {name: /Shipping & Gift Options/i})).toBeVisible() if (checkA11y) { await runAccessibilityTest(page, [snapShotName, 'checkout-a11y-violations-step-2.json']) } await advanceToPayment(page) await expect(page.getByRole('heading', {name: /Payment/i})).toBeVisible() const creditCardExpiry = getCreditCardExpiry() await page.locator('input#number').fill('4111111111111111') await page.locator('input#holder').fill('John Doe') await page.locator('input#expiry').fill(creditCardExpiry) await page.locator('input#securityCode').fill('213') if (checkA11y) { await runAccessibilityTest(page, [snapShotName, 'checkout-a11y-violations-step-3.json']) } await page.getByRole('button', {name: /Review Order/i}).click() page.getByRole('button', {name: /Place Order/i}) .first() .click() // order confirmation const orderConfirmationHeading = page.getByRole('heading', { name: /Thank you for your order!/i }) if (checkA11y) { await runAccessibilityTest(page, [ snapShotName, 'checkout-a11y-violations-step-4-order-confirmation.json' ]) } await orderConfirmationHeading.waitFor() } export const registeredUserHappyPath = async ({page, registeredUserCredentials, a11y = {}}) => { const {checkA11y = false, snapShotName} = a11y // Since we're re-using the same account, we need to check if the user is already registered. // This ensures the tests are independent and not dependent on the order they are run in. const isLoggedIn = await loginShopper({ page, userCredentials: registeredUserCredentials }) if (!isLoggedIn) { await registerShopper({ page, userCredentials: registeredUserCredentials }) } await answerConsentTrackingForm(page) await page.waitForLoadState() // Verify we're on account page and user is logged in const currentUrl = page.url() expect(currentUrl).toMatch(/\/account/) await expect(page.getByText(registeredUserCredentials.email)).toBeVisible() // Shop for items as registered user await addProductToCart({page}) // cart await page.getByLabel(/My cart/i).click() await expect(page.getByRole('link', {name: /Cotton Turtleneck Sweater/i})).toBeVisible() await page.getByRole('link', {name: 'Proceed to Checkout'}).click() // Confirm the email input toggles to show sign out button on clicking "Checkout as guest" const step0Card = page.locator("div[data-testid='sf-toggle-card-step-0']") await expect(step0Card.getByRole('button', {name: /Sign Out/i})).toBeVisible() if (checkA11y) { await runAccessibilityTest(page, [snapShotName, 'checkout-a11y-violations-step-0.json']) } await expect(page.getByRole('heading', {name: /Shipping Address/i})).toBeVisible() await page.locator('input#firstName').fill(registeredUserCredentials.firstName) await page.locator('input#lastName').fill(registeredUserCredentials.lastName) await page.locator('input#phone').fill(registeredUserCredentials.phone) await page.locator('input#address1').fill(registeredUserCredentials.address.street) await page.locator('input#city').fill(registeredUserCredentials.address.city) await page.locator('select#stateCode').selectOption(registeredUserCredentials.address.state) await page.locator('input#postalCode').fill(registeredUserCredentials.address.zipcode) if (checkA11y) { await runAccessibilityTest(page, [snapShotName, 'checkout-a11y-violations-step-1.json']) } await page.getByRole('button', {name: /Continue to Shipping Method/i}).click() // Confirm the shipping details form toggles to show edit button on clicking "Checkout as guest" const step1Card = page.locator("div[data-testid='sf-toggle-card-step-1']") await expect(step1Card.getByRole('button', {name: /Edit Shipping Address/i})).toBeVisible() await expect(page.getByRole('heading', {name: /Shipping & Gift Options/i})).toBeVisible() await page.waitForLoadState() if (checkA11y) { await runAccessibilityTest(page, [snapShotName, 'checkout-a11y-violations-step-2.json']) } await advanceToPayment(page) const step2Card = page.locator("div[data-testid='sf-toggle-card-step-2']") // After advancing to Payment, step 2 collapses to its summary with an Edit button. // A transient basket refetch can briefly disable the card (hiding the edit button), // so allow the same checkout-transition window the rest of this file uses instead of // the default 5s assertion timeout. await expect(step2Card.getByRole('button', {name: /Edit Shipping Options/i})).toBeVisible({ timeout: CHECKOUT_TRANSITION_TIMEOUT }) await expect(page.getByRole('heading', {name: /Payment/i})).toBeVisible() const creditCardExpiry = getCreditCardExpiry() await page.locator('input#number').fill('4111111111111111') await page.locator('input#holder').fill('John Doe') await page.locator('input#expiry').fill(creditCardExpiry) await page.locator('input#securityCode').fill('213') if (checkA11y) { await runAccessibilityTest(page, [snapShotName, 'checkout-a11y-violations-step-3.json']) } await page.getByRole('button', {name: /Review Order/i}).click() const step3Card = page.locator("div[data-testid='sf-toggle-card-step-3']") await expect(step3Card.getByRole('button', {name: /Edit Payment Info/i})).toBeVisible() page.getByRole('button', {name: /Place Order/i}) .first() .click() const orderConfirmationHeading = page.getByRole('heading', { name: /Thank you for your order!/i }) await orderConfirmationHeading.waitFor() await expect(page.getByRole('heading', {name: /Order Summary/i})).toBeVisible() await expect(page.getByText(/2 Items/i)).toBeVisible() await expect(page.getByRole('link', {name: /Cotton Turtleneck Sweater/i})).toBeVisible() if (checkA11y) { await runAccessibilityTest(page, [ 'registered', 'checkout-a11y-violations-step-4-order-confirmation.json' ]) } // order history await validateOrderHistory({page, a11y}) } /** * Executes the wishlist flow for a registered user. * * Includes robust authentication handling with fallback mechanisms. * * @param {Object} options.page - Playwright page object representing a browser tab/window * @param {Object} options.registeredUserCredentials - User credentials for authentication * @param {Object} options.a11y - Accessibility testing configuration (optional) */ export const wishlistFlow = async ({page, registeredUserCredentials, a11y = {}}) => { const isLoggedIn = await loginShopper({ page, userCredentials: registeredUserCredentials }) if (!isLoggedIn) { try { await registerShopper({ page, userCredentials: registeredUserCredentials }) } catch (error) { // If registration fails attempt to log in const secondLoginAttempt = await loginShopper({ page, userCredentials: registeredUserCredentials }) if (!secondLoginAttempt) { throw new Error('Authentication failed: Both login and registration unsuccessful') } } } // The consent form does not stick after registration await answerConsentTrackingForm(page) await page.waitForLoadState() const currentUrl = page.url() if (!currentUrl.includes('/account')) { await page.goto(config.RETAIL_APP_HOME + '/account') await page.waitForLoadState() } // Navigate to PDP await navigateToPDPDesktop({page}) // add product to wishlist await expect(page.getByRole('heading', {name: /Cotton Turtleneck Sweater/i})).toBeVisible() await page.getByRole('radio', {name: 'L', exact: true}).click() await page.getByRole('button', {name: /Add to Wishlist/i}).click() // wishlist await validateWishlist({page, a11y}) } /** * Navigates to a PLP and opens the store inventory filter to select a store. * * This helper function demonstrates the store inventory filtering functionality by: * 1. Navigating to the Womens > Tops category PLP * 2. Opening the store locator modal * 3. Searching for stores by postal code * 4. Returning the available store selection options * * This is useful for testing store inventory features and BOPIS (Buy Online, Pick Up In Store) functionality. * * @param {Object} options.page - Playwright page object representing a browser tab/window */ export const selectStoreFromPLP = async ({page}) => { // Navigate to a product category (Womens > Tops) await page.getByRole('link', {name: 'Womens'}).hover() const topsNav = await page.getByRole('link', {name: 'Tops', exact: true}) await expect(topsNav).toBeVisible() await topsNav.click() // Verify we're on the PLP await expect(page.getByRole('heading', {name: 'Tops'})).toBeVisible() const productTile = page.getByRole('link', { name: /Cotton Turtleneck Sweater/i }) const productTileImg = productTile.locator('img') await productTileImg.waitFor({state: 'visible'}) // Look for the store inventory filter component const storeInventoryFilter = page.getByTestId('sf-store-inventory-filter') await expect(storeInventoryFilter).toBeVisible() // Verify the filter shows "Select Store" initially await expect(page.getByText('Select Store')).toBeVisible() await expect(page.getByText('Shop by Availability')).toBeVisible() // Click on the store inventory filter checkbox to open store locator const inventoryCheckbox = page.getByTestId('sf-store-inventory-filter-checkbox') await inventoryCheckbox.click() // Verify store locator modal opens and select a store await expect(page.getByText('Find a Store')).toBeVisible() await page.locator('select[name="countryCode"]').selectOption({label: 'United States'}) await page.locator('input[name="postalCode"]').fill('01803') const searchStoreButton = page.getByRole('button', {name: 'Find'}) await expect(searchStoreButton).toBeVisible() const storeSearchResponsePromise = page.waitForResponse( (resp) => resp.url().includes('/shopper-stores/v1/organizations/') && resp.url().includes('/store-search') ) await searchStoreButton.click() const storeSearchResponse = await storeSearchResponsePromise expect(storeSearchResponse.status()).toBe(200) // Select the first available store (if any stores are available) await expect(page.getByText(/Burlington Retail Store/i)).toBeVisible() // Find and click the first available store label const storeRadioLabels = page.locator( 'label.chakra-radio:has(input[aria-describedby^="store-info-"])' ) const storeCount = await storeRadioLabels.count() if (storeCount > 0) { // Select the first store await storeRadioLabels.first().click() // Close the store locator modal await page.locator('button[aria-label="Close"]').click() await page.waitForLoadState() await expect(page.getByText('Find a Store')).not.toBeVisible() } else { // If no stores are available, verify the appropriate message is shown await expect(page.getByText('Sorry, there are no locations in this area.')).toBeVisible() // Close the modal await page.getByRole('button', {name: 'Close'}).click() } } /** * Tests that a master product in the wishlist can be added to cart via the "View Options" modal. * * Flow: * 1. Log in or register a shopper * 2. Navigate to PDP and add a product to wishlist without selecting all variants (master product) * 3. Go to wishlist page * 4. Click "View Options" to open the product modal * 5. Select variant attributes in the modal * 6. Click "Add to Cart" * 7. Verify the item was added successfully */ export const wishlistMasterProductAddToCartFlow = async ({page, registeredUserCredentials}) => { const isLoggedIn = await loginShopper({ page, userCredentials: registeredUserCredentials }) if (!isLoggedIn) { try { await registerShopper({ page, userCredentials: registeredUserCredentials }) } catch (error) { const secondLoginAttempt = await loginShopper({ page, userCredentials: registeredUserCredentials }) if (!secondLoginAttempt) { throw new Error('Authentication failed: Both login and registration unsuccessful') } } } await answerConsentTrackingForm(page) await page.waitForLoadState() // Navigate to PDP without selecting all variants so the master product is added to wishlist await navigateToPDPDesktop({page}) await expect(page.getByRole('heading', {name: /Cotton Turtleneck Sweater/i})).toBeVisible() // Do NOT select a size — this ensures the master product ID is used for the wishlist item await page.getByRole('button', {name: /Add to Wishlist/i}).click() await expect(page.getByText(/1 item added to wishlist/i)).toBeVisible() // Navigate to wishlist page await page.goto(config.RETAIL_APP_HOME + '/account/wishlist') await answerConsentTrackingForm(page) await expect(page.getByRole('heading', {name: /Wishlist/i})).toBeVisible() // Master product should show "View Options" button instead of "Add to Cart" const viewOptionsButton = page.getByRole('button', {name: /View Options/i}) await expect(viewOptionsButton).toBeVisible() await viewOptionsButton.click() // Wait for the product view modal to appear const modal = page.getByTestId('product-view-modal') await expect(modal).toBeVisible({timeout: 10000}) // Select variant attributes in the modal await modal.getByRole('radio', {name: 'L', exact: true}).click() // Click "Add to Cart" in the modal const addToCartButton = modal.getByRole('button', {name: /Add to Cart/i}) await expect(addToCartButton).toBeEnabled({timeout: 5000}) await addToCartButton.click() // Verify item was added to cart successfully (no API error) await expect(page.getByText(/1 item added to cart/i)).toBeVisible({timeout: 10000}) }