forge
Explore
Log in

Don't you dare go Hollow

hezarfen_frontend

Clone
★ 0

0 watching0 forksTypeScript5.5 MiBdcf123aBurak Boduroğlu2 months ago674 commits

client.test.ts389 lines, 18.4 KiBHistoryRawDownload
1import { afterEach, describe, expect, it, vi } from "vitest";
2import { ApiError, blobClient, client, formatApiError, formatApiErrorMessage, formClient, isModuleDisabledError, onModuleDisabled } from "../../client";
3import { lastFetchCall, mockFetch204, mockFetchBlob, mockFetchError, mockFetchSuccess } from "../helpers/mock-fetch";
4
5describe("client", () => {
6 afterEach(() => {
7 vi.restoreAllMocks();
8 });
9
10 describe("client()", () => {
11 it("makes GET request with correct URL", async () => {
12 mockFetchSuccess({ ok: true });
13 const data = await client("/test");
14 expect(data).toEqual({ ok: true });
15 const [url, init] = lastFetchCall();
16 expect(url).toBe("/api/test");
17 expect(init?.method).toBe("GET");
18 expect(init?.credentials).toBe("same-origin");
19 });
20
21 it("coalesces simultaneous identical GETs without caching later reads", async () => {
22 let resolve!: (value: Response) => void;
23 vi.stubGlobal("fetch", vi.fn(() => new Promise<Response>((done) => { resolve = done; })));
24 const first = client("/shared");
25 const second = client("/shared");
26 expect(globalThis.fetch).toHaveBeenCalledTimes(1);
27 resolve(new Response(JSON.stringify({ ok: true }), { status: 200 }));
28 await expect(Promise.all([first, second])).resolves.toEqual([{ ok: true }, { ok: true }]);
29 mockFetchSuccess({ fresh: true });
30 await expect(client("/shared")).resolves.toEqual({ fresh: true });
31 });
32
33 it("makes POST request with JSON body", async () => {
34 mockFetchSuccess({ ok: true });
35 const body = { foo: "bar" };
36 await client("/test", { method: "POST", body });
37 const [, init] = lastFetchCall();
38 expect(init?.method).toBe("POST");
39 expect(init?.body).toBe(JSON.stringify(body));
40 expect(init?.headers).toEqual({ "Content-Type": "application/json" });
41 });
42
43 it("handles 204 No Content", async () => {
44 mockFetch204();
45 const res = await client("/test");
46 expect(res).toBeUndefined();
47 });
48
49 it("throws ApiError on failure with retryAfter", async () => {
50 mockFetchError(429, { error: "Too Many Requests" }, { "Retry-After": "30" });
51 try {
52 await client("/test");
53 expect.fail("Should have thrown");
54 } catch (err) {
55 expect(err).toBeInstanceOf(ApiError);
56 if (err instanceof ApiError) {
57 expect(err.status).toBe(429);
58 expect(err.message).toBe("Too Many Requests");
59 expect(err.retryAfter).toBe(30);
60 }
61 }
62 });
63
64 it("throws ApiError with default message if none provided", async () => {
65 mockFetchError(500);
66 try {
67 await client("/test");
68 expect.fail("Should have thrown");
69 } catch (err) {
70 expect(err).toBeInstanceOf(ApiError);
71 if (err instanceof ApiError) {
72 expect(err.status).toBe(500);
73 expect(err.message).toBe("Error"); // From statusText in mock
74 }
75 }
76 });
77 });
78
79 describe("switched-off modules", () => {
80 it("tags a 403 carrying `module` and tells listeners", async () => {
81 const heard: string[] = [];
82 const stop = onModuleDisabled((module) => heard.push(module));
83 mockFetchError(403, { error: "forbidden", module: "notes" });
84 const err = await client("/notes").catch((e: unknown) => e);
85 stop();
86 expect(isModuleDisabledError(err)).toBe(true);
87 expect((err as ApiError).module).toBe("notes");
88 expect(heard).toEqual(["notes"]);
89 expect(formatApiError(err, "tr")).toBe("Bu özellik okulunuzda şu an kapalı.");
90 });
91
92 it("leaves an ordinary 403 as a permissions refusal", async () => {
93 const heard: string[] = [];
94 const stop = onModuleDisabled((module) => heard.push(module));
95 mockFetchError(403, { error: "forbidden" });
96 const err = await client("/users").catch((e: unknown) => e);
97 stop();
98 expect(isModuleDisabledError(err)).toBe(false);
99 expect(heard).toEqual([]);
100 });
101 });
102
103 describe("client() timeout", () => {
104 // hang until whatever signal fetch was given aborts
105 const hangingFetch = () =>
106 vi.spyOn(globalThis, "fetch").mockImplementation(
107 (_url, init?: RequestInit) =>
108 new Promise<Response>((_resolve, reject) => {
109 const signal = init?.signal;
110 if (!signal) return; // no deadline at all -> test times out, which is the bug
111 signal.addEventListener("abort", () => reject(signal.reason));
112 }),
113 );
114
115 it("fails a hung request as a localized ApiError instead of hanging forever", async () => {
116 // shrink the real deadline; everything else (AbortSignal.any, the catch) runs for real
117 const realTimeout = AbortSignal.timeout.bind(AbortSignal);
118 vi.spyOn(AbortSignal, "timeout").mockImplementation(() => realTimeout(5));
119 hangingFetch();
120 await expect(client("/slow")).rejects.toMatchObject({ name: "ApiError", status: 408 });
121 try {
122 await client("/slow");
123 } catch (err) {
124 expect(formatApiError(err, "tr")).toBe("Sunucu zamanında yanıt vermedi. Bağlantını kontrol edip tekrar dene.");
125 expect(formatApiError(err, "en")).toBe("The server did not respond in time. Check your connection and try again.");
126 }
127 });
128
129 // headers arrive promptly, the body stalls — the multi-MB shell feed on a
130 // school connection. The deadline lands while res.text() is streaming.
131 const stallingBodyFetch = () =>
132 vi.spyOn(globalThis, "fetch").mockImplementation((_url, init?: RequestInit) => {
133 const signal = init?.signal;
134 const stream = new ReadableStream({
135 start(ctrl) {
136 ctrl.enqueue(new TextEncoder().encode('{"items":['));
137 signal?.addEventListener("abort", () => ctrl.error(signal.reason));
138 },
139 });
140 return Promise.resolve(new Response(stream, { status: 200 }));
141 });
142
143 it("fails a timeout during body streaming as ApiError 408, not a raw DOMException", async () => {
144 const realTimeout = AbortSignal.timeout.bind(AbortSignal);
145 vi.spyOn(AbortSignal, "timeout").mockImplementation(() => realTimeout(5));
146 stallingBodyFetch();
147 await expect(client("/big-feed")).rejects.toMatchObject({ name: "ApiError", status: 408 });
148 try {
149 await client("/big-feed");
150 } catch (err) {
151 expect(formatApiError(err, "tr")).toBe("Sunucu zamanında yanıt vermedi. Bağlantını kontrol edip tekrar dene.");
152 }
153 });
154
155 it("still surfaces a caller abort mid-body as AbortError, not a timeout", async () => {
156 stallingBodyFetch();
157 const ctrl = new AbortController();
158 const pending = client("/big-feed", { signal: ctrl.signal });
159 await Promise.resolve();
160 ctrl.abort();
161 await expect(pending).rejects.toMatchObject({ name: "AbortError" });
162 });
163
164 it("still surfaces a caller abort as AbortError, not a timeout", async () => {
165 hangingFetch();
166 const ctrl = new AbortController();
167 const pending = client("/slow", { signal: ctrl.signal });
168 ctrl.abort();
169 await expect(pending).rejects.toMatchObject({ name: "AbortError" });
170 });
171 });
172
173 describe("formClient()", () => {
174 it("makes POST request with FormData", async () => {
175 mockFetchSuccess({ ok: true });
176 const fd = new FormData();
177 fd.append("file", new Blob(["test"]), "test.txt");
178 await formClient("/test-form", fd);
179 const [url, init] = lastFetchCall();
180 expect(url).toBe("/api/test-form");
181 expect(init?.method).toBe("POST");
182 expect(init?.body).toBe(fd);
183 });
184
185 it("throws ApiError on failure", async () => {
186 mockFetchError(400, { error: "Bad form" });
187 try {
188 await formClient("/test-form", new FormData());
189 expect.fail("Should have thrown");
190 } catch (err) {
191 expect(err).toBeInstanceOf(ApiError);
192 if (err instanceof ApiError) {
193 expect(err.status).toBe(400);
194 expect(err.message).toBe("Bad form");
195 }
196 }
197 });
198 });
199
200 describe("blobClient()", () => {
201 it("fetches blob successfully", async () => {
202 const blob = new Blob(["hello"], { type: "text/plain" });
203 mockFetchBlob(blob);
204 const res = await blobClient("/test-blob");
205 expect(res).toBeInstanceOf(Blob);
206 expect(res.type).toBe("text/plain");
207 const [url] = lastFetchCall();
208 expect(url).toBe("/api/test-blob");
209 });
210
211 it("throws ApiError on failure", async () => {
212 mockFetchError(404, { error: "Not found" });
213 try {
214 await blobClient("/test-blob");
215 expect.fail("Should have thrown");
216 } catch (err) {
217 expect(err).toBeInstanceOf(ApiError);
218 if (err instanceof ApiError) {
219 expect(err.status).toBe(404);
220 expect(err.message).toBe("Not found");
221 }
222 }
223 });
224 });
225
226 describe("formatApiErrorMessage", () => {
227 it("translates known messages", () => {
228 expect(formatApiErrorMessage("unauthorized", "en")).toBe("Sign in to continue.");
229 expect(formatApiErrorMessage("unauthorized", "tr")).toBe("Devam etmek için giriş yap.");
230 expect(formatApiErrorMessage("forbidden", "tr")).toBe("Bu işlem için yetkin yok.");
231 });
232
233 it("localizes the settings duplicate-entry error (Turkish casing)", () => {
234 // exact backend strings from settings.rs validate_list — a miss here renders
235 // "İşlem tamamlanamadı: <raw English>" to a Turkish admin
236 const kinds = "exam_kinds: two entries are the same word apart from upper/lower case or Turkish letters — keep only one of them";
237 const statuses =
238 "attendance_statuses: two entries are the same word apart from upper/lower case or Turkish letters — keep only one of them";
239 expect(formatApiErrorMessage(kinds, "tr")).toBe(
240 "İki sınav türü, büyük/küçük harf veya Türkçe harf farkı dışında aynı. Sadece birini bırak.",
241 );
242 expect(formatApiErrorMessage(statuses, "tr")).toBe(
243 "İki yoklama durumu, büyük/küçük harf veya Türkçe harf farkı dışında aynı. Sadece birini bırak.",
244 );
245 expect(formatApiErrorMessage(kinds, "en")).toBe(
246 "Two exam kinds are the same word apart from upper/lower case or Turkish letters. Keep only one of them.",
247 );
248 });
249
250 it("localizes slot-overlap conflicts (no half-English fallback)", () => {
251 // exact backend strings (lowercase) must map, not fall through to "İşlem tamamlanamadı: <english>"
252 expect(formatApiErrorMessage("this time overlaps a slot you have already published", "tr")).toBe(
253 "Bu zaman aralığı, daha önce yayınladığın bir müsaitlikle çakışıyor.",
254 );
255 expect(formatApiErrorMessage("a repeated slot overlaps one you have already published", "tr")).toBe(
256 "Tekrarlanan müsaitliklerden biri, daha önce yayınladığın bir müsaitlikle çakışıyor.",
257 );
258 expect(formatApiErrorMessage("the repeated slots overlap each other", "en")).toBe("The repeated slots overlap each other.");
259 // a 409 ApiError carrying the backend message resolves the same way
260 expect(formatApiError(new ApiError(409, "this time overlaps a slot you have already published"), "tr")).toBe(
261 "Bu zaman aralığı, daha önce yayınladığın bir müsaitlikle çakışıyor.",
262 );
263 });
264
265 it("localizes question-bank permission and attempt conflicts", () => {
266 // exact backend strings from web/bank_questions.rs + web/exams.rs
267 expect(formatApiErrorMessage("only the template's owner or an admin can change it", "tr")).toBe(
268 "Bu şablonu yalnızca onu oluşturan öğretmen (veya bir yönetici) değiştirebilir.",
269 );
270 expect(
271 formatApiErrorMessage("only the course creator, an assigned teacher, or a manager/admin can save questions to the bank", "en"),
272 ).toBe("Only this course's teachers or a manager can save this question to the bank.");
273 expect(formatApiError(new ApiError(409, "cannot change questions after attempts have started"), "tr")).toBe(
274 "Öğrenciler bu sınava başladığı için soruları artık değiştirilemez.",
275 );
276 expect(
277 formatApiErrorMessage("only the course creator, an assigned teacher, or a manager/admin can author questions", "tr"),
278 ).toBe("Bu sınava yalnızca dersin öğretmenleri veya bir müdür soru ekleyebilir.");
279 });
280
281 it("falls back to a clean localized message for unmapped errors (no raw leak)", () => {
282 expect(formatApiErrorMessage("custom error occurred", "en")).toBe(
283 "Something went wrong. Please check your input and try again.",
284 );
285 expect(formatApiErrorMessage("custom error occurred", "tr")).toBe(
286 "İşlem tamamlanamadı. Lütfen bilgileri kontrol edip tekrar dene.",
287 );
288 });
289
290 it("localizes backend max-length validation messages", () => {
291 const message = "Content must be at most 10000 characters (got 220896)";
292 expect(formatApiErrorMessage(message, "en")).toBe("Content must be at most 10,000 characters. Currently 220,896 characters.");
293 expect(formatApiErrorMessage(message, "tr")).toBe("İçerik en fazla 10.000 karakter olmalı. Şu an 220.896 karakter.");
294 });
295 });
296
297 describe("formatApiError", () => {
298 it("formats 429 with retry after", () => {
299 const err = new ApiError(429, "Too many", 10);
300 expect(formatApiError(err, "en")).toBe("Try again in 10s.");
301 expect(formatApiError(err, "tr")).toBe("10 sn sonra tekrar dene.");
302 });
303
304 it("formats 401, 403, 404", () => {
305 expect(formatApiError(new ApiError(401, ""), "en")).toBe("Sign in to continue.");
306 expect(formatApiError(new ApiError(403, ""), "tr")).toBe("Bu işlem için yetkin yok.");
307 expect(formatApiError(new ApiError(404, ""), "en")).toBe("The requested record was not found.");
308 });
309
310 it("prefers the table entry over the per-status generic message", () => {
311 // the whole 403 table was dead code: every 403 rendered "forbidden"
312 expect(formatApiError(new ApiError(403, "only the template's owner or an admin can change it"), "tr")).toBe(
313 "Bu şablonu yalnızca onu oluşturan öğretmen (veya bir yönetici) değiştirebilir.",
314 );
315 expect(
316 formatApiError(new ApiError(403, "only the course creator, an assigned teacher, or a manager/admin can author questions"), "tr"),
317 ).toBe("Bu sınava yalnızca dersin öğretmenleri veya bir müdür soru ekleyebilir.");
318 expect(
319 formatApiError(
320 new ApiError(403, "only the course creator, an assigned teacher, or a manager/admin can save questions to the bank"),
321 "en",
322 ),
323 ).toBe("Only this course's teachers or a manager can save this question to the bank.");
324 // same ordering bug shape for 404 ("course not found" / "exam not found")
325 expect(formatApiError(new ApiError(404, "exam not found"), "tr")).toBe("Sınav bulunamadı.");
326 expect(formatApiError(new ApiError(404, "course not found"), "en")).toBe("Course not found.");
327 // unmatched messages still fall back to the generic per-status message
328 expect(formatApiError(new ApiError(403, "some brand new refusal"), "tr")).toBe("Bu işlem için yetkin yok.");
329 expect(formatApiError(new ApiError(404, ""), "en")).toBe("The requested record was not found.");
330 });
331
332 it("localizes appointment booking and decision conflicts", () => {
333 // exact backend strings from domain/appointment.rs — a miss renders
334 // "İşlem tamamlanamadı: <English>"
335 const cases: Array<[string, string]> = [
336 ["the slot is already booked", "Bu saati senden önce başkası aldı."],
337 ["the slot has already started", "Bu saat başladığı için artık randevu alınamaz."],
338 ["you already have an appointment at that time", "O saatte zaten bir randevun var."],
339 ["the appointment is already settled", "Bu randevu zaten sonuçlanmış."],
340 ["the appointment has already started", "Bu randevu çoktan başladı."],
341 ["that time has already started", "O saat çoktan başladı. Daha ileri bir saat seç."],
342 ["no time has been proposed", "Bu randevu için henüz bir saat önerilmedi."],
343 ["the appointment is no longer pending", "Bu randevu artık yanıt bekliyor değil."],
344 ];
345 for (const [backend, turkish] of cases) {
346 expect(formatApiError(new ApiError(409, backend), "tr")).toBe(turkish);
347 expect(formatApiError(new ApiError(409, backend), "en")).not.toMatch(/^İşlem/);
348 expect(formatApiErrorMessage(backend, "en")).toMatch(/\.$/);
349 }
350 });
351
352 it("localizes the refresh-from-bank validation error", () => {
353 // ValidationError::Invalid renders "{field}: {reason}" (web/exams.rs:2013)
354 expect(formatApiError(new ApiError(400, "question: this question did not come from a bank template"), "tr")).toBe(
355 "Bu soru bir banka şablonundan kopyalanmadığı için yenilenecek bir kaynağı yok.",
356 );
357 expect(formatApiError(new ApiError(400, "question: this question did not come from a bank template"), "en")).toBe(
358 "This question was not copied from a bank template, so there is nothing to refresh it from.",
359 );
360 });
361
362 it("formats 500+", () => {
363 expect(formatApiError(new ApiError(500, ""), "en")).toBe("Server error. Please try again.");
364 expect(formatApiError(new ApiError(503, ""), "tr")).toBe("Sunucuda bir sorun oluştu. Lütfen tekrar dene.");
365 });
366
367 it("formats 422 backend validation messages", () => {
368 const err = new ApiError(422, "Title must be at most 200 characters (got 250)");
369 expect(formatApiError(err, "tr")).toBe("Başlık en fazla 200 karakter olmalı. Şu an 250 karakter.");
370 });
371
372 it("formats generic Error", () => {
373 expect(formatApiError(new Error("generic"), "en")).toBe("Something went wrong. Please check your input and try again.");
374 expect(formatApiError(new Error("generic"), "tr")).toBe("İşlem tamamlanamadı. Lütfen bilgileri kontrol edip tekrar dene.");
375 });
376
377 it("does not expose network, runtime, or provider errors to users", () => {
378 expect(formatApiError(new TypeError("Failed to fetch"), "tr")).toBe(
379 "Sunucuya ulaşılamadı. Bağlantını kontrol edip tekrar dene.",
380 );
381 expect(formatApiError(new TypeError("Cannot read properties of null (reading 'user')"), "tr")).toBe(
382 "Sayfa yüklenirken bir sorun oluştu. Sayfayı yeniden yükleyip tekrar dene.",
383 );
384 expect(formatApiError(new Error("useAuth must be used within AuthProvider"), "en")).toBe(
385 "Something went wrong while loading the page. Reload the page and try again.",
386 );
387 });
388 });
389});