forge
Explore
Log in

Don't you dare go Hollow

hezarfen_frontend

Clone
★ 0

0 watching0 forksTypeScript5.5 MiB5fcd955Burak Boduroğlu2 months ago730 commits

client.test.ts463 lines, 23.6 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("names the failure and quotes the server's reason for unmapped errors", () => {
282 expect(formatApiErrorMessage("custom error occurred", "en")).toBe(
283 "The action could not be completed. Server said: “custom error occurred”.",
284 );
285 expect(formatApiErrorMessage("custom error occurred", "tr")).toBe(
286 "İşlem tamamlanamadı. Sunucu yanıtı: “custom error occurred”.",
287 );
288 expect(formatApiError(new ApiError(409, "slot taken by a later edit"), "tr")).toBe(
289 "İşlem kaydın şu anki durumuyla çakışıyor. Sunucu yanıtı: “slot taken by a later edit”.",
290 );
291 expect(formatApiError(new ApiError(400, ""), "tr")).toBe(
292 "Sunucu isteği geçersiz buldu. Bilgileri kontrol edip tekrar dene.",
293 );
294 });
295
296 it("translates request bodies the backend could not decode", () => {
297 expect(
298 formatApiError(new ApiError(422, "Failed to deserialize the JSON body into the target type: missing field `title` at line 1 column 2"), "tr"),
299 ).toBe("“Başlık” alanı eksik. Doldurup tekrar dene.");
300 expect(
301 formatApiError(new ApiError(422, "Failed to deserialize the JSON body into the target type: format: unknown variant `kisa`, expected `duz_okuma` or `tek_ogretici` at line 1 column 20"), "tr"),
302 ).toBe("“kisa” geçerli bir seçenek değil. Geçerli değerler: duz_okuma or tek_ogretici.");
303 expect(
304 formatApiError(new ApiError(422, "Failed to deserialize the JSON body into the target type: ders_saati: invalid type: string \"3\", expected u32 at line 1 column 18"), "tr"),
305 ).toBe("“Ders saati” alanının biçimi hatalı: u32 bekleniyordu, string \"3\" geldi.");
306 });
307
308 it("localizes backend max-length validation messages", () => {
309 const message = "Content must be at most 10000 characters (got 220896)";
310 expect(formatApiErrorMessage(message, "en")).toBe("Content must be at most 10,000 characters. Currently 220,896 characters.");
311 expect(formatApiErrorMessage(message, "tr")).toBe("İçerik en fazla 10.000 karakter olmalı. Şu an 220.896 karakter.");
312 });
313 });
314
315 describe("formatApiError", () => {
316 it("formats 429 with retry after", () => {
317 const err = new ApiError(429, "Too many", 10);
318 expect(formatApiError(err, "en")).toBe("Try again in 10s.");
319 expect(formatApiError(err, "tr")).toBe("10 sn sonra tekrar dene.");
320 });
321
322 it("formats 401, 403, 404", () => {
323 expect(formatApiError(new ApiError(401, ""), "en")).toBe("Sign in to continue.");
324 expect(formatApiError(new ApiError(403, ""), "tr")).toBe("Bu işlem için yetkin yok.");
325 expect(formatApiError(new ApiError(404, ""), "en")).toBe("The requested record was not found.");
326 });
327
328 it("prefers the table entry over the per-status generic message", () => {
329 // the whole 403 table was dead code: every 403 rendered "forbidden"
330 expect(formatApiError(new ApiError(403, "only the template's owner or an admin can change it"), "tr")).toBe(
331 "Bu şablonu yalnızca onu oluşturan öğretmen (veya bir yönetici) değiştirebilir.",
332 );
333 expect(
334 formatApiError(new ApiError(403, "only the course creator, an assigned teacher, or a manager/admin can author questions"), "tr"),
335 ).toBe("Bu sınava yalnızca dersin öğretmenleri veya bir müdür soru ekleyebilir.");
336 expect(
337 formatApiError(
338 new ApiError(403, "only the course creator, an assigned teacher, or a manager/admin can save questions to the bank"),
339 "en",
340 ),
341 ).toBe("Only this course's teachers or a manager can save this question to the bank.");
342 // same ordering bug shape for 404 ("course not found" / "exam not found")
343 expect(formatApiError(new ApiError(404, "exam not found"), "tr")).toBe("Sınav bulunamadı.");
344 expect(formatApiError(new ApiError(404, "course not found"), "en")).toBe("Course not found.");
345 // unmatched messages still fall back to the generic per-status message
346 expect(formatApiError(new ApiError(403, "some brand new refusal"), "tr")).toBe("Bu işlem için yetkin yok.");
347 expect(formatApiError(new ApiError(404, ""), "en")).toBe("The requested record was not found.");
348 });
349
350 it("localizes appointment booking and decision conflicts", () => {
351 // exact backend strings from domain/appointment.rs — a miss renders
352 // "İşlem tamamlanamadı: <English>"
353 const cases: Array<[string, string]> = [
354 ["the slot is already booked", "Bu saati senden önce başkası aldı."],
355 ["the slot has already started", "Bu saat başladığı için artık randevu alınamaz."],
356 ["you already have an appointment at that time", "O saatte zaten bir randevun var."],
357 ["the appointment is already settled", "Bu randevu zaten sonuçlanmış."],
358 ["the appointment has already started", "Bu randevu çoktan başladı."],
359 ["that time has already started", "O saat çoktan başladı. Daha ileri bir saat seç."],
360 ["no time has been proposed", "Bu randevu için henüz bir saat önerilmedi."],
361 ["the appointment is no longer pending", "Bu randevu artık yanıt bekliyor değil."],
362 ];
363 for (const [backend, turkish] of cases) {
364 expect(formatApiError(new ApiError(409, backend), "tr")).toBe(turkish);
365 expect(formatApiError(new ApiError(409, backend), "en")).not.toMatch(/^İşlem/);
366 expect(formatApiErrorMessage(backend, "en")).toMatch(/\.$/);
367 }
368 });
369
370 it("localizes the refresh-from-bank validation error", () => {
371 // ValidationError::Invalid renders "{field}: {reason}" (web/exams.rs:2013)
372 expect(formatApiError(new ApiError(400, "question: this question did not come from a bank template"), "tr")).toBe(
373 "Bu soru bir banka şablonundan kopyalanmadığı için yenilenecek bir kaynağı yok.",
374 );
375 expect(formatApiError(new ApiError(400, "question: this question did not come from a bank template"), "en")).toBe(
376 "This question was not copied from a bank template, so there is nothing to refresh it from.",
377 );
378 });
379
380 it("localizes still-linked and archived conflicts instead of quoting them", () => {
381 const yearLinked = new ApiError(409, "classes and terms are still linked to this academic year — unlink them first");
382 expect(formatApiError(yearLinked, "tr")).toBe(
383 "Bu eğitim yılına bağlı şubeler ve dönemler var. Silmeden önce onları başka bir yıla taşı veya sil.",
384 );
385 expect(formatApiError(yearLinked, "en")).toBe(
386 "Classes and terms are still linked to this academic year. Move them to another year or delete them before deleting this one.",
387 );
388 // a reworded tail or a curly apostrophe still lands on the same wording
389 expect(formatApiError(new ApiError(409, "Terms are still linked to this year."), "tr")).toMatch(/^Bu eğitim yılına bağlı/);
390
391 const cases: Array<[string, RegExp]> = [
392 ["this class’s academic year is archived — past years are read-only", /^Bu eğitim yılı arşivlendi\./],
393 ["students or instances are still on this class", /^Bu şubede hâlâ öğrenci veya ders var\./],
394 ["a class still teaches this course", /^Bu ders hâlâ bir şubede okutuluyor/],
395 ["exams or frozen karnes still belong to this term", /^Bu döneme bağlı sınavlar/],
396 ["exam questions or homework still reference this subject", /^Sınav soruları veya ödevler/],
397 ["the menu still has live bookings", /^Bu menüde hâlâ rezervasyonlar var\./],
398 ["the slot has a pending or approved booking", /^Bu saatte bekleyen veya onaylanmış/],
399 ["the plan is already assigned to a student", /^Bu ödeme planı bir öğrenciye atanmış/],
400 ["that account is the school's last admin", /^Bu hesap okulun son yöneticisi\./],
401 ["a blueprint already exists for that grade", /^Bu seviye için zaten bir şablon var\./],
402 ["the year changed under concurrent edits (re-read and retry)", /^Bu kayıt sen düzenlerken değişti\./],
403 ];
404 for (const [backend, turkish] of cases) {
405 expect(formatApiError(new ApiError(409, backend), "tr")).toMatch(turkish);
406 expect(formatApiError(new ApiError(409, backend), "en")).not.toMatch(/Server said/);
407 }
408 // the exact table still wins over a looser pattern
409 expect(formatApiError(new ApiError(409, "bank questions still reference this subject — re-tag or delete them first"), "en")).toBe(
410 "Question bank templates still use this subject. Re-tag or delete them first.",
411 );
412 });
413
414 it("prefers the machine code over the prose when the backend sends one", () => {
415 expect(formatApiError(new ApiError(409, "class is at its course ceiling (12)", null, null, "class_at_course_ceiling"), "tr")).toBe(
416 "Bu şube en fazla ders sayısına ulaştı. Yeni ders eklemeden önce şubeden bir ders çıkar.",
417 );
418 expect(formatApiError(new ApiError(409, "some reworded text", null, null, "student_number_taken"), "en")).toBe(
419 "Another student already has this student number. Enter a different number.",
420 );
421 expect(formatApiError(new ApiError(409, "whatever", null, null, "academic_year_archived"), "tr")).toMatch(/^Bu eğitim yılı arşivlendi\./);
422 // an unknown code falls through to the prose and then the quoted fallback
423 expect(formatApiError(new ApiError(409, "slot taken by a later edit", null, null, "brand_new_code"), "tr")).toBe(
424 "İşlem kaydın şu anki durumuyla çakışıyor. Sunucu yanıtı: “slot taken by a later edit”.",
425 );
426 });
427
428 it("carries the payload code onto the ApiError", async () => {
429 mockFetchError(409, { error: "already attached", code: "class_at_course_ceiling" });
430 const err = await client("/classes/1/instances", { method: "POST", body: {} }).catch((e: unknown) => e);
431 expect(err).toBeInstanceOf(ApiError);
432 expect((err as ApiError).code).toBe("class_at_course_ceiling");
433 expect(formatApiError(err, "en")).toMatch(/^This class already has the maximum number of courses\./);
434 });
435
436 it("formats 500+", () => {
437 expect(formatApiError(new ApiError(500, ""), "en")).toBe("Server error. Please try again.");
438 expect(formatApiError(new ApiError(503, ""), "tr")).toBe("Sunucuda bir sorun oluştu. Lütfen tekrar dene.");
439 });
440
441 it("formats 422 backend validation messages", () => {
442 const err = new ApiError(422, "Title must be at most 200 characters (got 250)");
443 expect(formatApiError(err, "tr")).toBe("Başlık en fazla 200 karakter olmalı. Şu an 250 karakter.");
444 });
445
446 it("formats generic Error", () => {
447 expect(formatApiError(new Error("generic"), "en")).toBe("The action could not be completed. Server said: “generic”.");
448 expect(formatApiError(new Error("generic"), "tr")).toBe("İşlem tamamlanamadı. Sunucu yanıtı: “generic”.");
449 });
450
451 it("does not expose network, runtime, or provider errors to users", () => {
452 expect(formatApiError(new TypeError("Failed to fetch"), "tr")).toBe(
453 "Sunucuya ulaşılamadı. Bağlantını kontrol edip tekrar dene.",
454 );
455 expect(formatApiError(new TypeError("Cannot read properties of null (reading 'user')"), "tr")).toBe(
456 "Sayfa yüklenirken bir sorun oluştu. Sayfayı yeniden yükleyip tekrar dene.",
457 );
458 expect(formatApiError(new Error("useAuth must be used within AuthProvider"), "en")).toBe(
459 "Something went wrong while loading the page. Reload the page and try again.",
460 );
461 });
462 });
463});