tobogganSe connecter

library

Prebuilt pebble components: drop-in custom elements, no compiler needed

Clone avec HTTPS, un jeton personnel en mot de passe, ou avec SSH, une clé ajoutée dans vos paramètres.

Dernier runAucun
0Étoiles
0Forks
2Issues
256 lignes · 10606 octetsBrut · Historique
1// <pebble-vote>: the optimistic press, reconciliation with the server's tally,
2// rollback with a toast, the captcha fallback to a native submission, and the
3// in-flight guard. fetch is a fake per test; the tally arithmetic is also
4// proven on its own.
5import { afterEach, beforeEach, describe, expect, test } from "bun:test";
6import { bodyOf, fromAnswer, press } from "../packages/vote/index";
7import styles from "../packages/vote/vote.css";
8
9const sleep = (ms = 0) => new Promise(resolve => setTimeout(resolve, ms));
10
11const MARKUP = `<pebble-vote error="Le vote n’a pas passé.">
12 <form method="post" action="/suggestions/42/vote">
13 <input type="hidden" name="valeur" value="1"><input type="hidden" name="csrf" value="tok">
14 <button aria-pressed="false" data-count="12" data-label="Cadeau" aria-label="Cadeau (12)">🎁 <span data-count-label>12</span></button>
15 </form>
16 <form method="post" action="/suggestions/42/vote">
17 <input type="hidden" name="valeur" value="-1"><input type="hidden" name="csrf" value="tok">
18 <button aria-pressed="false" data-count="3" data-label="Charbon" aria-label="Charbon (3)">⚫ <span data-count-label>3</span></button>
19 </form>
20</pebble-vote>`;
21
22interface Call {
23 url: string;
24 init: RequestInit;
25}
26let calls: Call[] = [];
27let answer: () => Promise<Response>;
28let release: (() => void) | null = null;
29const realFetch = globalThis.fetch;
30const toasts: unknown[] = [];
31const onToast = (event: Event) => toasts.push((event as CustomEvent).detail);
32
33const json = (body: unknown, status = 200) =>
34 new Response(JSON.stringify(body), { status, headers: { "content-type": "application/json" } });
35
36beforeEach(() => {
37 calls = [];
38 toasts.length = 0;
39 answer = async () => json({ up: 13, down: 3, mine: 1 });
40 globalThis.fetch = (async (url: string | URL, init: RequestInit = {}) => {
41 calls.push({ url: String(url), init });
42 return answer();
43 }) as typeof fetch;
44 window.addEventListener("toast", onToast);
45});
46
47afterEach(async () => {
48 globalThis.fetch = realFetch;
49 window.removeEventListener("toast", onToast);
50 document.body.textContent = "";
51 await sleep(0); // define() releases one macrotask later
52});
53
54// Built detached, then attached: the element reads its children when it connects
55// (a browser's innerHTML and a deferred module script both guarantee that).
56const mount = (html = MARKUP) => {
57 const wrap = document.createElement("div");
58 wrap.innerHTML = html;
59 document.body.appendChild(wrap);
60 const host = wrap.querySelector("pebble-vote") as HTMLElement;
61 const [up, down] = [...host.querySelectorAll("button")] as HTMLButtonElement[];
62 return { host, up: up!, down: down! };
63};
64
65const state = (b: HTMLButtonElement) => ({
66 count: b.dataset.count,
67 pressed: b.getAttribute("aria-pressed"),
68 label: b.getAttribute("aria-label"),
69 text: b.querySelector("[data-count-label]")!.textContent,
70});
71
72const submit = (button: HTMLButtonElement) => {
73 const form = button.form!;
74 const event = new Event("submit", { bubbles: true, cancelable: true });
75 form.dispatchEvent(event);
76 return event;
77};
78
79describe("the tally", () => {
80 test("pressing a side casts, pressing it again takes it back, the other side moves it", () => {
81 expect(press({ up: 12, down: 3, mine: 0 }, 1)).toEqual({ up: 13, down: 3, mine: 1 });
82 expect(press({ up: 13, down: 3, mine: 1 }, 1)).toEqual({ up: 12, down: 3, mine: 0 });
83 expect(press({ up: 13, down: 3, mine: 1 }, -1)).toEqual({ up: 12, down: 4, mine: -1 });
84 expect(press({ up: 0, down: 0, mine: 1 }, 1)).toEqual({ up: 0, down: 0, mine: 0 });
85 });
86
87 test("only a well-formed answer is a tally", () => {
88 expect(fromAnswer({ up: 1, down: 2, mine: -1 })).toEqual({ up: 1, down: 2, mine: -1 });
89 expect(fromAnswer({ up: 1, down: 2, mine: 2 })).toBeNull();
90 expect(fromAnswer({ up: "1", down: 2, mine: 0 })).toBeNull();
91 expect(fromAnswer(null)).toBeNull();
92 });
93});
94
95describe("pebble-vote", () => {
96 test("coal sends -1, URL-encoded, as the form itself would", async () => {
97 const { down } = mount();
98 submit(down);
99 await sleep(5);
100 const body = calls[0]!.init.body as URLSearchParams;
101 expect(body).toBeInstanceOf(URLSearchParams);
102 expect(body.get("valeur")).toBe("-1");
103 expect(body.toString()).toContain("valeur=-1");
104 });
105
106 test("a form that asks for multipart sends multipart", () => {
107 const form = document.createElement("form");
108 form.setAttribute("enctype", "multipart/form-data");
109 form.innerHTML = '<input name="valeur" value="-1">';
110 expect(bodyOf(form)).toBeInstanceOf(FormData);
111 });
112
113 test("marks each side; the server's labels and counts stand", () => {
114 const { host, up, down } = mount();
115 expect(up.dataset.side).toBe("up");
116 expect(down.dataset.side).toBe("down");
117 expect(host.dataset.mine).toBe("0");
118 expect(state(up)).toEqual({ count: "12", pressed: "false", label: "Cadeau (12)", text: "12" });
119 });
120
121 test("a press is painted at once and posted as the same form data, asking for JSON", async () => {
122 let resolve!: (r: Response) => void;
123 answer = () => new Promise(r => (resolve = r));
124 const { host, up, down } = mount();
125 const event = submit(up);
126 expect(event.defaultPrevented).toBe(true);
127 expect(state(up)).toEqual({ count: "13", pressed: "true", label: "Cadeau (13)", text: "13" });
128 expect(state(down).pressed).toBe("false");
129 expect(host.hasAttribute("data-busy")).toBe(true);
130 expect(host.getAttribute("aria-busy")).toBe("true");
131 expect(up.classList.contains("bounce")).toBe(true);
132
133 expect(calls.length).toBe(1);
134 expect(calls[0]!.url).toEndWith("/suggestions/42/vote");
135 expect(calls[0]!.init.method).toBe("POST");
136 expect((calls[0]!.init.headers as Record<string, string>).Accept).toBe("application/json");
137 // URL-encoded, as the form itself would post it (not multipart).
138 const body = calls[0]!.init.body as URLSearchParams;
139 expect(body).toBeInstanceOf(URLSearchParams);
140 expect(body.get("valeur")).toBe("1");
141 expect(body.get("csrf")).toBe("tok");
142
143 resolve(json({ up: 20, down: 5, mine: 1 }));
144 await sleep(5);
145 expect(state(up)).toEqual({ count: "20", pressed: "true", label: "Cadeau (20)", text: "20" });
146 expect(state(down)).toEqual({ count: "5", pressed: "false", label: "Charbon (5)", text: "5" });
147 expect(host.hasAttribute("data-busy")).toBe(false);
148 });
149
150 test("the bounce lasts 400ms", async () => {
151 const { up } = mount();
152 submit(up);
153 expect(up.classList.contains("bounce")).toBe(true);
154 await sleep(450);
155 expect(up.classList.contains("bounce")).toBe(false);
156 });
157
158 test("switching sides moves the vote; pressing the chosen side takes it back", async () => {
159 const { up, down } = mount();
160 answer = async () => json({ up: 13, down: 3, mine: 1 });
161 submit(up);
162 await sleep(5);
163 answer = async () => json({ up: 12, down: 4, mine: -1 });
164 submit(down);
165 expect(state(up)).toMatchObject({ count: "12", pressed: "false" });
166 expect(state(down)).toMatchObject({ count: "4", pressed: "true", label: "Charbon (4)" });
167 await sleep(5);
168 answer = async () => json({ up: 12, down: 3, mine: 0 });
169 submit(down);
170 expect(state(down)).toMatchObject({ count: "3", pressed: "false" });
171 });
172
173 test("presses while a vote is in flight are cancelled and ignored", async () => {
174 let resolve!: (r: Response) => void;
175 answer = () => new Promise(r => (resolve = r));
176 const { up, down } = mount();
177 submit(up);
178 const second = submit(down);
179 const third = submit(up);
180 expect(second.defaultPrevented).toBe(true);
181 expect(third.defaultPrevented).toBe(true);
182 expect(calls.length).toBe(1);
183 expect(state(up)).toMatchObject({ count: "13", pressed: "true" });
184 resolve(json({ up: 13, down: 3, mine: 1 }));
185 await sleep(5);
186 submit(down);
187 expect(calls.length).toBe(2);
188 });
189
190 test("a refusal rolls back and toasts the server's error", async () => {
191 answer = async () => json({ error: "Trop de votes, réessayez plus tard." }, 429);
192 const { host, up } = mount();
193 submit(up);
194 await sleep(5);
195 expect(state(up)).toEqual({ count: "12", pressed: "false", label: "Cadeau (12)", text: "12" });
196 expect(host.dataset.mine).toBe("0");
197 expect(toasts).toEqual([{ message: "Trop de votes, réessayez plus tard.", type: "error" }]);
198 });
199
200 test("a refusal without a message, or no network, toasts the host's error", async () => {
201 answer = async () => new Response("oops", { status: 500 });
202 const { up } = mount();
203 submit(up);
204 await sleep(5);
205 answer = async () => {
206 throw new TypeError("offline");
207 };
208 submit(up);
209 await sleep(5);
210 expect(state(up).pressed).toBe("false");
211 expect(toasts).toEqual([
212 { message: "Le vote n’a pas passé.", type: "error" },
213 { message: "Le vote n’a pas passé.", type: "error" },
214 ]);
215 });
216
217 test("a captcha answer, or a 403, rolls back and submits the form natively", async () => {
218 for (const reply of [() => json({ captcha: true }), () => json({ error: "no" }, 403)]) {
219 answer = async () => reply();
220 const { host, up } = mount();
221 let submitted = 0;
222 up.form!.submit = () => void submitted++;
223 submit(up);
224 await sleep(5);
225 expect(submitted).toBe(1);
226 expect(state(up).pressed).toBe("false");
227 expect(host.hasAttribute("data-busy")).toBe(false);
228 expect(toasts).toEqual([]);
229 }
230 });
231
232 test("an OK answer that is not a tally keeps the guess", async () => {
233 answer = async () => new Response("<p>merci</p>", { status: 200, headers: { "content-type": "text/html" } });
234 const { up } = mount();
235 submit(up);
236 await sleep(5);
237 expect(state(up)).toMatchObject({ count: "13", pressed: "true" });
238 });
239
240 test("the field attribute names another input; without two sides the forms are left alone", async () => {
241 const { up } = mount(MARKUP.replaceAll('name="valeur"', 'name="v"').replace("<pebble-vote", '<pebble-vote field="v"'));
242 expect(up.dataset.side).toBe("up");
243 document.body.textContent = "";
244 await sleep(0);
245 const lone = mount(MARKUP.replaceAll('name="valeur"', 'name="v"'));
246 expect(lone.up.dataset.side).toBeUndefined();
247 expect(submit(lone.up).defaultPrevented).toBe(false);
248 });
249
250 test("the sheet: 44px targets, the reduced-motion opt-out, dark defaults", () => {
251 expect(styles).toContain("44px");
252 expect(styles).toContain("prefers-reduced-motion");
253 expect(styles).toContain("prefers-color-scheme:dark");
254 expect(styles).toContain("--pebble-vote-up");
255 });
256});