Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

usePullRequestDiff.test.tsx

292 lines9.9 KB

1import { RegistryContext } from "@effect/atom-react";
2import { sourceControlClients } from "@t3tools/client-runtime/source-control-clients";
3import { PullRequestOperationError, type PullRequestDiffResult } from "@t3tools/contracts";
4import * as Effect from "effect/Effect";
5import { Atom, AtomRegistry } from "effect/reactivity";
6import { act, useLayoutEffect, useState } from "react";
7import { createRoot } from "react-dom/client";
8import { expect, it, vi } from "vite-plus/test";
9​
10const mocks = vi.hoisted(() => ({ diff: vi.fn() }));
11vi.mock("../../state/pull-requests", () => ({ composerPullRequests: { diff: mocks.diff } }));
12​
13import { usePullRequestDiff, usePullRequestDiffEntry } from "./usePullRequestDiff";
14import * as reviewModel from "../review/reviewModel";
15import { getCachedNativeReviewDiffData } from "../review/nativeReviewDiffAdapter";
16​
17function patch(
18 path: string,
19 nextCursor: string | null = null,
20 added = "new",
21): PullRequestDiffResult {
22 return {
23 patch: `diff --git a/${path} b/${path}\n--- a/${path}\n+++ b/${path}\n@@ -1 +1 @@\n-old\n+${added}\n`,
24 truncated: false,
25 nextCursor,
26 };
28​
29function setup() {
30 (globalThis as { IS_REACT_ACT_ENVIRONMENT?: boolean }).IS_REACT_ACT_ENVIRONMENT = true;
31 const registry = AtomRegistry.make();
32 const requests: {
33 cursor: string | null;
34 resolve: (value: PullRequestDiffResult) => void;
35 reject: (error: Error) => void;
36 }[] = [];
37 const queries = Atom.family((cursor: string | null) =>
38 Atom.make(
39 Effect.tryPromise({
40 try: () =>
41 new Promise<PullRequestDiffResult>((resolve, reject) => {
42 requests.push({ cursor, resolve, reject });
43 }),
44 catch: (cause) =>
45 new PullRequestOperationError({ operation: "diff", detail: "Connection lost", cause }),
46 }),
47 ).pipe(Atom.keepAlive),
48 );
49 mocks.diff.mockImplementation((target: { input: { cursor?: string } }) =>
50 queries(target.input.cursor ?? null),
51 );
52 const root = createRoot(document.createElement("div"));
53 let current: ReturnType<typeof usePullRequestDiff>;
54 function Probe() {
55 const result = usePullRequestDiff(
56 {
57 environmentId: "environment",
58 projectId: "project",
59 repository: "repo",
60 number: 1,
61 },
62 sourceControlClients.get("github").changeRequest,
63 );
64 useLayoutEffect(() => {
65 current = result;
66 });
67 return null;
68 }
69 act(() =>
70 root.render(
71 <RegistryContext.Provider value={registry}>
72 <Probe />
73 </RegistryContext.Provider>,
74 ),
75 );
76 return {
77 requests,
78 remount() {
79 act(() =>
80 root.render(
81 <RegistryContext.Provider value={registry}>
82 <Probe key="new-route" />
83 </RegistryContext.Provider>,
84 ),
85 );
86 },
87 get current() {
88 return current;
89 },
90 async succeed(index: number, result: PullRequestDiffResult) {
91 await act(async () => {
92 requests[index]!.resolve(result);
93 });
94 },
95 async fail(index: number) {
96 await act(async () => {
97 requests[index]!.reject(new Error("Connection lost"));
98 });
99 },
100 [Symbol.dispose]() {
101 act(() => root.unmount());
102 registry.dispose();
103 },
104 };
106​
107it("reuses the parsed snapshot when a new route reads the same query result", async () => {
108 using parse = vi.spyOn(reviewModel, "buildReviewParsedDiff");
109 using screen = setup();
110 await screen.succeed(0, patch("first.ts"));
111 const parsed = screen.current.parsed;
112 const parses = parse.mock.calls.length;
113 screen.remount();
114 expect(screen.current.parsed).toBe(parsed);
115 expect(parse).toHaveBeenCalledTimes(parses);
116 expect(screen.requests).toHaveLength(1);
117});
118​
119function setupEntry() {
120 vi.useFakeTimers();
121 (globalThis as { IS_REACT_ACT_ENVIRONMENT?: boolean }).IS_REACT_ACT_ENVIRONMENT = true;
122 const frames = new Map<number, FrameRequestCallback>();
123 let frameId = 0;
124 const requestFrame = vi
125 .spyOn(globalThis, "requestAnimationFrame")
126 .mockImplementation((callback) => {
127 frames.set(++frameId, callback);
128 return frameId;
129 });
130 const cancelFrame = vi.spyOn(globalThis, "cancelAnimationFrame").mockImplementation((id) => {
131 if (id != null) frames.delete(id);
132 });
133 const listeners = new Map<string, (event: { data: { closing: boolean } }) => void>();
134 const navigation = {
135 addListener(
136 type: "transitionStart" | "transitionEnd",
137 listener: (event: { data: { closing: boolean } }) => void,
138 ) {
139 listeners.set(type, listener);
140 return () => {
141 listeners.delete(type);
142 };
143 },
144 };
145 const events: string[] = [];
146 const prepare = vi.fn(() => {
147 events.push("prepare");
148 return getCachedNativeReviewDiffData({
149 parsedDiff: reviewModel.buildReviewParsedDiff(
150 patch("first.ts").patch + patch("neighbor.ts").patch,
151 "entry",
152 ),
153 });
154 });
155 function Body() {
156 const [data] = useState(prepare);
157 return <div>{data.files.map((file) => file.path).join(",")}</div>;
158 }
159 function Entry() {
160 const ready = usePullRequestDiffEntry(navigation);
161 useLayoutEffect(() => {
162 events.push(ready ? "body-commit" : "shell-commit");
163 }, [ready]);
164 return ready ? <Body /> : <div>Opening changes</div>;
165 }
166 const container = document.createElement("div");
167 const root = createRoot(container);
168 act(() => root.render(<Entry />));
169 return {
170 prepare,
171 events,
172 container,
173 frame() {
174 const pending = [...frames.values()];
175 frames.clear();
176 act(() => {
177 for (const callback of pending) callback(0);
178 });
179 },
180 event(type: "transitionStart" | "transitionEnd", closing = false) {
181 act(() => listeners.get(type)?.({ data: { closing } }));
182 },
183 fallback() {
184 act(() => vi.runAllTimers());
185 },
186 [Symbol.dispose]() {
187 act(() => root.unmount());
188 requestFrame.mockRestore();
189 cancelFrame.mockRestore();
190 vi.useRealTimers();
191 },
192 };
194​
195it("commits the loading shell and waits for the opening transition before building the diff", () => {
196 using screen = setupEntry();
197 expect(screen.events).toEqual(["shell-commit"]);
198 screen.event("transitionStart");
199 screen.frame();
200 screen.frame();
201 screen.event("transitionEnd", true);
202 expect(screen.prepare).not.toHaveBeenCalled();
203 screen.event("transitionEnd");
204 expect(screen.events).toEqual(["shell-commit", "prepare", "body-commit"]);
205 expect(screen.container.textContent).toBe("first.ts,neighbor.ts");
206});
207​
208it.each(["unanimated", "missing-completion"] as const)(
209 "opens the diff after a %s presentation without stranding the shell",
210 (presentation) => {
211 using screen = setupEntry();
212 if (presentation === "missing-completion") screen.event("transitionStart");
213 screen.frame();
214 expect(screen.prepare).not.toHaveBeenCalled();
215 screen.frame();
216 if (presentation === "missing-completion") {
217 expect(screen.prepare).not.toHaveBeenCalled();
218 screen.fallback();
219 }
220 expect(screen.prepare).toHaveBeenCalledOnce();
221 },
222);
223​
224it("retries a failed continuation without discarding loaded files or restarting page one", async () => {
225 using screen = setup();
226 await screen.succeed(0, patch("first.ts", "second"));
227 act(() => screen.current.loadMore());
228 await screen.fail(1);
229 expect(screen.current.error).not.toBeNull();
230 expect(screen.current.patch).toContain("first.ts");
231​
232 act(() => screen.current.retry());
233 expect(screen.requests.map((request) => request.cursor)).toEqual([null, "second", "second"]);
234 expect(screen.current.patch).toContain("first.ts");
235 await screen.succeed(2, patch("second.ts"));
236 expect(screen.current.error).toBeNull();
237 expect(screen.current.parsed.kind).toBe("files");
238 if (screen.current.parsed.kind !== "files") throw new Error("Expected files");
239 expect(screen.current.parsed.files.map((file) => file.path)).toEqual(["first.ts", "second.ts"]);
240 expect(screen.current.nextCursor).toBeNull();
241});
242​
243it.each(["failed", "loaded"] as const)(
244 "reloads every page from page one after a continuation %s",
245 async (continuation) => {
246 using screen = setup();
247 await screen.succeed(0, patch("first.ts", "second"));
248 act(() => screen.current.loadMore());
249 if (continuation === "failed") await screen.fail(1);
250 else await screen.succeed(1, patch("second.ts"));
251​
252 act(() => screen.current.refresh());
253 expect(screen.requests.map((request) => request.cursor)).toEqual([null, "second", null]);
254 // The page already on screen stays there while its replacement loads.
255 expect(screen.current.patch).toContain("+new");
256 expect(screen.current.patch).not.toContain("second.ts");
257 expect(screen.current.canLoadMore).toBe(false);
258 await screen.succeed(2, patch("first.ts", "second", "pushed"));
259 expect(screen.current.error).toBeNull();
260 expect(screen.current.patch).not.toContain("+new");
261​
262 act(() => screen.current.loadMore());
263 expect(screen.requests.map((request) => request.cursor)).toEqual([
264 null,
265 "second",
266 null,
267 "second",
268 ]);
269 expect(screen.current.isPending).toBe(true);
270 await screen.succeed(3, patch("second.ts", null, "pushed"));
271 expect(screen.current.patch).not.toContain("+new");
272 if (screen.current.parsed.kind !== "files") throw new Error("Expected files");
273 expect(screen.current.parsed.files.map((file) => file.path)).toEqual(["first.ts", "second.ts"]);
274 },
275);
276​
277it("holds further pages back until a pull to refresh has reread page one", async () => {
278 using screen = setup();
279 await screen.succeed(0, patch("first.ts", "second"));
280​
281 // The pull's refetch starts a tick later, so page one still looks settled here.
282 act(() => void screen.current.onPullRefresh());
283 expect(screen.current.patch).toContain("first.ts");
284 expect(screen.current.canLoadMore).toBe(false);
285 act(() => screen.current.loadMore());
286 await act(async () => {});
287 expect(screen.requests.map((request) => request.cursor)).toEqual([null, null]);
288​
289 await screen.succeed(1, patch("first.ts", "second", "pushed"));
290 expect(screen.current.patch).toContain("+pushed");
291 expect(screen.current.canLoadMore).toBe(true);
292});