|
| 1 | +import assert from "node:assert/strict"; |
| 2 | +import test from "node:test"; |
| 3 | +import { fileURLToPath } from "node:url"; |
| 4 | +import { chromium, expect } from "@playwright/test"; |
| 5 | +import { build } from "esbuild"; |
| 6 | + |
| 7 | +const root = fileURLToPath(new URL("../", import.meta.url)); |
| 8 | +// Exercise the real form, store and Router lifecycle, including a slow loader |
| 9 | +// after the action completes. Only translations and the server are fixtures. |
| 10 | +const bundle = await build({ |
| 11 | + stdin: { |
| 12 | + resolveDir: root, |
| 13 | + loader: "tsx", |
| 14 | + contents: ` |
| 15 | + import React, {useLayoutEffect} from 'react'; |
| 16 | + import {createRoot} from 'react-dom/client'; |
| 17 | + import {createMemoryRouter,RouterProvider,useLoaderData} from 'react-router'; |
| 18 | + import {CartForm} from '@shopify/hydrogen'; |
| 19 | + import {useProductQuantity} from './app/hooks/use-product-quantity'; |
| 20 | + import {AddToCartButton} from './app/components/product/add-to-cart-button'; |
| 21 | + import {CartStoreSync} from './app/components/cart/cart-sync'; |
| 22 | + import {useCart,useCartStore} from './app/components/cart/store'; |
| 23 | + import {buildOptimisticAddCart} from './app/components/cart/optimistic-cart'; |
| 24 | + const variant={id:'gid://shopify/ProductVariant/7',availableForSale:true,quantityAvailable:7,price:{amount:'10',currencyCode:'USD'},product:{id:'product-1',handle:'chair',title:'Chair'},selectedOptions:[]}; |
| 25 | + const input=quantity=>({merchandiseId:variant.id,selectedVariant:variant,quantity}); |
| 26 | + function makeCart(quantity,sequence) { |
| 27 | + const cart=buildOptimisticAddCart([input(quantity)]); |
| 28 | + return {...cart,id:'cart-1',updatedAt:new Date(Date.UTC(2026,10,16,0,0,sequence)).toISOString(),isOptimistic:false,lines:{...cart.lines,nodes:cart.lines.nodes.map(line=>({...line,id:'line-1',isOptimistic:false}))}}; |
| 29 | + } |
| 30 | + function Fixture({quantity:requested}) { |
| 31 | + const {quantity,setQuantity}=useProductQuantity(variant); |
| 32 | + const {cart:initialCart}=useLoaderData(); |
| 33 | + const cart=useCart(); |
| 34 | + const total=cart?.totalQuantity ?? 0; |
| 35 | + const lineQuantity=cart?.lines.nodes[0]?.quantity ?? 0; |
| 36 | + useLayoutEffect(()=>{window.quantities.push({total,lineQuantity});},[total,lineQuantity]); |
| 37 | + return <><CartStoreSync initialCart={initialCart}/><button onClick={()=>setQuantity(requested)}>Select quantity</button><output data-test='cart-quantity'>{lineQuantity}</output><AddToCartButton data-test='add' cartOpenTiming='manual' lines={[input(quantity)]}>Add to cart</AddToCartButton></>; |
| 38 | + } |
| 39 | + window.start=({existing,quantity,reject})=>{ |
| 40 | + let currentCart=existing ? makeCart(existing,0) : null; |
| 41 | + let firstLoad=true, sequence=0; |
| 42 | + useCartStore.setState({serverCart:currentCart,isResolved:true}); |
| 43 | + useCartStore.setState({inventoryPolicies:new Map([[variant.id,'DENY']])}); |
| 44 | + window.quantities=[];window.requests=[];window.loaders=[]; |
| 45 | + const router=createMemoryRouter([ |
| 46 | + {id:'root',path:'/',element:<Fixture quantity={quantity}/>,loader:()=>{ |
| 47 | + if(firstLoad){firstLoad=false;return {cart:currentCart};} |
| 48 | + return new Promise(resolve=>window.loaders.push(()=>resolve({cart:currentCart}))); |
| 49 | + }}, |
| 50 | + {path:'/cart',action:async({request})=>{ |
| 51 | + const formData=await request.formData(); |
| 52 | + const {inputs}=CartForm.getFormInput(formData); |
| 53 | + window.requests.push({quantity:inputs.lines[0].quantity,token:formData.get('cartStageToken')}); |
| 54 | + await new Promise(resolve=>{window.finishAction=resolve;}); |
| 55 | + if(reject) return {userErrors:[{message:'Rejected'}]}; |
| 56 | + currentCart=makeCart((currentCart?.totalQuantity ?? 0)+inputs.lines[0].quantity,++sequence); |
| 57 | + return {cart:currentCart}; |
| 58 | + }}, |
| 59 | + ]); |
| 60 | + window.router=router; |
| 61 | + createRoot(document.getElementById('root')).render(<RouterProvider router={router}/>); |
| 62 | + }; |
| 63 | + `, |
| 64 | + }, |
| 65 | + bundle: true, |
| 66 | + write: false, |
| 67 | + format: "iife", |
| 68 | + jsx: "automatic", |
| 69 | + alias: { "~": `${root}app` }, |
| 70 | + plugins: [ |
| 71 | + { |
| 72 | + name: "translation-only", |
| 73 | + setup(builder) { |
| 74 | + builder.onResolve({ filter: /^@weaverse\/hydrogen$/ }, () => ({ |
| 75 | + path: "translation", |
| 76 | + namespace: "fixture", |
| 77 | + })); |
| 78 | + builder.onLoad({ filter: /.*/, namespace: "fixture" }, () => ({ |
| 79 | + loader: "js", |
| 80 | + contents: "export const useTranslation=()=>({t:key=>key});", |
| 81 | + })); |
| 82 | + }, |
| 83 | + }, |
| 84 | + ], |
| 85 | +}); |
| 86 | + |
| 87 | +for (const scenario of [ |
| 88 | + { existing: 0, quantity: 5, reject: false }, |
| 89 | + { existing: 0, quantity: 7, reject: false }, |
| 90 | + { existing: 1, quantity: 2, reject: false }, |
| 91 | + { existing: 2, quantity: 3, reject: true }, |
| 92 | +]) { |
| 93 | + test(`add quantities never double during revalidation: ${JSON.stringify(scenario)}`, async () => { |
| 94 | + const browser = await chromium.launch(); |
| 95 | + try { |
| 96 | + const page = await browser.newPage(); |
| 97 | + await page.setContent('<div id="root"></div>'); |
| 98 | + await page.addScriptTag({ content: bundle.outputFiles[0].text }); |
| 99 | + await page.evaluate((options) => window.start(options), scenario); |
| 100 | + const quantity = page.locator('[data-test="cart-quantity"]'); |
| 101 | + const add = page.locator('[data-test="add"]'); |
| 102 | + await expect(quantity).toHaveText(String(scenario.existing)); |
| 103 | + const tokens = []; |
| 104 | + let existing = scenario.existing; |
| 105 | + // A second submission on the same mounted form must get its own token. |
| 106 | + for ( |
| 107 | + let attempt = 0; |
| 108 | + attempt < (scenario.quantity > 3 ? 1 : 2); |
| 109 | + attempt += 1 |
| 110 | + ) { |
| 111 | + await page |
| 112 | + .getByRole("button", { name: "Select quantity", exact: true }) |
| 113 | + .click(); |
| 114 | + await expect(add).toBeEnabled(); |
| 115 | + await add.click(); |
| 116 | + await expect(quantity).toHaveText(String(existing + scenario.quantity)); |
| 117 | + await expect(add).toBeDisabled(); |
| 118 | + await expect |
| 119 | + .poll(() => page.evaluate(() => window.requests.length)) |
| 120 | + .toBe(attempt + 1); |
| 121 | + await page.evaluate(() => window.finishAction()); |
| 122 | + await expect |
| 123 | + .poll(() => page.evaluate(() => window.loaders.length)) |
| 124 | + .toBe(1); |
| 125 | + const accepted = scenario.reject |
| 126 | + ? existing |
| 127 | + : existing + scenario.quantity; |
| 128 | + // Check while revalidation is held, not just after the eventual idle state. |
| 129 | + await expect(quantity).toHaveText(String(accepted)); |
| 130 | + const trace = await page.evaluate(() => window.quantities); |
| 131 | + assert.ok( |
| 132 | + trace.every( |
| 133 | + (frame) => |
| 134 | + frame.total === frame.lineQuantity && |
| 135 | + [existing, existing + scenario.quantity].includes(frame.total), |
| 136 | + ), |
| 137 | + JSON.stringify(trace), |
| 138 | + ); |
| 139 | + const request = await page.evaluate(() => window.requests.at(-1)); |
| 140 | + assert.equal(request.quantity, scenario.quantity); |
| 141 | + assert.ok( |
| 142 | + request.token, |
| 143 | + "The submitted form must retain its stage token", |
| 144 | + ); |
| 145 | + assert.ok( |
| 146 | + !tokens.includes(request.token), |
| 147 | + "Each add needs a fresh token", |
| 148 | + ); |
| 149 | + tokens.push(request.token); |
| 150 | + await page.evaluate(() => { |
| 151 | + for (const finish of window.loaders.splice(0)) { |
| 152 | + finish(); |
| 153 | + } |
| 154 | + }); |
| 155 | + await expect |
| 156 | + .poll(() => |
| 157 | + page.evaluate(() => |
| 158 | + Array.from(window.router.state.fetchers.values()).every( |
| 159 | + (fetcher) => fetcher.state === "idle", |
| 160 | + ), |
| 161 | + ), |
| 162 | + ) |
| 163 | + .toBe(true); |
| 164 | + await expect(quantity).toHaveText(String(accepted)); |
| 165 | + existing = accepted; |
| 166 | + await page.evaluate(() => { |
| 167 | + window.quantities = []; |
| 168 | + }); |
| 169 | + } |
| 170 | + } finally { |
| 171 | + await browser.close(); |
| 172 | + } |
| 173 | + }); |
| 174 | +} |
0 commit comments