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

fake-api.test.ts

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