@shopbite-de/storefront 1.24.0 → 1.25.0

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 (77) hide show
  1. package/.env.example +3 -0
  2. package/CLAUDE.md +9 -2
  3. package/app/app.config.ts +3 -2
  4. package/app/app.vue +4 -1
  5. package/app/assets/css/main.css +16 -0
  6. package/app/components/AddToWishlist.vue +13 -6
  7. package/app/components/Cart/Bar.vue +102 -0
  8. package/app/components/Cart/QuickView.vue +4 -0
  9. package/app/components/Cart/Upsell.vue +106 -0
  10. package/app/components/Category/Listing.vue +11 -3
  11. package/app/components/Checkout/Summary.vue +5 -1
  12. package/app/components/DemoBanner.vue +13 -0
  13. package/app/components/Feature/Card.vue +121 -0
  14. package/app/components/Features.vue +14 -9
  15. package/app/components/Footer/Contact.vue +5 -1
  16. package/app/components/Header/Right.vue +44 -15
  17. package/app/components/Hero.vue +126 -36
  18. package/app/components/Product/Card.vue +102 -50
  19. package/app/components/Product/CardCompact.vue +72 -0
  20. package/app/components/Product/CardDietBadges.vue +38 -31
  21. package/app/components/Product/CardIngredients.vue +35 -0
  22. package/app/components/Product/CardSkeleton.vue +10 -18
  23. package/app/components/Product/Category.vue +9 -2
  24. package/app/components/Product/Configurator.vue +11 -7
  25. package/app/components/Product/CrossSelling.vue +45 -34
  26. package/app/components/Product/DeselectIngredient.vue +37 -31
  27. package/app/components/Product/Detail.vue +73 -13
  28. package/app/components/Product/QuickView.vue +77 -0
  29. package/app/components/Topseller.vue +44 -34
  30. package/app/composables/useAddToCart.ts +3 -30
  31. package/app/composables/useCartQuickView.ts +19 -0
  32. package/app/composables/useCartUpsell.ts +100 -0
  33. package/app/composables/useCategorySeo.ts +5 -4
  34. package/app/composables/useProductCartQuantity.ts +15 -0
  35. package/app/composables/useProductCrossSelling.ts +1 -0
  36. package/app/composables/useProductDetail.ts +15 -1
  37. package/app/composables/useProductEvents.ts +30 -0
  38. package/app/composables/useProductQuickView.ts +65 -0
  39. package/app/composables/useTopSellers.ts +22 -0
  40. package/app/composables/useTrackEvent.ts +7 -0
  41. package/app/pages/index.vue +3 -1
  42. package/app/pages/suche.vue +18 -5
  43. package/app/types/Association.d.ts +1 -0
  44. package/app/utils/openingHours.ts +31 -8
  45. package/app/utils/product.ts +31 -0
  46. package/content/index.yml +16 -11
  47. package/content.config.ts +13 -0
  48. package/docs/notes/2026-09-12-issue-319-stylesheet-cost.md +154 -0
  49. package/docs/notes/2026-09-12-issue-325-product-card.md +100 -0
  50. package/docs/notes/2026-09-12-issue-327-home-hero.md +64 -0
  51. package/docs/notes/2026-09-13-demo-banner.md +32 -0
  52. package/docs/notes/2026-09-13-issue-332-home-info-cards.md +46 -0
  53. package/docs/notes/2026-09-13-quick-view-flicker.md +65 -0
  54. package/docs/notes/2026-09-14-cart-upsell.md +105 -0
  55. package/docs/notes/2026-09-14-demo-noindex.md +57 -0
  56. package/nuxt.config.ts +24 -0
  57. package/package.json +1 -1
  58. package/scripts/perf/first-render.mjs +30 -0
  59. package/scripts/perf/h2-proxy.cjs +49 -0
  60. package/scripts/perf/lighthouse.sh +22 -0
  61. package/scripts/perf/quick-view-layout.mjs +126 -0
  62. package/server/api/listing/[categoryId].get.ts +2 -0
  63. package/server/api/search.get.ts +2 -0
  64. package/test/e2e/simple-checkout-as-recurring-customer.test.ts +13 -17
  65. package/test/nuxt/CartBar.test.ts +110 -0
  66. package/test/nuxt/CartUpsell.test.ts +125 -0
  67. package/test/nuxt/DemoBanner.test.ts +12 -0
  68. package/test/nuxt/useAddToCart.test.ts +6 -19
  69. package/test/nuxt/useCartUpsell.test.ts +126 -0
  70. package/test/nuxt/useTrackEvent.test.ts +15 -0
  71. package/test/unit/openingHours.spec.ts +32 -1
  72. package/test/unit/product.spec.ts +72 -0
  73. package/test/unit/useCategorySeo.spec.ts +2 -1
  74. package/test/visual/playwright.config.ts +33 -0
  75. package/test/visual/visual.spec.ts +87 -0
  76. package/app/components/Product/CardDescription.vue +0 -27
  77. package/app/components/Product/CardFooter.vue +0 -61
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@shopbite-de/storefront",
3
- "version": "1.24.0",
3
+ "version": "1.25.0",
4
4
  "main": "nuxt.config.ts",
5
5
  "description": "Shopware storefront for food delivery shops",
6
6
  "keywords": [
@@ -0,0 +1,30 @@
1
+ // First UpdateLayoutTree + first Layout duration of a page through the h2
2
+ // proxy (mobile viewport, CPU throttle RATE, default 4), median of N runs.
3
+ // node scripts/perf/first-render.mjs / /c/Pizza/
4
+ // BLOCK='\.woff2$' node scripts/perf/first-render.mjs / # abort matching requests
5
+ import { chromium } from 'playwright';
6
+ const paths = process.argv.slice(2); const N = Number(process.env.N || 3);
7
+ const browser = await chromium.launch({ args: ['--ignore-certificate-errors'] });
8
+ const med = (a) => { const s = [...a].sort((x, y) => x - y); return s[Math.floor(s.length / 2)]; };
9
+ for (const p of paths) {
10
+ const rs = [], ls = [], rt = [], lt = []; let rendered = 0;
11
+ for (let i = 0; i < N; i++) {
12
+ const ctx = await browser.newContext({ viewport: { width: 390, height: 844 }, isMobile: true, hasTouch: true, deviceScaleFactor: 2, ignoreHTTPSErrors: true });
13
+ if (process.env.BLOCK) await ctx.route(new RegExp(process.env.BLOCK), (r) => r.abort());
14
+ const page = await ctx.newPage(); const cdp = await ctx.newCDPSession(page);
15
+ await cdp.send('Emulation.setCPUThrottlingRate', { rate: Number(process.env.RATE || 4) });
16
+ await cdp.send('Tracing.start', { categories: 'devtools.timeline,disabled-by-default-devtools.timeline', transferMode: 'ReportEvents' });
17
+ const ev = []; cdp.on('Tracing.dataCollected', (e) => ev.push(...e.value));
18
+ await page.goto('https://localhost:3443' + p, { waitUntil: 'load' }); await page.waitForTimeout(1500);
19
+ rendered = await page.evaluate(() => [...document.querySelectorAll('*')].filter((e) => e.getClientRects().length).length);
20
+ await cdp.send('Tracing.end'); await new Promise((r) => cdp.on('Tracing.tracingComplete', r));
21
+ const x = ev.filter((e) => e.ph === 'X' && (e.name === 'UpdateLayoutTree' || e.name === 'Layout')).sort((a, b) => a.ts - b.ts);
22
+ const big = (n) => x.filter((e) => e.name === n && e.dur > 2000);
23
+ const r = big('UpdateLayoutTree'), l = big('Layout');
24
+ rs.push(r.length ? r[0].dur / 1000 : 0); ls.push(l.length ? l[0].dur / 1000 : 0);
25
+ rt.push(x.filter((e) => e.name === 'UpdateLayoutTree').reduce((s, e) => s + e.dur, 0) / 1000); lt.push(x.filter((e) => e.name === 'Layout').reduce((s, e) => s + e.dur, 0) / 1000);
26
+ await ctx.close();
27
+ }
28
+ console.log(`${p.padEnd(18)} first recalc ${med(rs).toFixed(1).padStart(6)} ms first layout ${med(ls).toFixed(1).padStart(6)} ms | total recalc ${med(rt).toFixed(0).padStart(4)} ms total layout ${med(lt).toFixed(0).padStart(4)} ms (median of ${N}) rendered=${rendered}`);
29
+ }
30
+ await browser.close();
@@ -0,0 +1,49 @@
1
+ // TLS + HTTP/2 + gzip reverse proxy in front of the Nitro server so that
2
+ // Lighthouse sees production-like transport (docs/notes/2026-09-10-issue-273-performance-media.md).
3
+ //
4
+ // openssl req -x509 -newkey rsa:2048 -nodes -keyout key.pem -out cert.pem -days 30 -subj "/CN=localhost"
5
+ // PORT=3099 node --env-file=.env .output/server/index.mjs
6
+ // node scripts/perf/h2-proxy.cjs # https://localhost:3443 -> :3099
7
+ //
8
+ // Files in scripts/perf/exp/ are served at /exp/ (static page variants, #319).
9
+ // key.pem, cert.pem and exp/ are git-ignored.
10
+ const http2 = require('http2');
11
+ const http = require('http');
12
+ const fs = require('fs');
13
+ const zlib = require('zlib');
14
+ const path = require('path');
15
+ const upstreamPort = Number(process.env.UPSTREAM_PORT || 3099);
16
+ const listenPort = Number(process.env.PORT || 3443);
17
+ const server = http2.createSecureServer({
18
+ key: fs.readFileSync(path.join(__dirname, 'key.pem')),
19
+ cert: fs.readFileSync(path.join(__dirname, 'cert.pem')),
20
+ allowHTTP1: true,
21
+ });
22
+ const types = { html: 'text/html; charset=utf-8', css: 'text/css', js: 'text/javascript', json: 'application/json', woff2: 'font/woff2', webp: 'image/webp', png: 'image/png', svg: 'image/svg+xml' };
23
+ server.on('request', (req, res) => {
24
+ if (req.url.startsWith('/exp/')) {
25
+ const file = path.join(__dirname, 'exp', req.url.slice(5).split('?')[0]);
26
+ if (!fs.existsSync(file)) { res.writeHead(404); res.end('nope'); return; }
27
+ const ext = file.split('.').pop(); const body = fs.readFileSync(file);
28
+ const type = types[ext] || 'application/octet-stream';
29
+ if (/text|javascript|json|svg/.test(type)) { res.writeHead(200, { 'content-type': type, 'content-encoding': 'gzip', 'cache-control': 'no-store' }); res.end(zlib.gzipSync(body)); }
30
+ else { res.writeHead(200, { 'content-type': type, 'cache-control': 'no-store' }); res.end(body); }
31
+ return;
32
+ }
33
+ const headers = { ...req.headers };
34
+ delete headers[':method']; delete headers[':path']; delete headers[':scheme']; delete headers[':authority'];
35
+ headers.host = 'localhost:' + upstreamPort;
36
+ headers['accept-encoding'] = 'identity';
37
+ const up = http.request({ host: '127.0.0.1', port: upstreamPort, method: req.method, path: req.url, headers }, (ur) => {
38
+ const h = { ...ur.headers };
39
+ delete h.connection; delete h['transfer-encoding']; delete h['keep-alive'];
40
+ const type = h['content-type'] || '';
41
+ const compressible = /text|javascript|json|xml|svg/.test(type) && !h['content-encoding'];
42
+ if (compressible) { h['content-encoding'] = 'gzip'; delete h['content-length']; }
43
+ res.writeHead(ur.statusCode, h);
44
+ if (compressible) ur.pipe(zlib.createGzip({ level: 6 })).pipe(res); else ur.pipe(res);
45
+ });
46
+ up.on('error', (e) => { res.writeHead(502); res.end(String(e)); });
47
+ req.pipe(up);
48
+ });
49
+ server.listen(listenPort, () => console.log('h2 proxy on https://localhost:' + listenPort + ' -> :' + upstreamPort));
@@ -0,0 +1,22 @@
1
+ #!/bin/bash
2
+ # Lighthouse mobile run against the h2 proxy with the main-thread breakdown.
3
+ # usage: scripts/perf/lighthouse.sh <label> <path> [runs]
4
+ # Needs Lighthouse (npx lighthouse) and a Chrome binary in CHROME_PATH
5
+ # (e.g. the Playwright Chromium: ~/.cache/ms-playwright/chromium-*/chrome-linux64/chrome).
6
+ # LH_EXTRA="--save-assets" keeps the trace next to the JSON.
7
+ S=${LH_OUT:-scripts/perf/out}
8
+ LABEL=$1; P=$2; RUNS=${3:-2}
9
+ export CHROME_PATH=${CHROME_PATH:-$(ls -d "$HOME"/.cache/ms-playwright/chromium-*/chrome-linux64/chrome 2>/dev/null | tail -1)}
10
+ LH=${LIGHTHOUSE:-lighthouse}
11
+ mkdir -p "$S/lh"
12
+ for i in $(seq 1 $RUNS); do
13
+ $LH "https://localhost:3443$P" --quiet --output=json --output-path=$S/lh/$LABEL-$i.json \
14
+ --form-factor=mobile --screenEmulation.mobile --throttling-method=simulate \
15
+ --only-categories=performance ${LH_EXTRA:-} --chrome-flags="--headless=new --ignore-certificate-errors --no-sandbox" >/dev/null 2>&1
16
+ node -e '
17
+ const r=require(process.argv[1]); const a=r.audits;
18
+ const mt=a["mainthread-work-breakdown"].details.items; const g=k=>{const i=mt.find(x=>x.group===k);return i?Math.round(i.duration):0};
19
+ const css=(a["network-requests"].details.items||[]).filter(x=>x.resourceType==="Stylesheet").map(x=>x.url.split("/").pop()+" "+Math.round(x.transferSize/1024)+"KB");
20
+ console.log(process.argv[2], "perf", Math.round(r.categories.performance.score*100), "FCP", Math.round(a["first-contentful-paint"].numericValue), "LCP", Math.round(a["largest-contentful-paint"].numericValue), "TBT", Math.round(a["total-blocking-time"].numericValue), "| style&layout", g("styleLayout"), "script", g("scriptEvaluation"), "parseHTML", g("parseHTML"), "paint", g("paintCompositeRender"), "total", Math.round(mt.reduce((s,x)=>s+x.duration,0)), "| dom", a["dom-size"].numericValue, "| css:", css.join(", "));
21
+ ' $S/lh/$LABEL-$i.json "$LABEL#$i"
22
+ done
@@ -0,0 +1,126 @@
1
+ // Logs the quick view drawer body per animation frame after opening it and
2
+ // after switching a variant, collapsed to the distinct layout states, plus
3
+ // the /api/product requests (docs/notes/2026-09-13-quick-view-flicker.md).
4
+ //
5
+ // BASE_URL=http://localhost:3000 node scripts/perf/quick-view-layout.mjs
6
+ // MOBILE=1 OUT=/tmp node scripts/perf/quick-view-layout.mjs
7
+ //
8
+ // Expects a listing at CATEGORY_PATH (default /c/Salate/) containing a card
9
+ // whose name matches PRODUCT (default "Insalata di Pollo") with variants.
10
+ import { chromium } from "@playwright/test";
11
+ const base = process.env.BASE_URL ?? "http://localhost:3000";
12
+ const mobile = process.env.MOBILE === "1";
13
+ const browser = await chromium.launch();
14
+ const ctx = await browser.newContext(
15
+ mobile
16
+ ? { viewport: { width: 390, height: 844 }, isMobile: true, hasTouch: true }
17
+ : { viewport: { width: 1280, height: 800 } },
18
+ );
19
+ const page = await ctx.newPage();
20
+ page.on("request", (r) => {
21
+ if (r.url().includes("/api/product"))
22
+ console.log(
23
+ " ->",
24
+ Math.round(performance.now() - (globalThis.__t0 ?? 0)),
25
+ "ms",
26
+ r.method(),
27
+ r.url().replace(base, ""),
28
+ );
29
+ });
30
+ page.on("response", (r) => {
31
+ if (r.url().includes("/api/product"))
32
+ console.log(
33
+ " <-",
34
+ Math.round(performance.now() - (globalThis.__t0 ?? 0)),
35
+ "ms",
36
+ r.status(),
37
+ r.url().replace(base, ""),
38
+ );
39
+ });
40
+ await page.goto(`${base}${process.env.CATEGORY_PATH ?? "/c/Salate/"}`, {
41
+ waitUntil: "networkidle",
42
+ });
43
+
44
+ async function record(label, action, ms = 2500) {
45
+ globalThis.__t0 = performance.now();
46
+ await page.evaluate(() => {
47
+ window.__log = [];
48
+ window.__t0 = performance.now();
49
+ const tick = () => {
50
+ const body = document.querySelector('[data-slot="body"]');
51
+ const content = document.querySelector('[data-slot="content"]');
52
+ window.__log.push({
53
+ t: Math.round(performance.now() - window.__t0),
54
+ content: content
55
+ ? Math.round(content.getBoundingClientRect().height)
56
+ : null,
57
+ body: body ? Math.round(body.scrollHeight) : null,
58
+ skeletons: body ? body.querySelectorAll(".animate-pulse").length : 0,
59
+ combos: body ? body.querySelectorAll('[role="combobox"]').length : 0,
60
+ chips: body ? body.querySelectorAll('[role="group"] button').length : 0,
61
+ });
62
+ if (performance.now() - window.__t0 < 6000) requestAnimationFrame(tick);
63
+ };
64
+ requestAnimationFrame(tick);
65
+ });
66
+ await action();
67
+ await page.waitForTimeout(ms);
68
+ const log = await page.evaluate(() => window.__log);
69
+ // Collapse consecutive identical states.
70
+ const steps = [];
71
+ for (const entry of log) {
72
+ const key = JSON.stringify([
73
+ entry.content,
74
+ entry.body,
75
+ entry.skeletons,
76
+ entry.combos,
77
+ entry.chips,
78
+ ]);
79
+ if (!steps.length || steps[steps.length - 1].key !== key)
80
+ steps.push({ key, ...entry });
81
+ }
82
+ console.log(`\n== ${label}: ${steps.length - 1} state changes`);
83
+ for (const s of steps)
84
+ console.log(
85
+ ` t=${String(s.t).padStart(4)}ms content=${s.content} body=${s.body} skeletons=${s.skeletons} selects=${s.combos} chips=${s.chips}`,
86
+ );
87
+ }
88
+
89
+ await record("open quick view", async () => {
90
+ await page
91
+ .getByText(process.env.PRODUCT ?? "Insalata di Pollo", { exact: false })
92
+ .first()
93
+ .click();
94
+ });
95
+ await page.screenshot({
96
+ path: `${process.env.OUT ?? "."}/open-${mobile ? "mobile" : "desktop"}.png`,
97
+ });
98
+
99
+ await record("switch variant", async () => {
100
+ const combo = page.locator('[data-slot="body"] [role="combobox"]').first();
101
+ const current = (await combo.innerText()).trim();
102
+ await combo.click();
103
+ const listbox = page.getByRole("listbox");
104
+ await listbox.waitFor({ state: "visible" });
105
+ const options = listbox.getByRole("option");
106
+ const texts = await options.allInnerTexts();
107
+ console.log(
108
+ " options:",
109
+ texts.map((t) => t.trim()).join(" | "),
110
+ "current:",
111
+ current,
112
+ );
113
+ const idx = texts.findIndex((t) => t.trim() !== current);
114
+ await options.nth(idx).click();
115
+ await page.waitForFunction(
116
+ (c) =>
117
+ document
118
+ .querySelector('[data-slot="body"] [role="combobox"]')
119
+ ?.innerText.trim() !== c,
120
+ current,
121
+ );
122
+ });
123
+ await page.screenshot({
124
+ path: `${process.env.OUT ?? "."}/variant-${mobile ? "mobile" : "desktop"}.png`,
125
+ });
126
+ await browser.close();
@@ -15,6 +15,8 @@ const BASE_CRITERIA = {
15
15
  "propertyIds",
16
16
  "sortedProperties",
17
17
  "cover",
18
+ // "Ausverkauft" on the card (#325).
19
+ "available",
18
20
  ],
19
21
  property: ["id", "name", "translated", "displayType", "options"],
20
22
  property_group_option: [
@@ -15,6 +15,8 @@ const BASE_CRITERIA = {
15
15
  "propertyIds",
16
16
  "sortedProperties",
17
17
  "cover",
18
+ // "Ausverkauft" on the card (#325).
19
+ "available",
18
20
  ],
19
21
  property: ["id", "name", "translated", "displayType", "options"],
20
22
  property_group_option: [
@@ -64,31 +64,27 @@ async function selectProductAndAddToCart(
64
64
  ) {
65
65
  const productCard = page.locator(`#product-card-${productId}`);
66
66
  await expect(productCard).toBeVisible();
67
-
68
- // Verify product card structure
69
- const buttons = productCard.locator("button");
70
- await expect(buttons).toHaveCount(2);
71
67
  await expect(productCard.locator("button .i-lucide\\:heart")).toBeVisible();
72
68
 
73
- // Open product details
74
- const showDetailsButton = productCard.locator(
75
- "button .i-lucide\\:shopping-cart",
76
- );
77
- await expect(showDetailsButton).toBeVisible();
78
- await showDetailsButton.click();
69
+ // The card opens the quick view drawer; its state is the `produkt`
70
+ // query parameter (#325).
71
+ await productCard.getByRole("button", { name: /auswählen$/i }).click();
72
+ const drawer = page.locator('[data-vaul-drawer][data-state="open"]');
73
+ await expect(drawer).toBeVisible({ timeout: 10000 });
74
+ await expect(page).toHaveURL(/[?&]produkt=/);
79
75
 
80
- // Set quantity and add to cart
81
- const quantityInput = page.getByRole("spinbutton", { name: /anzahl/i });
82
- await expect(quantityInput).toBeVisible();
76
+ const quantityInput = drawer.getByRole("spinbutton", { name: /anzahl/i });
77
+ await expect(quantityInput).toBeVisible({ timeout: 10000 });
83
78
  await quantityInput.fill(quantity.toString());
84
79
  await expect(quantityInput).toHaveValue(quantity.toString());
85
80
 
86
- const addToCartButton = page.getByRole("button", {
87
- name: "In den Warenkorb",
81
+ const addToCartButton = drawer.getByRole("button", {
82
+ name: /In den Warenkorb/,
88
83
  });
89
- await expect(addToCartButton).toBeVisible({ timeout: 10000 });
84
+ await expect(addToCartButton).toBeEnabled({ timeout: 10000 });
90
85
  await addToCartButton.click();
91
- await expect(addToCartButton).not.toBeVisible({ timeout: 5000 });
86
+ await expect(drawer).not.toBeVisible({ timeout: 10000 });
87
+ await expect(page).not.toHaveURL(/[?&]produkt=/);
92
88
  }
93
89
 
94
90
  async function proceedToCheckoutAndLogin(page: Page) {
@@ -0,0 +1,110 @@
1
+ import { describe, it, expect, vi, beforeEach } from "vitest";
2
+ import { mountSuspended, mockNuxtImport } from "@nuxt/test-utils/runtime";
3
+ import { ref, reactive, computed } from "vue";
4
+ import CartBar from "~/components/Cart/Bar.vue";
5
+
6
+ const state = reactive({ count: 0, subtotal: 0, path: "/c/Pizza/" });
7
+ const showCalls = vi.hoisted(() => ({ value: 0 }));
8
+ type Addition = {
9
+ product: { name: string; translated: { name: string } };
10
+ quantity: number;
11
+ };
12
+ const listeners: Array<(addition: Addition) => void> = [];
13
+
14
+ mockNuxtImport("useCart", () => () => ({
15
+ count: computed(() => state.count),
16
+ subtotal: computed(() => state.subtotal),
17
+ }));
18
+ mockNuxtImport("useShopBiteConfig", () => () => ({
19
+ isCheckoutEnabled: ref(true),
20
+ }));
21
+ mockNuxtImport("useCommercePrice", () => () => ({
22
+ getFormattedPrice: (price: number) => `${price.toFixed(2)} €`,
23
+ }));
24
+ mockNuxtImport("useRoute", () => () => ({
25
+ get path() {
26
+ return state.path;
27
+ },
28
+ query: {},
29
+ }));
30
+ mockNuxtImport("useProductEvents", () => () => ({
31
+ onCartItemAdded: (callback: (addition: Addition) => void) => {
32
+ listeners.push(callback);
33
+ },
34
+ }));
35
+ mockNuxtImport("useCartQuickView", () => () => ({
36
+ open: ref(false),
37
+ mounted: ref(false),
38
+ show: () => {
39
+ showCalls.value++;
40
+ },
41
+ }));
42
+
43
+ describe("CartBar", () => {
44
+ beforeEach(() => {
45
+ state.count = 0;
46
+ state.subtotal = 0;
47
+ state.path = "/c/Pizza/";
48
+ showCalls.value = 0;
49
+ listeners.length = 0;
50
+ });
51
+
52
+ it("stays hidden with an empty cart", async () => {
53
+ const wrapper = await mountSuspended(CartBar);
54
+ expect(wrapper.find('[data-testid="cart-bar"]').exists()).toBe(false);
55
+ });
56
+
57
+ it("shows the item count and the subtotal", async () => {
58
+ state.count = 2;
59
+ state.subtotal = 15.5;
60
+ const wrapper = await mountSuspended(CartBar);
61
+ const bar = wrapper.find('[data-testid="cart-bar"]');
62
+ expect(bar.text()).toContain("2 Artikel · 15.50 €");
63
+ });
64
+
65
+ it("uses the singular for one item", async () => {
66
+ state.count = 1;
67
+ state.subtotal = 7;
68
+ const wrapper = await mountSuspended(CartBar);
69
+ expect(wrapper.find('[data-testid="cart-bar"]').text()).toContain(
70
+ "1 Artikel",
71
+ );
72
+ });
73
+
74
+ it("opens the cart drawer on click", async () => {
75
+ state.count = 2;
76
+ const wrapper = await mountSuspended(CartBar);
77
+ await wrapper.find('[data-testid="cart-bar"]').trigger("click");
78
+ expect(showCalls.value).toBe(1);
79
+ });
80
+
81
+ it("names the added product for a moment instead of a toast", async () => {
82
+ vi.useFakeTimers();
83
+ state.count = 2;
84
+ state.subtotal = 15.5;
85
+ const wrapper = await mountSuspended(CartBar);
86
+ for (const listener of listeners) {
87
+ listener({
88
+ product: { name: "Pizza Salami", translated: { name: "Pizza Salami" } },
89
+ quantity: 2,
90
+ });
91
+ }
92
+ await wrapper.vm.$nextTick();
93
+ expect(wrapper.find('[data-testid="cart-bar"]').text()).toContain(
94
+ "2× Pizza Salami",
95
+ );
96
+ vi.advanceTimersByTime(2000);
97
+ await wrapper.vm.$nextTick();
98
+ expect(wrapper.find('[data-testid="cart-bar"]').text()).toContain(
99
+ "2 Artikel",
100
+ );
101
+ vi.useRealTimers();
102
+ });
103
+
104
+ it("is hidden on the checkout pages", async () => {
105
+ state.count = 2;
106
+ state.path = "/bestellung/warenkorb";
107
+ const wrapper = await mountSuspended(CartBar);
108
+ expect(wrapper.find('[data-testid="cart-bar"]').exists()).toBe(false);
109
+ });
110
+ });
@@ -0,0 +1,125 @@
1
+ import { describe, it, expect, vi, beforeEach } from "vitest";
2
+ import { mountSuspended, mockNuxtImport } from "@nuxt/test-utils/runtime";
3
+ import { flushPromises } from "@vue/test-utils";
4
+ import { computed, reactive } from "vue";
5
+ import { clearNuxtData } from "#imports";
6
+ import CartUpsell from "~/components/Cart/Upsell.vue";
7
+ import type { Schemas } from "#shopware";
8
+
9
+ const { mockLoadUpsellProducts, mockAddUpsellProduct } = vi.hoisted(() => ({
10
+ mockLoadUpsellProducts: vi.fn(),
11
+ mockAddUpsellProduct: vi.fn(),
12
+ }));
13
+
14
+ // Read lazily inside the factories, i.e. after module initialisation.
15
+ const cart = reactive({ items: [] as unknown[] });
16
+
17
+ mockNuxtImport("useCartUpsell", () => () => ({
18
+ loadUpsellProducts: mockLoadUpsellProducts,
19
+ addUpsellProduct: mockAddUpsellProduct,
20
+ isAdding: () => false,
21
+ }));
22
+ mockNuxtImport("useCart", () => () => ({
23
+ cartItems: computed(() => cart.items as Schemas["LineItem"][]),
24
+ }));
25
+ mockNuxtImport("useCommercePrice", () => () => ({
26
+ getFormattedPrice: (value: number) => `${value} €`,
27
+ }));
28
+
29
+ const product = (id: string, name: string, overrides = {}) =>
30
+ ({
31
+ id,
32
+ productNumber: id.toUpperCase(),
33
+ name,
34
+ translated: { name },
35
+ calculatedPrice: { totalPrice: 5.5 },
36
+ ...overrides,
37
+ }) as unknown as Schemas["Product"];
38
+
39
+ const tiramisu = product("tiramisu", "Tiramisu");
40
+ const cola = product("cola", "Cola");
41
+
42
+ async function mountUpsell() {
43
+ const wrapper = await mountSuspended(CartUpsell);
44
+ await flushPromises();
45
+ return wrapper;
46
+ }
47
+
48
+ describe("CartUpsell", () => {
49
+ beforeEach(() => {
50
+ vi.clearAllMocks();
51
+ clearNuxtData("cart-upsell");
52
+ cart.items = [];
53
+ mockLoadUpsellProducts.mockResolvedValue([tiramisu, cola]);
54
+ });
55
+
56
+ it("shows the suggestions with name, number and price", async () => {
57
+ const wrapper = await mountUpsell();
58
+
59
+ expect(wrapper.find("h3").text()).toBe("Dazu passt");
60
+ const tiles = wrapper.findAll("li");
61
+ expect(tiles).toHaveLength(2);
62
+ expect(tiles[0]!.text()).toContain("#TIRAMISU");
63
+ expect(tiles[0]!.text()).toContain("Tiramisu");
64
+ expect(tiles[0]!.text()).toContain("5.5 €");
65
+ });
66
+
67
+ it("hides products that are already in the cart", async () => {
68
+ cart.items = [{ id: "li-1", type: "product", referencedId: "tiramisu" }];
69
+ const wrapper = await mountUpsell();
70
+
71
+ expect(wrapper.text()).not.toContain("Tiramisu");
72
+ expect(wrapper.text()).toContain("Cola");
73
+
74
+ // Also as the product of a container item with extras.
75
+ cart.items = [
76
+ {
77
+ id: "li-2",
78
+ type: "container",
79
+ children: [{ id: "c-1", type: "product", referencedId: "cola" }],
80
+ },
81
+ ];
82
+ await flushPromises();
83
+ expect(wrapper.text()).toContain("Tiramisu");
84
+ expect(wrapper.text()).not.toContain("Cola");
85
+ });
86
+
87
+ it("renders no row when every suggestion is in the cart", async () => {
88
+ cart.items = [
89
+ { id: "li-1", type: "product", referencedId: "tiramisu" },
90
+ { id: "li-2", type: "product", referencedId: "cola" },
91
+ ];
92
+ const wrapper = await mountUpsell();
93
+
94
+ expect(wrapper.find("section").exists()).toBe(false);
95
+ });
96
+
97
+ it("adds the product on a plus click", async () => {
98
+ const wrapper = await mountUpsell();
99
+
100
+ await wrapper
101
+ .find('button[aria-label="Tiramisu in den Warenkorb"]')
102
+ .trigger("click");
103
+
104
+ expect(mockAddUpsellProduct).toHaveBeenCalledWith(tiramisu);
105
+ });
106
+
107
+ it("disables the button of an unavailable product", async () => {
108
+ mockLoadUpsellProducts.mockResolvedValue([
109
+ product("panna-cotta", "Panna Cotta", { available: false }),
110
+ cola,
111
+ ]);
112
+ const wrapper = await mountUpsell();
113
+
114
+ expect(
115
+ wrapper
116
+ .find('button[aria-label="Panna Cotta in den Warenkorb"]')
117
+ .attributes("disabled"),
118
+ ).toBeDefined();
119
+ expect(
120
+ wrapper
121
+ .find('button[aria-label="Cola in den Warenkorb"]')
122
+ .attributes("disabled"),
123
+ ).toBeUndefined();
124
+ });
125
+ });
@@ -0,0 +1,12 @@
1
+ import { describe, it, expect } from "vitest";
2
+ import { mountSuspended } from "@nuxt/test-utils/runtime";
3
+ import DemoBanner from "~/components/DemoBanner.vue";
4
+
5
+ describe("DemoBanner", () => {
6
+ it("renders the demo notice", async () => {
7
+ const wrapper = await mountSuspended(DemoBanner);
8
+
9
+ expect(wrapper.text()).toContain("Demo-Shop");
10
+ expect(wrapper.text()).toContain("nicht ausgeliefert");
11
+ });
12
+ });
@@ -9,14 +9,12 @@ import { nextTick } from "vue";
9
9
  const {
10
10
  mockAddProducts,
11
11
  mockRefreshCart,
12
- mockToastAdd,
13
- mockTriggerProductAdded,
12
+ mockTriggerCartItemAdded,
14
13
  mockTrackEvent,
15
14
  } = vi.hoisted(() => ({
16
15
  mockAddProducts: vi.fn(),
17
16
  mockRefreshCart: vi.fn(),
18
- mockToastAdd: vi.fn(),
19
- mockTriggerProductAdded: vi.fn(),
17
+ mockTriggerCartItemAdded: vi.fn(),
20
18
  mockTrackEvent: vi.fn(),
21
19
  }));
22
20
 
@@ -33,15 +31,9 @@ mockNuxtImport("useCart", () => {
33
31
  });
34
32
  });
35
33
 
36
- mockNuxtImport("useToast", () => {
37
- return () => ({
38
- add: mockToastAdd,
39
- });
40
- });
41
-
42
34
  mockNuxtImport("useProductEvents", () => {
43
35
  return () => ({
44
- triggerProductAdded: mockTriggerProductAdded,
36
+ triggerCartItemAdded: mockTriggerCartItemAdded,
45
37
  });
46
38
  });
47
39
 
@@ -59,11 +51,8 @@ vi.stubGlobal("useCart", () => ({
59
51
  addProducts: mockAddProducts,
60
52
  refreshCart: mockRefreshCart,
61
53
  }));
62
- vi.stubGlobal("useToast", () => ({
63
- add: mockToastAdd,
64
- }));
65
54
  vi.stubGlobal("useProductEvents", () => ({
66
- triggerProductAdded: mockTriggerProductAdded,
55
+ triggerCartItemAdded: mockTriggerCartItemAdded,
67
56
  }));
68
57
  vi.stubGlobal("useTrackEvent", () => ({
69
58
  trackAddToCart: mockTrackEvent,
@@ -142,8 +131,7 @@ describe("useAddToCart", () => {
142
131
  type: "product",
143
132
  },
144
133
  ]);
145
- expect(mockToastAdd).toHaveBeenCalled();
146
- expect(mockTriggerProductAdded).toHaveBeenCalled();
134
+ expect(mockTriggerCartItemAdded).toHaveBeenCalledWith(mockProduct, 1);
147
135
  expect(mockTrackEvent).toHaveBeenCalledWith(mockProduct, 1);
148
136
  });
149
137
 
@@ -157,8 +145,7 @@ describe("useAddToCart", () => {
157
145
  await addToCart();
158
146
 
159
147
  expect(isLoading.value).toBe(false);
160
- expect(mockToastAdd).not.toHaveBeenCalled();
161
- expect(mockTriggerProductAdded).not.toHaveBeenCalled();
148
+ expect(mockTriggerCartItemAdded).not.toHaveBeenCalled();
162
149
  expect(mockTrackEvent).not.toHaveBeenCalled();
163
150
  });
164
151