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

AttachmentFilePreview.browser.test.tsx

117 lines4.1 KB

1import { EnvironmentId } from "@t3tools/contracts";
2import { act } from "react";
3import { createRoot, type Root } from "react-dom/client";
4import { afterEach, beforeEach, describe, expect, it, vi } from "vite-plus/test";
5​
6const { refresh } = vi.hoisted(() => ({ refresh: vi.fn<() => Promise<string | null>>() }));
7​
8vi.mock(import("~/assets/assetUrls"), async (original) => ({
9 ...(await original()),
10 useAssetUrlRefresh: () => refresh,
11}));
12// The real source view highlights through a worker pool; the text it receives is what matters here.
13vi.mock(import("./ReadOnlySourcePreview"), async (original) => ({
14 ...(await original()),
15 default: ({ text }: { text: string }) => <pre>{text}</pre>,
16}));
17​
18import { AttachmentFilePreview } from "./AttachmentFilePreview";
19​
20describe("attachment HTML preview recovery", () => {
21 const originalUrl = "data:text/html,original";
22 const renewedUrl = "data:text/html,renewed";
23 let now = 0;
24 let root: Root;
25 let container: HTMLDivElement;
26​
27 beforeEach(() => {
28 vi.stubGlobal("IS_REACT_ACT_ENVIRONMENT", true);
29 now = 0;
30 vi.spyOn(Date, "now").mockImplementation(() => now);
31 refresh.mockReset().mockResolvedValueOnce(originalUrl).mockResolvedValue(renewedUrl);
32 vi.stubGlobal(
33 "fetch",
34 vi.fn(async () => new Response("<p>Captured HTML</p>")),
35 );
36 container = document.createElement("div");
37 document.body.append(container);
38 root = createRoot(container);
39 });
40​
41 afterEach(async () => {
42 await act(async () => root.unmount());
43 container.remove();
44 vi.restoreAllMocks();
45 vi.unstubAllGlobals();
46 });
47​
48 const openRemote = () =>
49 act(async () =>
50 root.render(
51 <AttachmentFilePreview
52 name="document.html"
53 mimeType="text/html"
54 sizeBytes={100}
55 asset={{ environmentId: EnvironmentId.make("test-environment"), attachmentId: "html" }}
56 />,
57 ),
58 );
59​
60 const toggleMode = async (label: string) => {
61 const button = container.querySelector<HTMLButtonElement>(`button[aria-label="${label}"]`);
62 expect(button, label).not.toBeNull();
63 await act(async () => button!.click());
64 };
65 const alert = () => container.querySelector('[role="alert"]');
66​
67 it("keeps a renewed URL for subsequent rendered and source views", async () => {
68 await openRemote();
69 expect(container.querySelector("iframe")?.getAttribute("src")).toBe(originalUrl);
70 now = 61 * 60_000;
71 await toggleMode("Show HTML source");
72 expect(fetch).toHaveBeenCalledExactlyOnceWith(renewedUrl, expect.any(Object));
73 await vi.waitFor(() =>
74 expect(container.querySelector("pre")?.textContent).toBe("<p>Captured HTML</p>"),
75 );
76​
77 await toggleMode("Show rendered page");
78 expect(container.querySelector("iframe")?.getAttribute("src")).toBe(renewedUrl);
79 await toggleMode("Show HTML source");
80 expect(refresh).toHaveBeenCalledTimes(2);
81 expect(vi.mocked(fetch).mock.calls.map(([url]) => url)).toEqual([renewedUrl, renewedUrl]);
82 });
83​
84 it("does not fetch or mark an expired URL fresh when reauthorization is unavailable", async () => {
85 await openRemote();
86 now = 61 * 60_000;
87 refresh.mockResolvedValue(null);
88 await toggleMode("Show HTML source");
89 expect(fetch).not.toHaveBeenCalled();
90 expect(alert()?.textContent).toContain("Reconnect to the environment and try again.");
91​
92 await toggleMode("Show rendered page");
93 await toggleMode("Show HTML source");
94 expect(refresh).toHaveBeenCalledTimes(3);
95 expect(fetch).not.toHaveBeenCalled();
96 });
97​
98 it("can return to rendered HTML after local source decoding fails", async () => {
99 const file = new Blob([new Uint8Array([0x3c, 0x70, 0x3e, 0xe9])], { type: "text/html" });
100 await act(async () =>
101 root.render(
102 <AttachmentFilePreview
103 name="document.html"
104 mimeType="text/html"
105 sizeBytes={file.size}
106 file={file}
107 />,
108 ),
109 );
110 await toggleMode("Show HTML source");
111 await vi.waitFor(() => expect(alert()?.textContent).toContain("not UTF-8"));
112​
113 await toggleMode("Show rendered page");
114 expect(alert()).toBeNull();
115 expect(container.querySelector("iframe")?.title).toBe("document.html");
116 });
117});