examples/storefront Public
import assert from "node:assert/strict";import { test } from "node:test";import { setup } from "./helpers/app.ts";async function withCart() { const s = setup(); await s.addProduct("wool-socks", { name: "Wool socks", price_cents: 1800, stock: 3 }); await s.addProduct("canvas-tote", { name: "Canvas tote", price_cents: 2400, stock: 10 }); const { body } = await s.call("POST", "/carts"); return { ...s, cartId: body.cart.id as string };}test("a new cart is open and empty", async () => { const s = await withCart(); const { body } = await s.call("GET", `/carts/${s.cartId}`); assert.equal(body.cart.status, "open"); assert.deepEqual(body.cart.items, []); assert.equal(body.cart.total_cents, 0);});test("adds items and totals them with shipping", async () => { const s = await withCart(); await s.call("PUT", `/carts/${s.cartId}/items/wool-socks`, { quantity: 2 }); const { body } = await s.call("PUT", `/carts/${s.cartId}/items/canvas-tote`, { quantity: 1 }); assert.equal(body.cart.items.length, 2); assert.equal(body.cart.subtotal_cents, 6000); assert.equal(body.cart.shipping_cents, 0, "free shipping from $50"); assert.equal(body.cart.total_cents, 6000);});test("charges shipping under the threshold", async () => { const s = await withCart(); const { body } = await s.call("PUT", `/carts/${s.cartId}/items/wool-socks`, { quantity: 1 }); assert.equal(body.cart.shipping_cents, 595); assert.equal(body.cart.total_cents, 2395);});test("setting a quantity replaces it, and zero removes the item", async () => { const s = await withCart(); await s.call("PUT", `/carts/${s.cartId}/items/wool-socks`, { quantity: 2 }); let { body } = await s.call("PUT", `/carts/${s.cartId}/items/wool-socks`, { quantity: 1 }); assert.equal(body.cart.items[0].quantity, 1); ({ body } = await s.call("DELETE", `/carts/${s.cartId}/items/wool-socks`)); assert.deepEqual(body.cart.items, []);});test("refuses more than are in stock and says how many are left", async () => { const s = await withCart(); const res = await s.call("PUT", `/carts/${s.cartId}/items/wool-socks`, { quantity: 4 }); assert.equal(res.status, 409); assert.equal(res.body.error, "out_of_stock"); assert.equal(res.body.available, 3);});test("quantities are whole numbers up to ten", async () => { const s = await withCart(); for (const quantity of [-1, 1.5, 11, "2"]) { const res = await s.call("PUT", `/carts/${s.cartId}/items/canvas-tote`, { quantity }); assert.equal(res.status, 400, `quantity ${JSON.stringify(quantity)}`); }});test("unknown carts and products", async () => { const s = await withCart(); assert.equal((await s.call("GET", "/carts/nope")).body.error, "cart_not_found"); assert.equal((await s.call("PUT", `/carts/${s.cartId}/items/nope`, { quantity: 1 })).body.error, "product_not_found");});