Skip to content
Source
Sign inSign up
fuko/trytanstackdb-v2
Open History to see the last commit

fake-api.test.ts

245 lines9.3 KB

1import { afterEach, beforeEach, describe, expect, it, vi } from "vite-plus/test";
2​
3import { ApiError, api } from "./client";
4import { fakeFetch, resetFakeServer } from "./fake-fetch";
5import { matchPath, NOTE_TITLE_MAX_LENGTH } from "./fake-server";
6import {
7 DEFAULT_NETWORK_CONFIG,
8 getNetworkConfig,
9 setNetworkConfig,
10 takeInjectedFailure,
11} from "./network-config";
12import { clearRequestLog, REQUEST_LOG_LIMIT, requestLogStore } from "./request-log";
13​
14const json = (body: unknown) => ({
15 headers: { "Content-Type": "application/json" },
16 body: JSON.stringify(body),
17});
18​
19beforeEach(() => {
20 resetFakeServer();
21 clearRequestLog();
22 setNetworkConfig({ ...DEFAULT_NETWORK_CONFIG, latencyMs: 0 });
23});
24​
25afterEach(() => {
26 vi.useRealTimers();
27});
28​
29describe("routing", () => {
30 it("returns real JSON responses", async () => {
31 const response = await fakeFetch("/api/folders");
32 expect(response).toBeInstanceOf(Response);
33 expect(response.status).toBe(200);
34 expect(response.headers.get("Content-Type")).toBe("application/json");
35 const folders = (await response.json()) as { id: string; position: number }[];
36 expect(folders.map((folder) => folder.position)).toEqual(
37 folders.map((folder) => folder.position).sort((a, b) => a - b),
38 );
39 });
40​
41 it("serves single records and the account", async () => {
42 expect((await api.get<{ id: string }>("/api/notes/note-01")).id).toBe("note-01");
43 expect((await api.get<{ id: string }>("/api/account")).id).toBe("account-1");
44 });
45​
46 it("answers unknown paths with 404 and wrong methods with 405", async () => {
47 expect((await fakeFetch("/api/nope")).status).toBe(404);
48 expect((await fakeFetch("/api/notes/missing")).status).toBe(404);
49 expect((await fakeFetch("/api/folders", { method: "DELETE" })).status).toBe(405);
50 });
51​
52 it("filters notes by folder", async () => {
53 const all = await api.get<{ folderId: string }[]>("/api/notes");
54 const work = await api.get<{ folderId: string }[]>("/api/notes?folderId=work");
55 expect(work.length).toBeGreaterThan(0);
56 expect(work.every((note) => note.folderId === "work")).toBe(true);
57 expect(work).toHaveLength(all.filter((note) => note.folderId === "work").length);
58 });
59​
60 it("matches path patterns", () => {
61 expect(matchPath("/api/notes/:id", "/api/notes/a%20b")).toEqual({ id: "a b" });
62 expect(matchPath("/api/notes/:id", "/api/notes")).toBeNull();
63 expect(matchPath("/api/notes", "/api/folders")).toBeNull();
64 });
65});
66​
67describe("validation", () => {
68 it("rejects a folder name that's already taken (any case) with 409", async () => {
69 const response = await fakeFetch("/api/folders/work", {
70 method: "PATCH",
71 ...json({ name: "personal" }),
72 });
73 expect(response.status).toBe(409);
74 expect(await response.json()).toEqual({
75 error: { code: "duplicate_name", message: "There's already a folder named “personal”." },
76 });
77 // Nothing changed on the server.
78 expect((await api.get<{ name: string }>("/api/folders/work")).name).toBe("Work");
79 });
80​
81 it("rejects empty names and renaming built-in folders", async () => {
82 await expect(api.patch("/api/folders/work", { name: " " })).rejects.toMatchObject({
83 status: 422,
84 });
85 await expect(api.patch("/api/folders/notes", { name: "Inbox" })).rejects.toMatchObject({
86 status: 403,
87 });
88 });
89​
90 it("renames a folder, trimming the name", async () => {
91 const folder = await api.patch<{ name: string }>("/api/folders/work", { name: " Job " });
92 expect(folder.name).toBe("Job");
93 });
94​
95 it("rejects note titles over the limit with 422", async () => {
96 const error = await api
97 .patch("/api/notes/note-01", { title: "x".repeat(NOTE_TITLE_MAX_LENGTH + 1) })
98 .catch((caught: unknown) => caught);
99 expect(error).toBeInstanceOf(ApiError);
100 expect(error).toMatchObject({ status: 422, code: "title_too_long" });
101 });
102​
103 it("rejects moving a note to a folder that doesn't exist", async () => {
104 await expect(api.patch("/api/notes/note-01", { folderId: "nope" })).rejects.toMatchObject({
105 status: 422,
106 });
107 });
108​
109 it("rejects an invalid email", async () => {
110 await expect(api.patch("/api/account", { email: "not-an-email" })).rejects.toMatchObject({
111 status: 422,
112 code: "validation_failed",
113 });
114 });
115});
116​
117describe("notes", () => {
118 it("stamps updatedAt when the text changes, not when pinning", async () => {
119 const before = await api.get<{ updatedAt: string }>("/api/notes/note-02");
120 const pinned = await api.patch<{ updatedAt: string; pinned: boolean }>("/api/notes/note-02", {
121 pinned: true,
122 });
123 expect(pinned).toMatchObject({ pinned: true, updatedAt: before.updatedAt });
124 const edited = await api.patch<{ updatedAt: string; title: string }>("/api/notes/note-02", {
125 title: "Packing list (Lisbon)",
126 });
127 expect(edited.title).toBe("Packing list (Lisbon)");
128 expect(Date.parse(edited.updatedAt)).toBeGreaterThan(Date.parse(before.updatedAt));
129 });
130​
131 it("creates and deletes notes", async () => {
132 const now = new Date().toISOString();
133 const note = {
134 id: "new-note",
135 folderId: "work",
136 title: "Hello",
137 body: "",
138 pinned: false,
139 shared: false,
140 createdAt: now,
141 updatedAt: now,
142 deletedAt: null,
143 };
144 expect((await fakeFetch("/api/notes", { method: "POST", ...json(note) })).status).toBe(201);
145 expect((await fakeFetch("/api/notes", { method: "POST", ...json(note) })).status).toBe(409);
146 const deleted = await fakeFetch("/api/notes/new-note", { method: "DELETE" });
147 expect(deleted.status).toBe(204);
148 expect(await deleted.text()).toBe("");
149 expect((await fakeFetch("/api/notes/new-note")).status).toBe(404);
150 });
151​
152 it("hands out copies, so callers can't change server data", async () => {
153 const note = await api.get<{ title: string }>("/api/notes/note-01");
154 note.title = "Mutated";
155 expect((await api.get<{ title: string }>("/api/notes/note-01")).title).not.toBe("Mutated");
156 });
157});
158​
159describe("latency and failure injection", () => {
160 it("waits the configured latency before answering", async () => {
161 vi.useFakeTimers();
162 setNetworkConfig({ latencyMs: 2000 });
163 let settled = false;
164 const request = fakeFetch("/api/account").then(() => (settled = true));
165 await vi.advanceTimersByTimeAsync(1999);
166 expect(settled).toBe(false);
167 await vi.advanceTimersByTimeAsync(1);
168 await request;
169 expect(settled).toBe(true);
170 });
171​
172 it("fails the next request once, without touching server data", async () => {
173 setNetworkConfig({ failNextRequest: true });
174 const failed = await fakeFetch("/api/folders/work", {
175 method: "PATCH",
176 ...json({ name: "Job" }),
177 });
178 expect(failed.status).toBe(500);
179 expect(await failed.json()).toMatchObject({ error: { code: "injected_failure" } });
180 expect(getNetworkConfig().failNextRequest).toBe(false);
181 expect((await api.get<{ name: string }>("/api/folders/work")).name).toBe("Work");
182 });
183​
184 it("fails a share of requests at random", () => {
185 setNetworkConfig({ failureRate: 0.25 });
186 expect(takeInjectedFailure(() => 0.1)).toBe(true);
187 expect(takeInjectedFailure(() => 0.9)).toBe(false);
188 setNetworkConfig({ failureRate: 0 });
189 expect(takeInjectedFailure(() => 0)).toBe(false);
190 });
191​
192 it("can be aborted while waiting", async () => {
193 setNetworkConfig({ latencyMs: 1000 });
194 const controller = new AbortController();
195 const request = fakeFetch("/api/notes", { signal: controller.signal });
196 controller.abort();
197 await expect(request).rejects.toBeDefined();
198 expect(requestLogStore.get().at(-1)).toMatchObject({ state: "aborted", status: null });
199 });
200});
201​
202describe("request log", () => {
203 it("records each request while pending, then its result", async () => {
204 vi.useFakeTimers();
205 setNetworkConfig({ latencyMs: 500 });
206 const request = fakeFetch("/api/folders/work", { method: "PATCH", ...json({ name: "Job" }) });
207 expect(requestLogStore.get()).toMatchObject([
208 { method: "PATCH", url: "/api/folders/work", state: "pending", requestBody: { name: "Job" } },
209 ]);
210 await vi.advanceTimersByTimeAsync(500);
211 await request;
212 const [entry] = requestLogStore.get();
213 expect(entry).toMatchObject({
214 state: "done",
215 status: 200,
216 durationMs: 500,
217 injectedFailure: false,
218 responseBody: { id: "work", name: "Job" },
219 });
220 });
221​
222 it("records malformed JSON and answers it with a 400", async () => {
223 const response = await fakeFetch("/api/notes", { method: "POST", body: "{broken" });
224 expect(response.status).toBe(400);
225 expect(await response.json()).toEqual({
226 error: { code: "invalid_json", message: "The request body isn't valid JSON." },
227 });
228 expect(requestLogStore.get()).toMatchObject([
229 { method: "POST", url: "/api/notes", state: "done", status: 400, requestBody: "{broken" },
230 ]);
231 });
232​
233 it("marks injected failures", async () => {
234 setNetworkConfig({ failNextRequest: true });
235 await fakeFetch("/api/notes");
236 expect(requestLogStore.get().at(-1)).toMatchObject({ status: 500, injectedFailure: true });
237 });
238​
239 it("keeps only the most recent requests", async () => {
240 for (let i = 0; i < REQUEST_LOG_LIMIT + 5; i++) await fakeFetch("/api/account");
241 const entries = requestLogStore.get();
242 expect(entries).toHaveLength(REQUEST_LOG_LIMIT);
243 expect(entries[0]!.id).toBeLessThan(entries.at(-1)!.id);
244 });
245});