Skip to content

Commit d53e751

Browse files
test(web): file browser and attachment image tests run in a real browser
FileBrowserPanel.test.tsx (#17132) and AttachmentImage.test.tsx (#10429) still imported react-test-renderer, which #20944 removed from apps/web, so main failed typecheck and the unit suite. Both now mount with createRoot into document.body and query the DOM, like #21274. The file browser test now reads tree rows from the rendered tree's shadow root instead of the model. That made the tree render rows for the first time, which exposed a gap in the useDirectoryEntries mock: it never returned loadingDirectories. Co-Authored-By: Claude Opus 5.5 <[email protected]>
1 parent e2cc34f commit d53e751

2 files changed

Lines changed: 89 additions & 57 deletions

File tree

apps/web/src/components/files/FileBrowserPanel.test.tsx renamed to apps/web/src/components/files/FileBrowserPanel.browser.test.tsx

Lines changed: 39 additions & 28 deletions
Original file line numberDiff line numberDiff line change
@@ -1,25 +1,24 @@
1-
import { FileTree } from "@pierre/trees/react";
2-
import type { FileTree as FileTreeModel } from "@pierre/trees";
31
import { EnvironmentId, type ProjectEntry } from "@t3tools/contracts";
42
import { act, type ReactNode } from "react";
5-
import { create, type ReactTestRenderer } from "react-test-renderer";
3+
import { createRoot, type Root } from "react-dom/client";
64
import { afterEach, beforeEach, describe, expect, it, vi } from "vite-plus/test";
75

8-
import { InputGroupInput } from "~/components/ui/input-group";
96
import FileBrowserPanel from "./FileBrowserPanel";
107

118
const files = vi.hoisted(() => ({
129
directoryEntries: [] as ProjectEntry[],
1310
searchEntries: [] as ProjectEntry[],
1411
searchPending: false,
1512
searchError: null as string | null,
13+
loadingDirectories: new Set<string>() as ReadonlySet<string>,
1614
load: vi.fn(async () => {}),
1715
refresh: vi.fn(),
1816
}));
1917

2018
vi.mock("./useDirectoryEntries", () => ({
2119
useDirectoryEntries: () => ({
2220
entries: files.directoryEntries,
21+
loadingDirectories: files.loadingDirectories,
2322
load: files.load,
2423
refresh: files.refresh,
2524
ready: true,
@@ -50,7 +49,8 @@ vi.mock("~/components/ui/tooltip", () => ({
5049
}));
5150

5251
describe("Files panel search", () => {
53-
let renderer: ReactTestRenderer | undefined;
52+
let root: Root | undefined;
53+
let container: HTMLDivElement | undefined;
5454
const props = {
5555
environmentId: EnvironmentId.make("test-environment"),
5656
cwd: "/workspace",
@@ -62,36 +62,47 @@ describe("Files panel search", () => {
6262
};
6363

6464
async function render() {
65-
await act(async () => {
66-
if (renderer) renderer.update(<FileBrowserPanel {...props} />);
67-
else renderer = create(<FileBrowserPanel {...props} />);
68-
});
65+
if (!container) {
66+
container = document.body.appendChild(document.createElement("div"));
67+
// The tree virtualizes its rows, so it needs a real viewport to render any.
68+
container.style.cssText =
69+
"display: flex; flex-direction: column; width: 320px; height: 480px;";
70+
root = createRoot(container);
71+
}
72+
await act(async () => root!.render(<FileBrowserPanel {...props} />));
73+
}
74+
75+
function searchInput() {
76+
const input = container!.querySelector<HTMLInputElement>('input[type="search"]');
77+
expect(input).not.toBeNull();
78+
return input!;
6979
}
7080

7181
async function search(value: string) {
82+
const input = searchInput();
83+
// React tracks the last value it saw on the element, so set it through the native setter.
84+
Object.getOwnPropertyDescriptor(HTMLInputElement.prototype, "value")!.set!.call(input, value);
7285
await act(async () => {
73-
renderer!.root.findByType(InputGroupInput).props.onChange({ target: { value } });
86+
input.dispatchEvent(new Event("input", { bubbles: true }));
7487
});
7588
}
7689

7790
function visiblePaths() {
78-
const trees = renderer!.root.findAllByType(FileTree);
79-
if (trees.length === 0) return [];
80-
const model: FileTreeModel = trees[0]!.props.model;
81-
return model.getVisibleRows(0, model.getVisibleCount()).map((row) => row.path);
91+
const tree = container!.querySelector("file-tree-container");
92+
if (!tree) return [];
93+
return [...tree.shadowRoot!.querySelectorAll("[data-item-path]")].map((row) =>
94+
row.getAttribute("data-item-path"),
95+
);
8296
}
8397

8498
function hasMessage(message: string) {
85-
return (
86-
renderer!.root.findAll((node) => node.type === "div" && node.props.children === message)
87-
.length > 0
99+
return [...container!.querySelectorAll("div")].some(
100+
(node) => node.childNodes.length === 1 && node.textContent === message,
88101
);
89102
}
90103

91104
beforeEach(() => {
92-
vi.useFakeTimers();
93105
vi.stubGlobal("IS_REACT_ACT_ENVIRONMENT", true);
94-
vi.stubGlobal("document", new EventTarget());
95106
files.directoryEntries = [
96107
{ path: "src", kind: "directory" },
97108
{ path: "src/app.ts", kind: "file" },
@@ -103,10 +114,10 @@ describe("Files panel search", () => {
103114
});
104115

105116
afterEach(async () => {
106-
await act(async () => renderer?.unmount());
107-
renderer = undefined;
108-
vi.runOnlyPendingTimers();
109-
vi.useRealTimers();
117+
await act(async () => root?.unmount());
118+
container?.remove();
119+
root = undefined;
120+
container = undefined;
110121
vi.unstubAllGlobals();
111122
});
112123

@@ -154,12 +165,12 @@ describe("Files panel search", () => {
154165
await search("missing-file");
155166
expect(visiblePaths()).toEqual([]);
156167

168+
const input = searchInput();
169+
input.focus();
157170
await act(async () => {
158-
renderer!.root.findByType(InputGroupInput).props.onKeyDown({
159-
key: "Escape",
160-
currentTarget: { blur: vi.fn() },
161-
});
171+
input.dispatchEvent(new KeyboardEvent("keydown", { key: "Escape", bubbles: true }));
162172
});
173+
expect(document.activeElement).not.toBe(input);
163174
expect(visiblePaths()).toEqual(["src/", "package.json"]);
164175
expect(hasMessage("No matching files.")).toBe(false);
165176
});
@@ -170,6 +181,6 @@ describe("Files panel search", () => {
170181
await search("missing-file");
171182
expect(visiblePaths()).toEqual([]);
172183
expect(hasMessage("No matching files.")).toBe(false);
173-
expect(JSON.stringify(renderer!.toJSON())).toContain("Workspace search failed.");
184+
expect(container!.textContent).toContain("Workspace search failed.");
174185
});
175186
});

apps/web/src/components/media/AttachmentImage.test.tsx renamed to apps/web/src/components/media/AttachmentImage.browser.test.tsx

Lines changed: 50 additions & 29 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,5 @@
1-
import { act, type SyntheticEvent } from "react";
2-
import { create, type ReactTestRenderer } from "react-test-renderer";
1+
import { act, type ReactNode } from "react";
2+
import { createRoot, type Root } from "react-dom/client";
33
import { afterEach, beforeEach, expect, it, vi } from "vite-plus/test";
44
import { AttachmentImage } from "./AttachmentImage";
55
import { prepareImageForAttachment } from "../../lib/imageCompression";
@@ -9,10 +9,10 @@ vi.mock("../../lib/imageCompression", async (importOriginal) => ({
99
prepareImageForAttachment: vi.fn(),
1010
}));
1111

12-
let renderer: ReactTestRenderer;
12+
let root: Root | undefined;
13+
let container: HTMLDivElement | undefined;
1314
const fetchImage = vi.fn();
1415
const revokeUrl = vi.fn();
15-
const decodeError = {} as SyntheticEvent<HTMLImageElement>;
1616
const jpeg = new File(["jpeg"], "photo.jpg", { type: "image/jpeg" });
1717

1818
beforeEach(() => {
@@ -29,53 +29,76 @@ beforeEach(() => {
2929
});
3030

3131
afterEach(async () => {
32-
await act(() => renderer?.unmount());
32+
await act(() => root?.unmount());
33+
container?.remove();
34+
root = undefined;
35+
container = undefined;
3336
vi.restoreAllMocks();
3437
vi.unstubAllGlobals();
3538
vi.clearAllMocks();
3639
});
3740

41+
async function render(element: ReactNode) {
42+
if (!container) {
43+
container = document.body.appendChild(document.createElement("div"));
44+
root = createRoot(container);
45+
}
46+
await act(() => root!.render(element));
47+
}
48+
49+
function image() {
50+
const img = container!.querySelector("img");
51+
expect(img).not.toBeNull();
52+
return img!;
53+
}
54+
55+
// Stands in for the browser failing to decode the current source.
56+
async function failDecode() {
57+
const img = image();
58+
await act(() => {
59+
img.dispatchEvent(new Event("error"));
60+
});
61+
return img;
62+
}
63+
64+
function expectDecodeErrorFor(onError: ReturnType<typeof vi.fn>, img: HTMLImageElement) {
65+
expect(onError).toHaveBeenCalledWith(expect.objectContaining({ type: "error", target: img }));
66+
}
67+
3868
it.each([
3969
{ name: "photo.HEIC", mimeType: undefined },
4070
{ name: "photo", mimeType: "image/heif" },
4171
])(
4272
"converts $name after native decoding fails and releases its preview",
4373
async ({ name, mimeType }) => {
44-
await act(() => {
45-
renderer = create(
46-
<AttachmentImage src="https://environment.test/photo" name={name} mimeType={mimeType} />,
47-
);
48-
});
74+
await render(
75+
<AttachmentImage src="https://environment.test/photo" name={name} mimeType={mimeType} />,
76+
);
4977
expect(fetchImage).not.toHaveBeenCalled();
50-
await act(() => renderer.root.findByType("img").props.onError(decodeError));
51-
expect(renderer.root.findByType("img").props.src).toBe("blob:jpeg");
78+
await failDecode();
79+
expect(image().getAttribute("src")).toBe("blob:jpeg");
5280
expect(prepareImageForAttachment).toHaveBeenCalledWith(
5381
expect.objectContaining({ name, type: "image/heic" }),
5482
50 * 1024 * 1024,
5583
);
56-
await act(() => renderer.unmount());
84+
await act(() => root!.unmount());
85+
root = undefined;
5786
expect(revokeUrl).toHaveBeenCalledWith("blob:jpeg");
5887
},
5988
);
6089

6190
it("leaves PNG errors to the caller without fetching or converting", async () => {
6291
const onError = vi.fn();
63-
await act(() => {
64-
renderer = create(<AttachmentImage src="blob:png" name="photo.png" onError={onError} />);
65-
});
66-
await act(() => renderer.root.findByType("img").props.onError(decodeError));
67-
expect(onError).toHaveBeenCalledWith(decodeError);
92+
await render(<AttachmentImage src="blob:png" name="photo.png" onError={onError} />);
93+
expectDecodeErrorFor(onError, await failDecode());
6894
expect(fetchImage).not.toHaveBeenCalled();
6995
});
7096

7197
it("reports failed HEIC conversion through the existing error handler", async () => {
7298
const onError = vi.fn();
7399
vi.mocked(prepareImageForAttachment).mockResolvedValue({ ok: false, reason: "unreadable" });
74-
await act(() => {
75-
renderer = create(<AttachmentImage src="blob:heic" name="photo.heif" onError={onError} />);
76-
});
77-
await act(() => renderer.root.findByType("img").props.onError(decodeError));
78-
expect(onError).toHaveBeenCalledWith(decodeError);
100+
await render(<AttachmentImage src="blob:heic" name="photo.heif" onError={onError} />);
101+
expectDecodeErrorFor(onError, await failDecode());
79102
expect(URL.createObjectURL).not.toHaveBeenCalled();
80103
});
81104

@@ -86,13 +109,11 @@ it("discards an old decode when navigating to a different source", async () => {
86109
finishDecode = resolve;
87110
}),
88111
);
89-
await act(() => {
90-
renderer = create(<AttachmentImage src="blob:first" name="photo.heic" />);
91-
});
92-
await act(() => renderer.root.findByType("img").props.onError(decodeError));
93-
await act(() => renderer.update(<AttachmentImage src="blob:second" name="photo.heic" />));
112+
await render(<AttachmentImage src="blob:first" name="photo.heic" />);
113+
await failDecode();
114+
await render(<AttachmentImage src="blob:second" name="photo.heic" />);
94115
await act(() => finishDecode({ ok: true, file: jpeg, recompressed: true }));
95-
expect(renderer.root.findByType("img").props.src).toBe("blob:second");
116+
expect(image().getAttribute("src")).toBe("blob:second");
96117
expect(URL.createObjectURL).not.toHaveBeenCalled();
97118
expect(fetchImage.mock.calls[0]?.[1].signal.aborted).toBe(true);
98119
});

0 commit comments

Comments
 (0)