Open History to see the last commit
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", "1/2"],
160 ["success", "pending", "1/2"],
161 ["pending", "pending", "0/2"],
162 ["pending", "action-required", "0/2"],
163 ["skipped", "pending", "1/2"],
164 ["neutral", "pending", "1/2"],
165 ["failure", "pending", "1/2"],
166 ["cancelled", "pending", "1/2"],
167])("counts finished checks while work remains (%s, %s)", (status, extraStatus, count) => {
168 state.status = status;
169 state.extraStatus = extraStatus;
170 act(() => {
171 root.render(
172 <ThreadDetailsPrRow
173 environmentId={EnvironmentId.make("environment")}
174 pr={null}
175 number={1}
176 status={null}
177 project={null}
178 label="Test PR"
179 openAriaLabel="Open PR"
180 onOpen={vi.fn()}
181 />,
182 );
183 });
184 const counts = [...container.querySelectorAll("*")]
185 .map((element) => element.textContent?.trim() ?? "")
186 .filter((value) => /^\d+\/\d+$/.test(value));
187 expect(new Set(counts)).toEqual(new Set(count ? [count] : []));
188});
189
190it("shows the current checkout recovery detail when fixing checks fails and is retried", async () => {
191 state.status = "failure";
192 const first = new GitManagerError({
193 cwd: "/workspace",
194 operation: "preparePullRequestThread",
195 detail: "This PR branch is already checked out in the main repo. Use Local.",
196 });
197 const second = new GitCommandError({
198 cwd: "/workspace",
199 operation: "GitVcsDriver.createWorktree",
200 command: "git worktree add",
201 detail: "The worktree directory already exists. Choose another directory.",
202 });
203 await act(async () => {
204 root.render(
205 <ThreadDetailsPrRow
206 environmentId={EnvironmentId.make("environment")}
207 pr={null}
208 number={1}
209 status={null}
210 project={null}
211 label="Test PR"
212 openAriaLabel="Open PR"
213 onOpen={vi.fn()}
214 />,
215 );
216 });
217
218 for (const error of [first, second]) {
219 state.prepareThread.mockImplementationOnce(async () => {
220 state.checkoutError = error;
221 return { _tag: "Failure", cause: Cause.fail(error) };
222 });
223 await act(async () => {
224 [...container.querySelectorAll("button")]
225 .find((button) => button.textContent?.trim() === "Fix")!
226 .click();
227 });
228 }
229 expect(state.updateToast.mock.calls.map(([, toast]) => toast.description)).toEqual([
230 expect.stringContaining(first.detail),
231 second.detail,
232 ]);
233});