TypeScript
test(web): jsdom-leftovers tests run in a real browser (#20862)
Julius Marminge759f68fdf5b2
diff --git a/apps/web/src/components/ComposerPromptEditorTiptap.citationDraft.test.tsx b/apps/web/src/components/ComposerPromptEditorTiptap.citationDraft.browser.test.tsxsimilarity index 67%rename from apps/web/src/components/ComposerPromptEditorTiptap.citationDraft.test.tsxrename to apps/web/src/components/ComposerPromptEditorTiptap.citationDraft.browser.test.tsxindex e1c8aa00cf8..98ae97a2e8c 100644--- a/apps/web/src/components/ComposerPromptEditorTiptap.citationDraft.test.tsx+++ b/apps/web/src/components/ComposerPromptEditorTiptap.citationDraft.browser.test.tsx@@ -1,5 +1,3 @@-// @vitest-environment jsdom-import { EnvironmentId, MessageId, ThreadId } from "@t3tools/contracts";import {serializeAssistantCitation,@@ -9,22 +7,15 @@ import { act, createRef, useState, type ReactNode } from "react";import { createRoot, type Root } from "react-dom/client";import { afterEach, beforeEach, expect, it, vi } from "vite-plus/test";-import type { AssistantCitationSourceAnchor } from "~/lib/assistantTextSelection";+import { page, userEvent } from "vite-plus/test/browser";-vi.mock("./chat/AssistantCitationSource", () => ({- observeAssistantCitationCommentSource: () => () => {},-}));-vi.mock("@tanstack/react-router", () => ({- useNavigate: () => () => {},- Link: ({ children }: { children: ReactNode }) => <a>{children}</a>,-}));-vi.mock("./ui/popover", () => ({- Popover: ({ children }: { children: ReactNode }) => <>{children}</>,- PopoverTrigger: ({ "aria-label": label }: { "aria-label": string }) => (- <button aria-label={label} />- ),- PopoverPopup: ({ children }: { children: ReactNode }) => <>{children}</>,- PopoverClose: ({ children }: { children: ReactNode }) => <>{children}</>,+import { findAssistantCitationSourceAnchor } from "~/lib/assistantTextSelection";++// No router is mounted; the citation chip only needs navigation to exist.+vi.mock(import("@tanstack/react-router"), async (original) => ({+ ...(await original()),+ useNavigate: () => async () => {},+ Link: (({ children }: { children: ReactNode }) => <a>{children}</a>) as never,}));import { ComposerPromptEditor, type ComposerPromptEditorHandle } from "./ComposerPromptEditor";@@ -46,7 +37,6 @@ let root: Root;let container: HTMLDivElement;beforeEach(() => {- vi.stubGlobal("IS_REACT_ACT_ENVIRONMENT", true);container = document.createElement("div");document.body.append(container);root = createRoot(container);@@ -55,7 +45,6 @@ beforeEach(() => {afterEach(async () => {await act(async () => root.unmount());container.remove();- vi.unstubAllGlobals();});function Composer({@@ -69,6 +58,15 @@ function Composer({const [answer, setAnswer] = useState("");return (<>+ <div data-assistant-citation-viewport="">+ <p+ data-assistant-citation-source={citation.messageId}+ data-assistant-citation-environment={citation.environmentId}+ data-assistant-citation-thread={citation.threadId}+ >+ hello world+ </p>+ </div><output data-prompt={prompt} data-answer={answer} /><ComposerPromptEditoreditorRef={editorRef}@@ -93,22 +91,21 @@ it("keeps an unsaved citation comment when a question takes the composer", asyncconst drafts = () => container.querySelector("output")?.dataset;await act(async () => root.render(<Composer question={false} editorRef={editorRef} />));+ const sourceAnchor = findAssistantCitationSourceAnchor(document, citation);+ if (!sourceAnchor) throw new Error("Citation source did not resolve");await act(async () =>editorRef.current?.requestCitationComment({previousValue: "See ",value: promptBefore,citationStart: "See ".length,- sourceAnchor: {} as AssistantCitationSourceAnchor,+ sourceAnchor,insertedSpaces: { before: false, after: true },}),);- const textarea = container.querySelector("textarea");- if (!textarea) throw new Error("Comment editor did not open");- await act(async () => {- const setValue = Object.getOwnPropertyDescriptor(HTMLTextAreaElement.prototype, "value")?.set;- setValue?.call(textarea, "check this");- textarea.dispatchEvent(new Event("input", { bubbles: true }));- });+ const comment = page.getByLabelText("Comment on selected text");+ await expect.element(comment).toBeVisible();+ await comment.click();+ await userEvent.keyboard("check this");await act(async () => root.render(<Composer question editorRef={editorRef} />));expect(drafts()?.answer).toBe("");@@ -117,5 +114,5 @@ it("keeps an unsaved citation comment when a question takes the composer", asyncexpect(drafts()?.prompt).toBe(`See ${serializeAssistantCitation(withAssistantCitationComment(citation, "check this"))} `,);- expect(container.querySelector('[aria-label="Edit citation comment"]')).not.toBeNull();+ await expect.element(page.getByLabelText("Edit citation comment")).toBeInTheDocument();});diff --git a/apps/web/src/components/chat/HtmlRenderDialog.test.tsx b/apps/web/src/components/chat/HtmlRenderDialog.browser.test.tsxsimilarity index 83%rename from apps/web/src/components/chat/HtmlRenderDialog.test.tsxrename to apps/web/src/components/chat/HtmlRenderDialog.browser.test.tsxindex d0c28267ed7..275f50ca37e 100644--- a/apps/web/src/components/chat/HtmlRenderDialog.test.tsx+++ b/apps/web/src/components/chat/HtmlRenderDialog.browser.test.tsx@@ -1,12 +1,13 @@-// @vitest-environment jsdom-import { act } from "react";import { createRoot, type Root } from "react-dom/client";import { afterEach, beforeEach, expect, it, vi } from "vite-plus/test";+import { page, userEvent } from "vite-plus/test/browser";import { htmlRenderTheme, HTML_RENDER_DEFAULT_FONTS } from "@t3tools/shared/htmlRender";import { T3_CODE_DARK_THEME_COLORS } from "@t3tools/shared/themePalettes";import { EnvironmentId, ThreadId } from "@t3tools/contracts";+import "~/index.css";+import { HtmlRenderDialog } from "./HtmlRenderDialog";import { HtmlRenderFrame } from "./HtmlRenderFrame";@@ -17,11 +18,16 @@ const { cachedUrl, refresh, showError, openLink, openChangeRequestLink } = vi.hoopenLink: vi.fn(),openChangeRequestLink: vi.fn(),}));-vi.mock("~/browser/useOpenLink", () => ({ useOpenLink: () => openLink }));-vi.mock("~/lib/openPullRequestLink", () => ({+vi.mock(import("~/browser/useOpenLink"), async (original) => ({+ ...(await original()),+ useOpenLink: () => openLink,+}));+vi.mock(import("~/lib/openPullRequestLink"), async (original) => ({+ ...(await original()),useOpenChangeRequestLink: () => openChangeRequestLink,}));-vi.mock("~/assets/assetUrls", () => ({+vi.mock(import("~/assets/assetUrls"), async (original) => ({+ ...(await original()),useAssetUrlState: () => ({_tag: "Success",url: "https://environment.test/original.html",@@ -29,9 +35,12 @@ vi.mock("~/assets/assetUrls", () => ({}),useAssetUrlRefresh: () => refresh,}));-vi.mock("../ui/toast", () => ({ toastManager: { add: showError } }));--vi.mock("~/hooks/useHtmlRenderTheme", () => ({+vi.mock(import("../ui/toast"), async (original) => {+ const actual = await original();+ return { ...actual, toastManager: { ...actual.toastManager, add: showError } };+});+vi.mock(import("~/hooks/useHtmlRenderTheme"), async (original) => ({+ ...(await original()),useHtmlRenderTheme: () =>htmlRenderTheme(T3_CODE_DARK_THEME_COLORS, "dark", HTML_RENDER_DEFAULT_FONTS),}));@@ -41,15 +50,6 @@ let container: HTMLDivElement;const onClose = vi.fn();beforeEach(async () => {- vi.stubGlobal("IS_REACT_ACT_ENVIRONMENT", true);- vi.stubGlobal(- "ResizeObserver",- class {- observe() {}- disconnect() {}- unobserve() {}- },- );refresh.mockReset();cachedUrl.lifeMs = 60 * 60_000;openLink.mockReset().mockResolvedValue(undefined);@@ -73,23 +73,25 @@ beforeEach(async () => {afterEach(async () => {await act(() => root.unmount());container.remove();- vi.unstubAllGlobals();});+function button(label: string) {+ return page.getByRole("button", { name: label, exact: true });+}++// A trusted click, so the page also gets the user activation the link handler requires.async function click(label: string) {- const button = document.querySelector<HTMLButtonElement>(`button[aria-label="${label}"]`);- expect(button).not.toBeNull();- await act(() => button!.click());+ await button(label).click();}it("zooms the loaded page within bounds and resets without reloading it", async () => {const frame = document.querySelector("iframe")!;const src = frame.src;- for (let step = 0; step < 6; step += 1) await click("Zoom in");- expect(document.querySelector<HTMLButtonElement>('[aria-label="Zoom in"]')!.disabled).toBe(true);+ for (let step = 0; step < 4; step += 1) await click("Zoom in");+ await expect.element(button("Zoom in")).toBeDisabled();expect(frame.parentElement!.style.getPropertyValue("zoom")).toBe("2");- for (let step = 0; step < 8; step += 1) await click("Zoom out");- expect(document.querySelector<HTMLButtonElement>('[aria-label="Zoom out"]')!.disabled).toBe(true);+ for (let step = 0; step < 6; step += 1) await click("Zoom out");+ await expect.element(button("Zoom out")).toBeDisabled();expect(frame.parentElement!.style.getPropertyValue("zoom")).toBe("0.5");await click("Reset zoom");expect(frame.parentElement!.style.getPropertyValue("zoom")).toBe("1");@@ -102,11 +104,7 @@ it("closes with the close button or Escape", async () => {await click("Close");expect(onClose).toHaveBeenCalledOnce();onClose.mockClear();- await act(() => {- document.activeElement?.dispatchEvent(- new KeyboardEvent("keydown", { key: "Escape", bubbles: true }),- );- });+ await userEvent.keyboard("{Escape}");expect(onClose).toHaveBeenCalledOnce();});diff --git a/apps/web/src/components/settings/StorageSettings.test.tsx b/apps/web/src/components/settings/StorageSettings.browser.test.tsxsimilarity index 81%rename from apps/web/src/components/settings/StorageSettings.test.tsxrename to apps/web/src/components/settings/StorageSettings.browser.test.tsxindex c479a6e10e9..dacb009d332 100644--- a/apps/web/src/components/settings/StorageSettings.test.tsx+++ b/apps/web/src/components/settings/StorageSettings.browser.test.tsx@@ -1,4 +1,3 @@-// @vitest-environment jsdomimport { RegistryProvider } from "@effect/atom-react";import {DEFAULT_SERVER_SETTINGS,@@ -16,20 +15,30 @@ const state = vi.hoisted(() => ({report: null as StorageCleanupReport | null,}));-vi.mock("../../state/server", async () => {+vi.mock(import("../../state/server"), async (original) => {+ const actual = await original();const { Atom } = await import("effect/reactivity");const report = Atom.make(() => ({ _tag: "Success", value: state.report, waiting: false }));const allowed = Atom.make(true);return {+ ...actual,serverEnvironment: {- storageCleanupReport: () => report,- runStorageCleanup: { permissionAtom: () => allowed },+ ...actual.serverEnvironment,+ storageCleanupReport: (() => report) as never,+ runStorageCleanup: {+ ...actual.serverEnvironment.runStorageCleanup,+ permissionAtom: () => allowed,+ },},};});-vi.mock("../../state/use-atom-command", () => ({ useAtomCommand: () => state.run }));-vi.mock("./SettingsScopeContext", () => ({- useSettingsScope: () => {+vi.mock(import("../../state/use-atom-command"), async (original) => ({+ ...(await original()),+ useAtomCommand: (() => state.run) as never,+}));+vi.mock(import("./SettingsScopeContext"), async (original) => ({+ ...(await original()),+ useSettingsScope: (() => {const environment = {environmentId: "env",label: "Machine",@@ -51,38 +60,34 @@ vi.mock("./SettingsScopeContext", () => ({targets: [],target: null,};- },+ }) as never,}));-vi.mock("./useScopedSettings", () => ({- useScopedSettings: () => state.settings,+vi.mock(import("./useScopedSettings"), async (original) => ({+ ...(await original()),+ useScopedSettings: (() => state.settings) as never,useScopedSettingsMixed: () => false,useUpdateScopedSettings: () => vi.fn(),useClearScopedSettings: () => vi.fn(),}));-vi.mock("./settingsLayout", () => ({- SettingsPageContainer: ({ children }: { children: ReactNode }) => children,- SettingsSection: ({ children }: { children: ReactNode }) => children,- SettingsRow: ({- title,- description,- control,- }: {- title: ReactNode;- description: ReactNode;- control: ReactNode;- }) => (+// The real page container needs a router and the real row reads write permission and+// overrides from live environment state; this suite is about the cleanup panel.+vi.mock(import("./settingsLayout"), async (original) => ({+ ...(await original()),+ SettingsPageContainer: (({ children }: { children: ReactNode }) => children) as never,+ SettingsRow: ({ title, description, control, children }) => (<div><h3>{title}</h3>{description}{control}+ {children}</div>),- SettingResetButton: () => null,- useRelativeTimeTick: () => undefined,- useSettingsSearchTargetId: () => null,- useSettingsSearchTarget: () => undefined,+ SettingResetButton: (() => null) as never,}));-vi.mock("../ui/toast", () => ({ toastManager: { add: vi.fn() } }));+vi.mock(import("../ui/toast"), async (original) => {+ const actual = await original();+ return { ...actual, toastManager: { ...actual.toastManager, add: vi.fn() } };+});import { StorageSettingsPanel } from "./StorageSettings";@@ -90,7 +95,6 @@ let root: Root;let container: HTMLDivElement;beforeEach(() => {- vi.stubGlobal("IS_REACT_ACT_ENVIRONMENT", true);state.settings = {...DEFAULT_SERVER_SETTINGS,storageCleanup: {@@ -115,7 +119,6 @@ beforeEach(() => {afterEach(async () => {await act(async () => root.unmount());container.remove();- vi.unstubAllGlobals();});async function render() {diff --git a/apps/web/src/components/settings/settingsScopeRetention.test.tsx b/apps/web/src/components/settings/settingsScopeRetention.browser.test.tsxsimilarity index 68%rename from apps/web/src/components/settings/settingsScopeRetention.test.tsxrename to apps/web/src/components/settings/settingsScopeRetention.browser.test.tsxindex a44d73e0fda..8c029938b17 100644--- a/apps/web/src/components/settings/settingsScopeRetention.test.tsx+++ b/apps/web/src/components/settings/settingsScopeRetention.browser.test.tsx@@ -1,4 +1,3 @@-// @vitest-environment jsdomimport { act, useState, type ReactNode } from "react";import { createRoot, type Root } from "react-dom/client";import { afterEach, beforeEach, expect, it, vi } from "vite-plus/test";@@ -14,28 +13,28 @@ const state = vi.hoisted(() => ({scope: { search: {}, environmentId: null } as ScopeState,}));-vi.mock("@tanstack/react-router", async (importOriginal) => ({- ...(await importOriginal<typeof import("@tanstack/react-router")>()),- createFileRoute: () => (options: { component: () => ReactNode }) => ({+vi.mock(import("@tanstack/react-router"), async (original) => ({+ ...(await original()),+ createFileRoute: (() => (options: { component: () => ReactNode }) => ({options,useSearch: () => state.scope.search,useNavigate: () => vi.fn(),- }),- useLocation: (options?: { select: (location: unknown) => unknown }) => {+ })) as never,+ useLocation: ((options?: { select: (location: unknown) => unknown }) => {const location = { pathname: state.pathname, hash: "", state: {} };return options ? options.select(location) : location;- },- Outlet: () => <StatefulContent />,- redirect: vi.fn(),+ }) as never,+ Outlet: (() => <StatefulContent />) as never,}));-vi.mock("./SettingsScopeContext", async () => {+vi.mock(import("./SettingsScopeContext"), async (original) => {const { createContext, useContext } = await import("react");const Scope = createContext<ScopeState>(state.scope);return {- SettingsScopeProvider: ({ children }: { children: ReactNode }) => (+ ...(await original()),+ SettingsScopeProvider: (({ children }: { children: ReactNode }) => (<Scope value={state.scope}>{children}</Scope>- ),- useSettingsScope: () => {+ )) as never,+ useSettingsScope: (() => {const { search, environmentId } = useContext(Scope);return {search,@@ -43,23 +42,37 @@ vi.mock("./SettingsScopeContext", async () => {environment: environmentId ? { environmentId } : null,connectedEnvironments: environmentId ? [{}] : [],};- },+ }) as never,};});-vi.mock("../../state/environments", () => ({ useEnvironments: () => ({ environments: [] }) }));-vi.mock("../ui/sidebar", () => ({- SidebarInset: ({ children }: { children: ReactNode }) => <div>{children}</div>,+vi.mock(import("../../state/environments"), async (original) => ({+ ...(await original()),+ useEnvironments: (() => ({ environments: [] })) as never,}));-vi.mock("../WorkspacePageHeader", () => ({- WorkspacePageHeader: ({ children }: { children: ReactNode }) => <div>{children}</div>,+vi.mock(import("../ui/sidebar"), async (original) => ({+ ...(await original()),+ SidebarInset: ({ children }: { children?: ReactNode }) => <div>{children}</div>,}));-vi.mock("./settingsLayout", () => ({- SettingsPageContainer: ({ children }: { children: ReactNode }) => <div>{children}</div>,+vi.mock(import("../WorkspacePageHeader"), async (original) => ({+ ...(await original()),+ WorkspacePageHeader: ({ children }: { children?: ReactNode }) => <div>{children}</div>,+}));+vi.mock(import("./SettingsBreadcrumb"), async (original) => ({+ ...(await original()),+ SettingsBreadcrumb: (() => null) as never,+}));+vi.mock(import("../sidebar/mainAppLocation"), async (original) => ({+ ...(await original()),+ useNavigateToMainApp: () => vi.fn(),+}));+vi.mock(import("../../hooks/useNavigateBack"), async (original) => ({+ ...(await original()),+ useEscapeToGoBack: () => undefined,+}));+vi.mock(import("./SettingsPanels"), async (original) => ({+ ...(await original()),+ useSettingsRestore: (() => ({ changedSettingLabels: [] })) as never,}));-vi.mock("./SettingsBreadcrumb", () => ({ SettingsBreadcrumb: () => null }));-vi.mock("../sidebar/mainAppLocation", () => ({ useNavigateToMainApp: () => vi.fn() }));-vi.mock("../../hooks/useNavigateBack", () => ({ useEscapeToGoBack: () => undefined }));-vi.mock("./SettingsPanels", () => ({ useSettingsRestore: () => ({ changedSettingLabels: [] }) }));import { Route } from "../../routes/settings";@@ -86,7 +99,6 @@ function retainedValue() {}beforeEach(() => {- vi.stubGlobal("IS_REACT_ACT_ENVIRONMENT", true);container = document.createElement("div");document.body.append(container);root = createRoot(container);@@ -94,7 +106,6 @@ beforeEach(() => {afterEach(async () => {await act(async () => root.unmount());container.remove();- vi.unstubAllGlobals();});const first = { search: { machine: "first", project: "one" }, environmentId: "first" };