// : the optimistic press, reconciliation with the server's tally, // rollback with a toast, the captcha fallback to a native submission, and the // in-flight guard. fetch is a fake per test; the tally arithmetic is also // proven on its own. import { afterEach, beforeEach, describe, expect, test } from "bun:test"; import { bodyOf, fromAnswer, press } from "../packages/vote/index"; import styles from "../packages/vote/vote.css"; const sleep = (ms = 0) => new Promise(resolve => setTimeout(resolve, ms)); const MARKUP = `
`; interface Call { url: string; init: RequestInit; } let calls: Call[] = []; let answer: () => Promise; let release: (() => void) | null = null; const realFetch = globalThis.fetch; const toasts: unknown[] = []; const onToast = (event: Event) => toasts.push((event as CustomEvent).detail); const json = (body: unknown, status = 200) => new Response(JSON.stringify(body), { status, headers: { "content-type": "application/json" } }); beforeEach(() => { calls = []; toasts.length = 0; answer = async () => json({ up: 13, down: 3, mine: 1 }); globalThis.fetch = (async (url: string | URL, init: RequestInit = {}) => { calls.push({ url: String(url), init }); return answer(); }) as typeof fetch; window.addEventListener("toast", onToast); }); afterEach(async () => { globalThis.fetch = realFetch; window.removeEventListener("toast", onToast); document.body.textContent = ""; await sleep(0); // define() releases one macrotask later }); // Built detached, then attached: the element reads its children when it connects // (a browser's innerHTML and a deferred module script both guarantee that). const mount = (html = MARKUP) => { const wrap = document.createElement("div"); wrap.innerHTML = html; document.body.appendChild(wrap); const host = wrap.querySelector("pebble-vote") as HTMLElement; const [up, down] = [...host.querySelectorAll("button")] as HTMLButtonElement[]; return { host, up: up!, down: down! }; }; const state = (b: HTMLButtonElement) => ({ count: b.dataset.count, pressed: b.getAttribute("aria-pressed"), label: b.getAttribute("aria-label"), text: b.querySelector("[data-count-label]")!.textContent, }); const submit = (button: HTMLButtonElement) => { const form = button.form!; const event = new Event("submit", { bubbles: true, cancelable: true }); form.dispatchEvent(event); return event; }; describe("the tally", () => { test("pressing a side casts, pressing it again takes it back, the other side moves it", () => { expect(press({ up: 12, down: 3, mine: 0 }, 1)).toEqual({ up: 13, down: 3, mine: 1 }); expect(press({ up: 13, down: 3, mine: 1 }, 1)).toEqual({ up: 12, down: 3, mine: 0 }); expect(press({ up: 13, down: 3, mine: 1 }, -1)).toEqual({ up: 12, down: 4, mine: -1 }); expect(press({ up: 0, down: 0, mine: 1 }, 1)).toEqual({ up: 0, down: 0, mine: 0 }); }); test("only a well-formed answer is a tally", () => { expect(fromAnswer({ up: 1, down: 2, mine: -1 })).toEqual({ up: 1, down: 2, mine: -1 }); expect(fromAnswer({ up: 1, down: 2, mine: 2 })).toBeNull(); expect(fromAnswer({ up: "1", down: 2, mine: 0 })).toBeNull(); expect(fromAnswer(null)).toBeNull(); }); }); describe("pebble-vote", () => { test("coal sends -1, URL-encoded, as the form itself would", async () => { const { down } = mount(); submit(down); await sleep(5); const body = calls[0]!.init.body as URLSearchParams; expect(body).toBeInstanceOf(URLSearchParams); expect(body.get("valeur")).toBe("-1"); expect(body.toString()).toContain("valeur=-1"); }); test("a form that asks for multipart sends multipart", () => { const form = document.createElement("form"); form.setAttribute("enctype", "multipart/form-data"); form.innerHTML = ''; expect(bodyOf(form)).toBeInstanceOf(FormData); }); test("marks each side; the server's labels and counts stand", () => { const { host, up, down } = mount(); expect(up.dataset.side).toBe("up"); expect(down.dataset.side).toBe("down"); expect(host.dataset.mine).toBe("0"); expect(state(up)).toEqual({ count: "12", pressed: "false", label: "Cadeau (12)", text: "12" }); }); test("a press is painted at once and posted as the same form data, asking for JSON", async () => { let resolve!: (r: Response) => void; answer = () => new Promise(r => (resolve = r)); const { host, up, down } = mount(); const event = submit(up); expect(event.defaultPrevented).toBe(true); expect(state(up)).toEqual({ count: "13", pressed: "true", label: "Cadeau (13)", text: "13" }); expect(state(down).pressed).toBe("false"); expect(host.hasAttribute("data-busy")).toBe(true); expect(host.getAttribute("aria-busy")).toBe("true"); expect(up.classList.contains("bounce")).toBe(true); expect(calls.length).toBe(1); expect(calls[0]!.url).toEndWith("/suggestions/42/vote"); expect(calls[0]!.init.method).toBe("POST"); expect((calls[0]!.init.headers as Record).Accept).toBe("application/json"); // URL-encoded, as the form itself would post it (not multipart). const body = calls[0]!.init.body as URLSearchParams; expect(body).toBeInstanceOf(URLSearchParams); expect(body.get("valeur")).toBe("1"); expect(body.get("csrf")).toBe("tok"); resolve(json({ up: 20, down: 5, mine: 1 })); await sleep(5); expect(state(up)).toEqual({ count: "20", pressed: "true", label: "Cadeau (20)", text: "20" }); expect(state(down)).toEqual({ count: "5", pressed: "false", label: "Charbon (5)", text: "5" }); expect(host.hasAttribute("data-busy")).toBe(false); }); test("the bounce lasts 400ms", async () => { const { up } = mount(); submit(up); expect(up.classList.contains("bounce")).toBe(true); await sleep(450); expect(up.classList.contains("bounce")).toBe(false); }); test("switching sides moves the vote; pressing the chosen side takes it back", async () => { const { up, down } = mount(); answer = async () => json({ up: 13, down: 3, mine: 1 }); submit(up); await sleep(5); answer = async () => json({ up: 12, down: 4, mine: -1 }); submit(down); expect(state(up)).toMatchObject({ count: "12", pressed: "false" }); expect(state(down)).toMatchObject({ count: "4", pressed: "true", label: "Charbon (4)" }); await sleep(5); answer = async () => json({ up: 12, down: 3, mine: 0 }); submit(down); expect(state(down)).toMatchObject({ count: "3", pressed: "false" }); }); test("presses while a vote is in flight are cancelled and ignored", async () => { let resolve!: (r: Response) => void; answer = () => new Promise(r => (resolve = r)); const { up, down } = mount(); submit(up); const second = submit(down); const third = submit(up); expect(second.defaultPrevented).toBe(true); expect(third.defaultPrevented).toBe(true); expect(calls.length).toBe(1); expect(state(up)).toMatchObject({ count: "13", pressed: "true" }); resolve(json({ up: 13, down: 3, mine: 1 })); await sleep(5); submit(down); expect(calls.length).toBe(2); }); test("a refusal rolls back and toasts the server's error", async () => { answer = async () => json({ error: "Trop de votes, réessayez plus tard." }, 429); const { host, up } = mount(); submit(up); await sleep(5); expect(state(up)).toEqual({ count: "12", pressed: "false", label: "Cadeau (12)", text: "12" }); expect(host.dataset.mine).toBe("0"); expect(toasts).toEqual([{ message: "Trop de votes, réessayez plus tard.", type: "error" }]); }); test("a refusal without a message, or no network, toasts the host's error", async () => { answer = async () => new Response("oops", { status: 500 }); const { up } = mount(); submit(up); await sleep(5); answer = async () => { throw new TypeError("offline"); }; submit(up); await sleep(5); expect(state(up).pressed).toBe("false"); expect(toasts).toEqual([ { message: "Le vote n’a pas passé.", type: "error" }, { message: "Le vote n’a pas passé.", type: "error" }, ]); }); test("a captcha answer, or a 403, rolls back and submits the form natively", async () => { for (const reply of [() => json({ captcha: true }), () => json({ error: "no" }, 403)]) { answer = async () => reply(); const { host, up } = mount(); let submitted = 0; up.form!.submit = () => void submitted++; submit(up); await sleep(5); expect(submitted).toBe(1); expect(state(up).pressed).toBe("false"); expect(host.hasAttribute("data-busy")).toBe(false); expect(toasts).toEqual([]); } }); test("an OK answer that is not a tally keeps the guess", async () => { answer = async () => new Response("

merci

", { status: 200, headers: { "content-type": "text/html" } }); const { up } = mount(); submit(up); await sleep(5); expect(state(up)).toMatchObject({ count: "13", pressed: "true" }); }); test("the field attribute names another input; without two sides the forms are left alone", async () => { const { up } = mount(MARKUP.replaceAll('name="valeur"', 'name="v"').replace(" { expect(styles).toContain("44px"); expect(styles).toContain("prefers-reduced-motion"); expect(styles).toContain("prefers-color-scheme:dark"); expect(styles).toContain("--pebble-vote-up"); }); });