Skip to content
TypeScript

test(web): file browser and attachment image tests run in a real browser (#21297)

Julius Marminge97efada6a91c
diff --git a/apps/web/src/components/files/FileBrowserPanel.test.tsx b/apps/web/src/components/files/FileBrowserPanel.browser.test.tsx
similarity index 71%
rename from apps/web/src/components/files/FileBrowserPanel.test.tsx
rename to apps/web/src/components/files/FileBrowserPanel.browser.test.tsx
index e2b273b1aba..4f8f9a5d44b 100644
--- a/apps/web/src/components/files/FileBrowserPanel.test.tsx
+++ b/apps/web/src/components/files/FileBrowserPanel.browser.test.tsx
@@ -1,11 +1,8 @@
-import { FileTree } from "@pierre/trees/react";
-import type { FileTree as FileTreeModel } from "@pierre/trees";
import { EnvironmentId, type ProjectEntry } from "@t3tools/contracts";
import { act, type ReactNode } from "react";
-import { create, type ReactTestRenderer } from "react-test-renderer";
+import { createRoot, type Root } from "react-dom/client";
import { afterEach, beforeEach, describe, expect, it, vi } from "vite-plus/test";
-import { InputGroupInput } from "~/components/ui/input-group";
import FileBrowserPanel from "./FileBrowserPanel";
const files = vi.hoisted(() => ({
@@ -13,6 +10,7 @@ const files = vi.hoisted(() => ({
searchEntries: [] as ProjectEntry[],
searchPending: false,
searchError: null as string | null,
+ loadingDirectories: new Set<string>() as ReadonlySet<string>,
load: vi.fn(async () => {}),
refresh: vi.fn(),
}));
@@ -20,6 +18,7 @@ const files = vi.hoisted(() => ({
vi.mock("./useDirectoryEntries", () => ({
useDirectoryEntries: () => ({
entries: files.directoryEntries,
+ loadingDirectories: files.loadingDirectories,
load: files.load,
refresh: files.refresh,
ready: true,
@@ -50,7 +49,8 @@ vi.mock("~/components/ui/tooltip", () => ({
}));
describe("Files panel search", () => {
- let renderer: ReactTestRenderer | undefined;
+ let root: Root | undefined;
+ let container: HTMLDivElement | undefined;
const props = {
environmentId: EnvironmentId.make("test-environment"),
cwd: "/workspace",
@@ -62,36 +62,47 @@ describe("Files panel search", () => {
};
async function render() {
- await act(async () => {
- if (renderer) renderer.update(<FileBrowserPanel {...props} />);
- else renderer = create(<FileBrowserPanel {...props} />);
- });
+ if (!container) {
+ container = document.body.appendChild(document.createElement("div"));
+ // The tree virtualizes its rows, so it needs a real viewport to render any.
+ container.style.cssText =
+ "display: flex; flex-direction: column; width: 320px; height: 480px;";
+ root = createRoot(container);
+ }
+ await act(async () => root!.render(<FileBrowserPanel {...props} />));
+ }
+
+ function searchInput() {
+ const input = container!.querySelector<HTMLInputElement>('input[type="search"]');
+ expect(input).not.toBeNull();
+ return input!;
}
async function search(value: string) {
+ const input = searchInput();
+ // React tracks the last value it saw on the element, so set it through the native setter.
+ Object.getOwnPropertyDescriptor(HTMLInputElement.prototype, "value")!.set!.call(input, value);
await act(async () => {
- renderer!.root.findByType(InputGroupInput).props.onChange({ target: { value } });
+ input.dispatchEvent(new Event("input", { bubbles: true }));
});
}
function visiblePaths() {
- const trees = renderer!.root.findAllByType(FileTree);
- if (trees.length === 0) return [];
- const model: FileTreeModel = trees[0]!.props.model;
- return model.getVisibleRows(0, model.getVisibleCount()).map((row) => row.path);
+ const tree = container!.querySelector("file-tree-container");
+ if (!tree) return [];
+ return [...tree.shadowRoot!.querySelectorAll("[data-item-path]")].map((row) =>
+ row.getAttribute("data-item-path"),
+ );
}
function hasMessage(message: string) {
- return (
- renderer!.root.findAll((node) => node.type === "div" && node.props.children === message)
- .length > 0
+ return [...container!.querySelectorAll("div")].some(
+ (node) => node.childNodes.length === 1 && node.textContent === message,
);
}
beforeEach(() => {
- vi.useFakeTimers();
vi.stubGlobal("IS_REACT_ACT_ENVIRONMENT", true);
- vi.stubGlobal("document", new EventTarget());
files.directoryEntries = [
{ path: "src", kind: "directory" },
{ path: "src/app.ts", kind: "file" },
@@ -103,10 +114,10 @@ describe("Files panel search", () => {
});
afterEach(async () => {
- await act(async () => renderer?.unmount());
- renderer = undefined;
- vi.runOnlyPendingTimers();
- vi.useRealTimers();
+ await act(async () => root?.unmount());
+ container?.remove();
+ root = undefined;
+ container = undefined;
vi.unstubAllGlobals();
});
@@ -154,12 +165,12 @@ describe("Files panel search", () => {
await search("missing-file");
expect(visiblePaths()).toEqual([]);
+ const input = searchInput();
+ input.focus();
await act(async () => {
- renderer!.root.findByType(InputGroupInput).props.onKeyDown({
- key: "Escape",
- currentTarget: { blur: vi.fn() },
- });
+ input.dispatchEvent(new KeyboardEvent("keydown", { key: "Escape", bubbles: true }));
});
+ expect(document.activeElement).not.toBe(input);
expect(visiblePaths()).toEqual(["src/", "package.json"]);
expect(hasMessage("No matching files.")).toBe(false);
});
@@ -170,6 +181,6 @@ describe("Files panel search", () => {
await search("missing-file");
expect(visiblePaths()).toEqual([]);
expect(hasMessage("No matching files.")).toBe(false);
- expect(JSON.stringify(renderer!.toJSON())).toContain("Workspace search failed.");
+ expect(container!.textContent).toContain("Workspace search failed.");
});
});
diff --git a/apps/web/src/components/media/AttachmentImage.test.tsx b/apps/web/src/components/media/AttachmentImage.browser.test.tsx
similarity index 58%
rename from apps/web/src/components/media/AttachmentImage.test.tsx
rename to apps/web/src/components/media/AttachmentImage.browser.test.tsx
index 1358d98ae29..a99c64dff9a 100644
--- a/apps/web/src/components/media/AttachmentImage.test.tsx
+++ b/apps/web/src/components/media/AttachmentImage.browser.test.tsx
@@ -1,5 +1,5 @@
-import { act, type SyntheticEvent } from "react";
-import { create, type ReactTestRenderer } from "react-test-renderer";
+import { act, type ReactNode } from "react";
+import { createRoot, type Root } from "react-dom/client";
import { afterEach, beforeEach, expect, it, vi } from "vite-plus/test";
import { AttachmentImage } from "./AttachmentImage";
import { prepareImageForAttachment } from "../../lib/imageCompression";
@@ -9,10 +9,10 @@ vi.mock("../../lib/imageCompression", async (importOriginal) => ({
prepareImageForAttachment: vi.fn(),
}));
-let renderer: ReactTestRenderer;
+let root: Root | undefined;
+let container: HTMLDivElement | undefined;
const fetchImage = vi.fn();
const revokeUrl = vi.fn();
-const decodeError = {} as SyntheticEvent<HTMLImageElement>;
const jpeg = new File(["jpeg"], "photo.jpg", { type: "image/jpeg" });
beforeEach(() => {
@@ -29,53 +29,76 @@ beforeEach(() => {
});
afterEach(async () => {
- await act(() => renderer?.unmount());
+ await act(() => root?.unmount());
+ container?.remove();
+ root = undefined;
+ container = undefined;
vi.restoreAllMocks();
vi.unstubAllGlobals();
vi.clearAllMocks();
});
+async function render(element: ReactNode) {
+ if (!container) {
+ container = document.body.appendChild(document.createElement("div"));
+ root = createRoot(container);
+ }
+ await act(() => root!.render(element));
+}
+
+function image() {
+ const img = container!.querySelector("img");
+ expect(img).not.toBeNull();
+ return img!;
+}
+
+// Stands in for the browser failing to decode the current source.
+async function failDecode() {
+ const img = image();
+ await act(() => {
+ img.dispatchEvent(new Event("error"));
+ });
+ return img;
+}
+
+function expectDecodeErrorFor(onError: ReturnType<typeof vi.fn>, img: HTMLImageElement) {
+ expect(onError).toHaveBeenCalledWith(expect.objectContaining({ type: "error", target: img }));
+}
+
it.each([
{ name: "photo.HEIC", mimeType: undefined },
{ name: "photo", mimeType: "image/heif" },
])(
"converts $name after native decoding fails and releases its preview",
async ({ name, mimeType }) => {
- await act(() => {
- renderer = create(
- <AttachmentImage src="https://environment.test/photo" name={name} mimeType={mimeType} />,
- );
- });
+ await render(
+ <AttachmentImage src="https://environment.test/photo" name={name} mimeType={mimeType} />,
+ );
expect(fetchImage).not.toHaveBeenCalled();
- await act(() => renderer.root.findByType("img").props.onError(decodeError));
- expect(renderer.root.findByType("img").props.src).toBe("blob:jpeg");
+ await failDecode();
+ expect(image().getAttribute("src")).toBe("blob:jpeg");
expect(prepareImageForAttachment).toHaveBeenCalledWith(
expect.objectContaining({ name, type: "image/heic" }),
50 * 1024 * 1024,
);
- await act(() => renderer.unmount());
+ await act(() => root!.unmount());
+ root = undefined;
expect(revokeUrl).toHaveBeenCalledWith("blob:jpeg");
},
);
it("leaves PNG errors to the caller without fetching or converting", async () => {
const onError = vi.fn();
- await act(() => {
- renderer = create(<AttachmentImage src="blob:png" name="photo.png" onError={onError} />);
- });
- await act(() => renderer.root.findByType("img").props.onError(decodeError));
- expect(onError).toHaveBeenCalledWith(decodeError);
+ await render(<AttachmentImage src="blob:png" name="photo.png" onError={onError} />);
+ expectDecodeErrorFor(onError, await failDecode());
expect(fetchImage).not.toHaveBeenCalled();
});
it("reports failed HEIC conversion through the existing error handler", async () => {
const onError = vi.fn();
vi.mocked(prepareImageForAttachment).mockResolvedValue({ ok: false, reason: "unreadable" });
- await act(() => {
- renderer = create(<AttachmentImage src="blob:heic" name="photo.heif" onError={onError} />);
- });
- await act(() => renderer.root.findByType("img").props.onError(decodeError));
- expect(onError).toHaveBeenCalledWith(decodeError);
+ await render(<AttachmentImage src="blob:heic" name="photo.heif" onError={onError} />);
+ expectDecodeErrorFor(onError, await failDecode());
expect(URL.createObjectURL).not.toHaveBeenCalled();
});
@@ -86,13 +109,11 @@ it("discards an old decode when navigating to a different source", async () => {
finishDecode = resolve;
}),
);
- await act(() => {
- renderer = create(<AttachmentImage src="blob:first" name="photo.heic" />);
- });
- await act(() => renderer.root.findByType("img").props.onError(decodeError));
- await act(() => renderer.update(<AttachmentImage src="blob:second" name="photo.heic" />));
+ await render(<AttachmentImage src="blob:first" name="photo.heic" />);
+ await failDecode();
+ await render(<AttachmentImage src="blob:second" name="photo.heic" />);
await act(() => finishDecode({ ok: true, file: jpeg, recompressed: true }));
- expect(renderer.root.findByType("img").props.src).toBe("blob:second");
+ expect(image().getAttribute("src")).toBe("blob:second");
expect(URL.createObjectURL).not.toHaveBeenCalled();
expect(fetchImage.mock.calls[0]?.[1].signal.aborted).toBe(true);
});