forge
Explore
Log in

Don't you dare go Hollow

hezarfen_frontend

Clone
★ 0

0 watching0 forksTypeScript5.5 MiB4e0a329Burak Boduroğlu2 months ago537 commits

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