forge
Explore
Log in

Don't you dare go Hollow

hezarfen_frontend

Clone
★ 0

0 watching0 forksTypeScript5.5 MiB7122d71Burak Boduroğlu4 months ago419 commits

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