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

ThreadDetailsPrRow.browser.test.tsx

228 lines6.8 KB

1import {
2 EnvironmentId,
3 GitCommandError,
4 GitManagerError,
5 ProjectId,
6 ThreadId,
7 type PullRequestCheck,
8} from "@t3tools/contracts";
9import * as Cause from "effect/Cause";
10import { DraftId } from "~/composerDraftStore";
11import { AsyncResult } from "effect/reactivity";
12import { act } from "react";
13import { createRoot, type Root } from "react-dom/client";
14import { afterEach, beforeEach, expect, it, vi } from "vite-plus/test";
15​
16const state = vi.hoisted(() => ({
17 status: "success" as PullRequestCheck["status"],
18 extraStatus: null as PullRequestCheck["status"] | null,
19 perform: vi.fn(),
20 newThread: vi.fn(),
21 prepareThread: vi.fn(),
22 checkoutError: null as Error | null,
23 addToast: vi.fn(),
24 updateToast: vi.fn(),
25}));
26​
27vi.mock(import("~/state/entities"), async (importOriginal) => ({
28 ...(await importOriginal()),
29 useServerConfigs: (() => new Map()) as never,
30}));
31const queryData = () => ({
32 projectId: ProjectId.make("project"),
33 workspaceRoot: "/workspace",
34 url: "https://github.com/owner/repo/pull/1",
35 number: 1,
36 title: "Test PR",
37 state: "open",
38 isDraft: false,
39 mergeability: "mergeable",
40 headBranch: "feature",
41 baseBranch: "main",
42 changedFiles: 1,
43 additions: 1,
44 deletions: 0,
45 checks: [state.status, ...(state.extraStatus ? [state.extraStatus] : [])].map((status) => ({
46 name: `CI-${status}`,
47 status,
48 description: null,
49 url: null,
50 })),
51 capabilities: { actions: ["merge"], mergeMethods: ["merge"] },
52 viewerPermissions: { actions: ["merge"] },
53 mergeCapabilities: { merge: true, squash: false, rebase: false },
54});
55vi.mock(import("~/state/query"), async (importOriginal) => ({
56 ...(await importOriginal()),
57 useEnvironmentQuerySelector: ((_atom: unknown, select: (result: unknown) => unknown) =>
58 select(AsyncResult.success(queryData()))) as never,
59 useEnvironmentQueryIsNewer: () => true,
60 useEnvironmentQueryRefresh: () => ({ refresh: vi.fn(), isPending: () => false }),
61}));
62vi.mock(import("../pullRequest/usePullRequestActions"), async (importOriginal) => ({
63 ...(await importOriginal()),
64 usePullRequestActionRunner: () => ({ actionPending: false, perform: state.perform }),
65}));
66​
67vi.mock(import("~/hooks/useHandleNewThread"), async (original) => ({
68 ...(await original()),
69 useNewThreadHandler: (() => state.newThread) as never,
70}));
71vi.mock(import("~/lib/sourceControlActions"), async (original) => ({
72 ...(await original()),
73 usePreparePullRequestThreadAction: (() => ({
74 run: state.prepareThread,
75 isAllowed: true,
76 error: state.checkoutError,
77 })) as never,
78}));
79vi.mock(import("../ui/toast"), async (original) => {
80 const actual = await original();
81 return {
82 ...actual,
83 toastManager: {
84 ...actual.toastManager,
85 add: state.addToast,
86 update: state.updateToast,
87 } as never,
88 };
89});
90​
91import { ThreadDetailsPrRow } from "./ThreadDetailsPrRow";
92​
93let root: Root;
94let container: HTMLDivElement;
95beforeEach(() => {
96 vi.stubGlobal("IS_REACT_ACT_ENVIRONMENT", true);
97 container = document.createElement("div");
98 document.body.append(container);
99 root = createRoot(container);
100 state.checkoutError = null;
101 state.newThread.mockReset().mockResolvedValue({
102 draftId: DraftId.make("new-draft"),
103 threadId: ThreadId.make("new-thread"),
104 });
105 state.prepareThread.mockReset();
106 state.addToast.mockReset().mockReturnValue("checkout-toast");
107 state.updateToast.mockReset();
108});
109afterEach(() => {
110 act(() => root.unmount());
111 document.body.replaceChildren();
112 vi.unstubAllGlobals();
113 state.status = "success";
114 state.extraStatus = null;
115});
116​
117it("requires a new merge click after passing checks become pending and pass again", () => {
118 const render = () => (
119 <ThreadDetailsPrRow
120 environmentId={EnvironmentId.make("environment")}
121 pr={null}
122 number={1}
123 status={null}
124 project={null}
125 label="Test PR"
126 openAriaLabel="Open PR"
127 onOpen={vi.fn()}
128 />
129 );
130 const clickMerge = () =>
131 act(() => {
132 [...container.querySelectorAll("button")]
133 .find((button) => button.textContent?.trim() === "Merge")!
134 .click();
135 });
136 const dialogs = () => [...document.querySelectorAll('[role="alertdialog"]')];
137​
138 act(() => root.render(render()));
139 clickMerge();
140 expect(dialogs()).toHaveLength(1);
141 act(() => {
142 state.status = "pending";
143 root.render(render());
144 });
145 expect(dialogs()).toHaveLength(0);
146 act(() => {
147 state.status = "success";
148 root.render(render());
149 });
150 expect(dialogs()).toHaveLength(0);
151 clickMerge();
152 expect(dialogs()).toHaveLength(1);
153 expect(state.perform).not.toHaveBeenCalled();
154});
155​
156it.each<[PullRequestCheck["status"], PullRequestCheck["status"], string]>([
157 ["success", "skipped", ""],
158 ["failure", "cancelled", ""],
159 ["success", "action-required", ""],
160 ["success", "pending", "1/2"],
161 ["failure", "pending", "1/2"],
162])("shows a count only while checks run (%s, %s)", (status, extraStatus, count) => {
163 state.status = status;
164 state.extraStatus = extraStatus;
165 act(() => {
166 root.render(
167 <ThreadDetailsPrRow
168 environmentId={EnvironmentId.make("environment")}
169 pr={null}
170 number={1}
171 status={null}
172 project={null}
173 label="Test PR"
174 openAriaLabel="Open PR"
175 onOpen={vi.fn()}
176 />,
177 );
178 });
179 const counts = [...container.querySelectorAll("*")]
180 .map((element) => element.textContent?.trim() ?? "")
181 .filter((value) => /^\d+\/\d+$/.test(value));
182 expect(new Set(counts)).toEqual(new Set(count ? [count] : []));
183});
184​
185it("shows the current checkout recovery detail when fixing checks fails and is retried", async () => {
186 state.status = "failure";
187 const first = new GitManagerError({
188 cwd: "/workspace",
189 operation: "preparePullRequestThread",
190 detail: "This PR branch is already checked out in the main repo. Use Local.",
191 });
192 const second = new GitCommandError({
193 cwd: "/workspace",
194 operation: "GitVcsDriver.createWorktree",
195 command: "git worktree add",
196 detail: "The worktree directory already exists. Choose another directory.",
197 });
198 await act(async () => {
199 root.render(
200 <ThreadDetailsPrRow
201 environmentId={EnvironmentId.make("environment")}
202 pr={null}
203 number={1}
204 status={null}
205 project={null}
206 label="Test PR"
207 openAriaLabel="Open PR"
208 onOpen={vi.fn()}
209 />,
210 );
211 });
212​
213 for (const error of [first, second]) {
214 state.prepareThread.mockImplementationOnce(async () => {
215 state.checkoutError = error;
216 return { _tag: "Failure", cause: Cause.fail(error) };
217 });
218 await act(async () => {
219 [...container.querySelectorAll("button")]
220 .find((button) => button.textContent?.trim() === "Fix")!
221 .click();
222 });
223 }
224 expect(state.updateToast.mock.calls.map(([, toast]) => toast.description)).toEqual([
225 expect.stringContaining(first.detail),
226 second.detail,
227 ]);
228});