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

PullRequestInlineCommentScreen.test.tsx

166 lines5.8 KB

1import { RegistryContext } from "@effect/atom-react";
2import { act, type ReactNode } from "react";
3import { createRoot } from "react-dom/client";
4import { expect, it, vi } from "vite-plus/test";
5​
6type ButtonProps = { label: string; loading?: boolean; onPress: () => void };
7const mocks = vi.hoisted(() => {
8 let markLoaded!: () => void;
9 const loaded = new Promise<void>((resolve) => (markLoaded = resolve));
10 let ids = 0;
11 return {
12 write: vi.fn<(file: unknown, contents: string) => Promise<void>>(),
13 goBack: vi.fn(),
14 isFocused: vi.fn(() => true),
15 button: null as ButtonProps | null,
16 saving: Promise.resolve() as Promise<unknown>,
17 changeText: (_text: string) => {},
18 uuid: () => `comment-${++ids}`,
19 loaded,
20 markLoaded,
21 };
22});
23vi.mock("expo-file-system", () => ({
24 Directory: class {
25 create() {}
26 },
27 File: class {
28 // The draft store reads this once while loading and sets ready in the same tick.
29 get exists() {
30 mocks.markLoaded();
31 return false;
32 }
33 },
34 Paths: { document: {} },
35}));
36vi.mock("../../lib/atomic-file", () => ({ writeFileAtomically: mocks.write }));
37vi.mock("../../lib/uuid", () => ({ uuidv4: mocks.uuid }));
38vi.mock("@t3tools/client-runtime/state/runtime", async (importOriginal) => {
39 const runtime = await importOriginal<typeof import("@t3tools/client-runtime/state/runtime")>();
40 return {
41 ...runtime,
42 // Save gives the press handler no promise, so the test awaits the one save awaits.
43 settlePromise: <A,>(execute: () => Promise<A>) =>
44 (mocks.saving = runtime.settlePromise(execute)),
45 };
46});
47vi.mock("react-native", () => ({
48 AppState: { addEventListener: () => ({ remove() {} }) },
49 View: ({ children }: { children: ReactNode }) => children,
50}));
51vi.mock("@react-navigation/native", () => ({
52 useNavigation: () => ({ goBack: mocks.goBack, isFocused: mocks.isFocused }),
53 useFocusEffect: () => {},
54}));
55vi.mock("../../components/ui/Dialog", () => ({ alert: () => {} }));
56vi.mock("../../components/ui/AppText", () => ({
57 AppText: ({ children }: { children: ReactNode }) => <span>{children}</span>,
58 AppTextInput: (props: { onChangeText: (text: string) => void }) => {
59 mocks.changeText = props.onChangeText;
60 return null;
61 },
62}));
63vi.mock("../../components/ui/Button", () => ({
64 Button: (props: ButtonProps) => {
65 mocks.button = props;
66 return null;
67 },
68}));
69vi.mock("./PullRequestSheetContent", () => ({
70 PullRequestSheetContent: (props: { children: ReactNode; footer: ReactNode }) => (
71 <>
72 {props.children}
73 {props.footer}
74 </>
75 ),
76}));
77vi.mock("../../state/pull-requests", () => ({ composerPullRequests: { detail: () => null } }));
78vi.mock("../../state/query", () => ({
79 useEnvironmentQuery: () => ({
80 data: { headSha: "head", capabilities: null },
81 isPending: false,
82 error: null,
83 refresh: () => {},
84 }),
85}));
86vi.mock("./usePullRequestDiff", () => ({ pullRequestTarget: () => null }));
87vi.mock("./usePullRequestPermissions", () => ({
88 usePullRequestPermissions: () => ({ canInlineComment: true }),
89}));
90vi.mock("./PullRequestCompletionSuggestions", () => ({
91 PullRequestCompletionSuggestions: () => null,
92}));
93vi.mock("./usePullRequestCompletions", () => ({ usePullRequestCompletions: () => ({}) }));
94​
95import { appAtomRegistry } from "../../state/atom-registry";
96import { PullRequestInlineCommentScreen } from "./PullRequestInlineCommentScreen";
97​
98function renderScreen() {
99 (globalThis as { IS_REACT_ACT_ENVIRONMENT?: boolean }).IS_REACT_ACT_ENVIRONMENT = true;
100 const container = document.createElement("div");
101 const root = createRoot(container);
102 const params = {
103 environmentId: "environment",
104 projectId: "project",
105 repository: "owner/repo",
106 number: 1,
107 path: "src/a.ts",
108 position: { kind: "added" as const, newLine: 3 },
109 headSha: "head",
110 code: "const a = 1;",
111 };
112 act(() =>
113 root.render(
114 <RegistryContext.Provider value={appAtomRegistry}>
115 <PullRequestInlineCommentScreen route={{ params } as never} />
116 </RegistryContext.Provider>,
117 ),
118 );
119 return { container, [Symbol.dispose]: () => act(() => root.unmount()) };
121​
122it("keeps a new comment open after a failed save and saves it once on retry", async () => {
123 using screen = renderScreen();
124 const { container } = screen;
125 await act(() => mocks.loaded);
126 act(() => mocks.changeText("Rename this"));
127 const failure = Promise.withResolvers<void>();
128 mocks.write.mockImplementationOnce(async () => {
129 await failure.promise;
130 throw new Error("ENOSPC");
131 });
132 act(() => mocks.button?.onPress());
133 expect(mocks.button).toMatchObject({ label: "Saving…", loading: true });
134 await act(async () => {
135 failure.resolve();
136 await mocks.saving;
137 });
138 expect(mocks.button).toMatchObject({ label: "Save draft", loading: false });
139 expect(container.textContent).toContain("could not be saved on this device");
140 expect(mocks.goBack).not.toHaveBeenCalled();
141​
142 mocks.write.mockResolvedValueOnce(undefined);
143 act(() => mocks.button?.onPress());
144 await act(() => mocks.saving);
145 expect(mocks.goBack).toHaveBeenCalledTimes(1);
146 const written = JSON.parse(mocks.write.mock.lastCall?.[1] ?? "{}");
147 expect(
148 Object.values(written.drafts).flatMap((draft) => (draft as { comments: unknown[] }).comments),
149 ).toEqual([expect.objectContaining({ id: "comment-1", body: "Rename this" })]);
150});
151​
152it("does not go back again when the editor was dismissed before its save finished", async () => {
153 using _screen = renderScreen();
154 await act(() => mocks.loaded);
155 mocks.goBack.mockClear();
156 act(() => mocks.changeText("Rename this"));
157 const write = Promise.withResolvers<void>();
158 mocks.write.mockImplementationOnce(() => write.promise);
159 act(() => mocks.button?.onPress());
160 mocks.isFocused.mockReturnValue(false);
161 await act(async () => {
162 write.resolve();
163 await mocks.saving;
164 });
165 expect(mocks.goBack).not.toHaveBeenCalled();
166});