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

usePullRequestDiff.test.tsx

246 lines8.1 KB

1import { RegistryContext } from "@effect/atom-react";
2import { sourceControlClients } from "@t3tools/client-runtime/source-control-clients";
3import 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(path: string, nextCursor: string | null = null): PullRequestDiffResult {
18 return {
19 patch: `diff --git a/${path} b/${path}\n--- a/${path}\n+++ b/${path}\n@@ -1 +1 @@\n-old\n+new\n`,
20 truncated: false,
21 nextCursor,
22 };
24​
25function setup() {
26 (globalThis as { IS_REACT_ACT_ENVIRONMENT?: boolean }).IS_REACT_ACT_ENVIRONMENT = true;
27 const registry = AtomRegistry.make();
28 const requests: {
29 cursor: string | null;
30 resolve: (value: PullRequestDiffResult) => void;
31 reject: (error: Error) => void;
32 }[] = [];
33 const queries = Atom.family((cursor: string | null) =>
34 Atom.make(
35 Effect.tryPromise(
36 () =>
37 new Promise<PullRequestDiffResult>((resolve, reject) => {
38 requests.push({ cursor, resolve, reject });
39 }),
40 ),
41 ).pipe(Atom.keepAlive),
42 );
43 mocks.diff.mockImplementation((target: { input: { cursor?: string } }) =>
44 queries(target.input.cursor ?? null),
45 );
46 const root = createRoot(document.createElement("div"));
47 let current: ReturnType<typeof usePullRequestDiff>;
48 function Probe() {
49 const result = usePullRequestDiff(
50 {
51 environmentId: "environment",
52 projectId: "project",
53 repository: "repo",
54 number: 1,
55 },
56 sourceControlClients.get("github").changeRequest,
57 );
58 useLayoutEffect(() => {
59 current = result;
60 });
61 return null;
62 }
63 act(() =>
64 root.render(
65 <RegistryContext.Provider value={registry}>
66 <Probe />
67 </RegistryContext.Provider>,
68 ),
69 );
70 return {
71 requests,
72 remount() {
73 act(() =>
74 root.render(
75 <RegistryContext.Provider value={registry}>
76 <Probe key="new-route" />
77 </RegistryContext.Provider>,
78 ),
79 );
80 },
81 get current() {
82 return current;
83 },
84 async succeed(index: number, result: PullRequestDiffResult) {
85 await act(async () => {
86 requests[index]!.resolve(result);
87 });
88 },
89 async fail(index: number) {
90 await act(async () => {
91 requests[index]!.reject(new Error("Connection lost"));
92 });
93 },
94 [Symbol.dispose]() {
95 act(() => root.unmount());
96 registry.dispose();
97 },
98 };
100​
101it("reuses the parsed snapshot when a new route reads the same query result", async () => {
102 using parse = vi.spyOn(reviewModel, "buildReviewParsedDiff");
103 using screen = setup();
104 await screen.succeed(0, patch("first.ts"));
105 const parsed = screen.current.parsed;
106 const parses = parse.mock.calls.length;
107 screen.remount();
108 expect(screen.current.parsed).toBe(parsed);
109 expect(parse).toHaveBeenCalledTimes(parses);
110 expect(screen.requests).toHaveLength(1);
111});
112​
113function setupEntry() {
114 vi.useFakeTimers();
115 (globalThis as { IS_REACT_ACT_ENVIRONMENT?: boolean }).IS_REACT_ACT_ENVIRONMENT = true;
116 const frames = new Map<number, FrameRequestCallback>();
117 let frameId = 0;
118 const requestFrame = vi
119 .spyOn(globalThis, "requestAnimationFrame")
120 .mockImplementation((callback) => {
121 frames.set(++frameId, callback);
122 return frameId;
123 });
124 const cancelFrame = vi.spyOn(globalThis, "cancelAnimationFrame").mockImplementation((id) => {
125 if (id != null) frames.delete(id);
126 });
127 const listeners = new Map<string, (event: { data: { closing: boolean } }) => void>();
128 const navigation = {
129 addListener(
130 type: "transitionStart" | "transitionEnd",
131 listener: (event: { data: { closing: boolean } }) => void,
132 ) {
133 listeners.set(type, listener);
134 return () => {
135 listeners.delete(type);
136 };
137 },
138 };
139 const events: string[] = [];
140 const prepare = vi.fn(() => {
141 events.push("prepare");
142 return getCachedNativeReviewDiffData({
143 parsedDiff: reviewModel.buildReviewParsedDiff(
144 patch("first.ts").patch + patch("neighbor.ts").patch,
145 "entry",
146 ),
147 });
148 });
149 function Body() {
150 const [data] = useState(prepare);
151 return <div>{data.files.map((file) => file.path).join(",")}</div>;
152 }
153 function Entry() {
154 const ready = usePullRequestDiffEntry(navigation);
155 useLayoutEffect(() => {
156 events.push(ready ? "body-commit" : "shell-commit");
157 }, [ready]);
158 return ready ? <Body /> : <div>Opening changes</div>;
159 }
160 const container = document.createElement("div");
161 const root = createRoot(container);
162 act(() => root.render(<Entry />));
163 return {
164 prepare,
165 events,
166 container,
167 frame() {
168 const pending = [...frames.values()];
169 frames.clear();
170 act(() => {
171 for (const callback of pending) callback(0);
172 });
173 },
174 event(type: "transitionStart" | "transitionEnd", closing = false) {
175 act(() => listeners.get(type)?.({ data: { closing } }));
176 },
177 fallback() {
178 act(() => vi.runAllTimers());
179 },
180 [Symbol.dispose]() {
181 act(() => root.unmount());
182 requestFrame.mockRestore();
183 cancelFrame.mockRestore();
184 vi.useRealTimers();
185 },
186 };
188​
189it("commits the loading shell and waits for the opening transition before building the diff", () => {
190 using screen = setupEntry();
191 expect(screen.events).toEqual(["shell-commit"]);
192 screen.event("transitionStart");
193 screen.frame();
194 screen.frame();
195 screen.event("transitionEnd", true);
196 expect(screen.prepare).not.toHaveBeenCalled();
197 screen.event("transitionEnd");
198 expect(screen.events).toEqual(["shell-commit", "prepare", "body-commit"]);
199 expect(screen.container.textContent).toBe("first.ts,neighbor.ts");
200});
201​
202it.each(["unanimated", "missing-completion"] as const)(
203 "opens the diff after a %s presentation without stranding the shell",
204 (presentation) => {
205 using screen = setupEntry();
206 if (presentation === "missing-completion") screen.event("transitionStart");
207 screen.frame();
208 expect(screen.prepare).not.toHaveBeenCalled();
209 screen.frame();
210 if (presentation === "missing-completion") {
211 expect(screen.prepare).not.toHaveBeenCalled();
212 screen.fallback();
213 }
214 expect(screen.prepare).toHaveBeenCalledOnce();
215 },
216);
217​
218it("retries a failed continuation without discarding loaded files or restarting page one", async () => {
219 using screen = setup();
220 await screen.succeed(0, patch("first.ts", "second"));
221 act(() => screen.current.loadMore());
222 await screen.fail(1);
223 expect(screen.current.error).not.toBeNull();
224 expect(screen.current.patch).toContain("first.ts");
225​
226 act(() => screen.current.refresh());
227 expect(screen.requests.map((request) => request.cursor)).toEqual([null, "second", "second"]);
228 expect(screen.current.patch).toContain("first.ts");
229 await screen.succeed(2, patch("second.ts"));
230 expect(screen.current.error).toBeNull();
231 expect(screen.current.parsed.kind).toBe("files");
232 if (screen.current.parsed.kind !== "files") throw new Error("Expected files");
233 expect(screen.current.parsed.files.map((file) => file.path)).toEqual(["first.ts", "second.ts"]);
234 expect(screen.current.nextCursor).toBeNull();
235});
236​
237it("still refreshes from page one after successfully loading a continuation", async () => {
238 using screen = setup();
239 await screen.succeed(0, patch("first.ts", "second"));
240 act(() => screen.current.loadMore());
241 await screen.succeed(1, patch("second.ts"));
242 act(() => screen.current.refresh());
243 await screen.succeed(2, patch("refreshed.ts"));
244 if (screen.current.parsed.kind !== "files") throw new Error("Expected files");
245 expect(screen.current.parsed.files.map((file) => file.path)).toEqual(["refreshed.ts"]);
246});