Skip to content

Linger is An Open-Source Personal Agent That Runs Fully on Your PC. We aim to break Big Tech’s grip on AI by bringing powerful local AI to everyday computers through efficient model–harness co-design, so everyone can run their own.

test(web): share the test environment between files without module mocks

shoudi zheng047f5a1c2d37
diff --git a/apps/web/src/components/ui/action-menu.test.tsx b/apps/web/src/components/ui/action-menu.test.tsx
index a837d820..29c1a766 100644
--- a/apps/web/src/components/ui/action-menu.test.tsx
+++ b/apps/web/src/components/ui/action-menu.test.tsx
@@ -1,5 +1,6 @@
import { fireEvent, render, screen, within } from "@testing-library/react";
import { describe, expect, it, vi } from "vitest";
+import { defineGlobalProperty } from "@/test/global-properties";
import { ActionMenu } from "./action-menu";
@@ -96,11 +97,11 @@ describe("ActionMenu", () => {
({ triggerLeft, expectedLeft }) => {
const originalWidth = window.innerWidth;
const originalHeight = window.innerHeight;
- Object.defineProperty(window, "innerWidth", {
+ defineGlobalProperty(window, "innerWidth", {
configurable: true,
value: 1024,
});
- Object.defineProperty(window, "innerHeight", {
+ defineGlobalProperty(window, "innerHeight", {
configurable: true,
value: 768,
});
@@ -134,11 +135,11 @@ describe("ActionMenu", () => {
);
} finally {
bounds.mockRestore();
- Object.defineProperty(window, "innerWidth", {
+ defineGlobalProperty(window, "innerWidth", {
configurable: true,
value: originalWidth,
});
- Object.defineProperty(window, "innerHeight", {
+ defineGlobalProperty(window, "innerHeight", {
configurable: true,
value: originalHeight,
});
@@ -201,7 +202,7 @@ describe("ActionMenu", () => {
y: 8,
toJSON: () => undefined,
});
- Object.defineProperty(window, "innerWidth", {
+ defineGlobalProperty(window, "innerWidth", {
configurable: true,
value: 1024,
});
@@ -219,7 +220,7 @@ describe("ActionMenu", () => {
"right-[calc(100%+4px)]",
);
bounds.mockRestore();
- Object.defineProperty(window, "innerWidth", {
+ defineGlobalProperty(window, "innerWidth", {
configurable: true,
value: originalInnerWidth,
});
diff --git a/apps/web/src/features/library/library-layout.test.tsx b/apps/web/src/features/library/library-layout.test.tsx
index cc8b241e..d797b295 100644
--- a/apps/web/src/features/library/library-layout.test.tsx
+++ b/apps/web/src/features/library/library-layout.test.tsx
@@ -2,6 +2,7 @@ import { QueryClient, QueryClientProvider } from "@tanstack/react-query";
import { render, screen, within } from "@testing-library/react";
import { createMemoryRouter, RouterProvider } from "react-router";
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
+import { defineGlobalProperty } from "@/test/global-properties";
import { createTestTeamHubRuntime } from "@/test/teamhub-test-runtime";
import { TeamHubRuntimeProvider } from "@/features/teamhub/teamhub-runtime";
@@ -24,7 +25,7 @@ function createTestStorage(): Storage {
describe("Library layout", () => {
beforeEach(() => {
- Object.defineProperty(window, "localStorage", {
+ defineGlobalProperty(window, "localStorage", {
configurable: true,
value: createTestStorage(),
});
diff --git a/apps/web/src/features/library/library-overview.test.tsx b/apps/web/src/features/library/library-overview.test.tsx
index 3c9d853c..54e0ac01 100644
--- a/apps/web/src/features/library/library-overview.test.tsx
+++ b/apps/web/src/features/library/library-overview.test.tsx
@@ -14,6 +14,7 @@ import {
import { Suspense } from "react";
import { createMemoryRouter, RouterProvider } from "react-router";
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
+import { defineGlobalProperty } from "@/test/global-properties";
import {
createDocumentTestRuntime,
@@ -36,7 +37,7 @@ import {
describe("Library Home", () => {
beforeEach(() => {
- Object.defineProperty(window, "localStorage", {
+ defineGlobalProperty(window, "localStorage", {
configurable: true,
value: createTestStorage(),
});
diff --git a/apps/web/src/features/library/library-sidebar-scroll.test.tsx b/apps/web/src/features/library/library-sidebar-scroll.test.tsx
index baa65449..b43b917b 100644
--- a/apps/web/src/features/library/library-sidebar-scroll.test.tsx
+++ b/apps/web/src/features/library/library-sidebar-scroll.test.tsx
@@ -2,6 +2,7 @@ import { QueryClient, QueryClientProvider } from "@tanstack/react-query";
import { act, fireEvent, render, screen } from "@testing-library/react";
import { MemoryRouter } from "react-router";
import { afterEach, expect, it, vi } from "vitest";
+import { defineGlobalProperty } from "@/test/global-properties";
import { createTestTeamHubRuntime } from "@/test/teamhub-test-runtime";
import { TeamHubRuntimeProvider } from "@/features/teamhub/teamhub-runtime";
@@ -16,19 +17,19 @@ it.each([false, true])(
"restores pending sidebar scroll unless the user takes control (interrupted=%s)",
async (interrupted) => {
const positions = new WeakMap<Element, number>();
- vi.spyOn(Element.prototype, "scrollTop", "get").mockImplementation(
- function (this: Element) {
+ // One descriptor for both accessors: separate get and set spies on the
+ // same property restore out of order and leave a stale getter behind.
+ defineGlobalProperty(Element.prototype, "scrollTop", {
+ get(this: Element) {
return positions.get(this) ?? 0;
},
- );
- vi.spyOn(Element.prototype, "scrollTop", "set").mockImplementation(
- function (this: Element, value: number) {
+ set(this: Element, value: number) {
positions.set(
this,
Math.min(value, this.querySelector("[data-loaded]") ? 500 : 0),
);
},
- );
+ });
const runtime = createTestTeamHubRuntime();
const client = new QueryClient();
diff --git a/apps/web/src/features/local-computer/computer-setup-instructions.test.tsx b/apps/web/src/features/local-computer/computer-setup-instructions.test.tsx
index 1da54ebd..2d93280b 100644
--- a/apps/web/src/features/local-computer/computer-setup-instructions.test.tsx
+++ b/apps/web/src/features/local-computer/computer-setup-instructions.test.tsx
@@ -1,6 +1,7 @@
import { fireEvent, render, screen, within } from "@testing-library/react";
import { useRef } from "react";
import { afterEach, describe, expect, it, vi } from "vitest";
+import { defineGlobalProperty } from "@/test/global-properties";
import {
ComputerSetupInstructions,
@@ -8,33 +9,9 @@ import {
} from "./computer-setup-instructions";
import { ConnectComputerDialog } from "./computer-empty-states";
-const originalClipboardDescriptor = Object.getOwnPropertyDescriptor(
- navigator,
- "clipboard",
-);
-const originalSecureContextDescriptor = Object.getOwnPropertyDescriptor(
- window,
- "isSecureContext",
-);
const originalExecCommand = document.execCommand;
afterEach(() => {
- if (originalClipboardDescriptor) {
- Object.defineProperty(navigator, "clipboard", originalClipboardDescriptor);
- } else {
- Reflect.deleteProperty(navigator, "clipboard");
- }
-
- if (originalSecureContextDescriptor) {
- Object.defineProperty(
- window,
- "isSecureContext",
- originalSecureContextDescriptor,
- );
- } else {
- Reflect.deleteProperty(window, "isSecureContext");
- }
-
document.execCommand = originalExecCommand;
vi.restoreAllMocks();
});
@@ -215,14 +192,14 @@ describe("CopyValueButton", () => {
});
function setSecureContext(value: boolean) {
- Object.defineProperty(window, "isSecureContext", {
+ defineGlobalProperty(window, "isSecureContext", {
configurable: true,
value,
});
}
function setClipboard(clipboard: Pick<Clipboard, "writeText"> | undefined) {
- Object.defineProperty(navigator, "clipboard", {
+ defineGlobalProperty(navigator, "clipboard", {
configurable: true,
value: clipboard,
});
diff --git a/apps/web/src/features/memory/meeting-page.test.tsx b/apps/web/src/features/memory/meeting-page.test.tsx
index 78e0d59c..b25f7dba 100644
--- a/apps/web/src/features/memory/meeting-page.test.tsx
+++ b/apps/web/src/features/memory/meeting-page.test.tsx
@@ -275,7 +275,10 @@ describe("MeetingPage", () => {
expect(
screen.getByRole("button", { name: "Collapse Meetings" }),
).toHaveAttribute("aria-expanded", "true");
- expect(screen.getByText("The meeting summary is ready.")).toBeVisible();
+ // The summary body renders from a lazy chunk after the article appears.
+ expect(
+ await screen.findByText("The meeting summary is ready."),
+ ).toBeVisible();
expect(screen.queryByText("CRM Evidence Cache")).toBeNull();
expect(screen.queryByText("Internal CRM evidence.")).toBeNull();
expect(screen.queryByText("Client Candidates")).toBeNull();
@@ -310,7 +313,10 @@ describe("MeetingPage", () => {
name: "Meeting summary",
});
const overview = screen.getByRole("region", { name: "Meeting overview" });
- expect(summary).toHaveTextContent("Scoped the first release.");
+ // The summary body renders from a lazy chunk after the overview appears.
+ await waitFor(() =>
+ expect(summary).toHaveTextContent("Scoped the first release."),
+ );
expect(overview).not.toHaveTextContent("Scoped the first release.");
expect(overview).toHaveTextContent(
"01Release plan00:01:00 – 00:05:00Open source by October.",
@@ -332,6 +338,8 @@ describe("MeetingPage", () => {
const article = await screen.findByRole("article", {
name: "Meeting summary",
});
+ // The summary body renders from a lazy chunk after the article appears.
+ expect(await within(article).findByText("Raw session")).toBeVisible();
for (const name of ["Raw session", "Session source"]) {
expect(within(article).queryByRole("link", { name })).toBeNull();
expect(within(article).getByText(name)).toBeVisible();
diff --git a/apps/web/src/features/memory/wiki-graph-page.test.tsx b/apps/web/src/features/memory/wiki-graph-page.test.tsx
index a76fc8e2..4902e7bb 100644
--- a/apps/web/src/features/memory/wiki-graph-page.test.tsx
+++ b/apps/web/src/features/memory/wiki-graph-page.test.tsx
@@ -7,7 +7,16 @@ import {
within,
} from "@testing-library/react";
import { createMemoryRouter, RouterProvider } from "react-router";
-import { afterEach, beforeAll, describe, expect, it, vi } from "vitest";
+import {
+ afterEach,
+ beforeEach,
+ beforeAll,
+ describe,
+ expect,
+ it,
+ vi,
+} from "vitest";
+import { defineGlobalProperty } from "@/test/global-properties";
import { createTestTeamHubRuntime } from "@/test/teamhub-test-runtime";
import { LibraryLayout } from "@/features/library/library-layout";
@@ -23,9 +32,8 @@ import { WikiGraphPage } from "./wiki-graph-page";
afterEach(() => vi.restoreAllMocks());
// jsdom supplies no scroll geometry; the real-service proof verifies movement.
-Object.defineProperty(HTMLElement.prototype, "scrollTo", {
- configurable: true,
- value: vi.fn(),
+beforeEach(() => {
+ defineGlobalProperty(HTMLElement.prototype, "scrollTo", { value: vi.fn() });
});
describe("WikiGraphPage", () => {
diff --git a/apps/web/src/features/rooms/cards/decision-connection-auth-view.test.tsx b/apps/web/src/features/rooms/cards/decision-connection-auth-view.test.tsx
index eda426bf..c63bec12 100644
--- a/apps/web/src/features/rooms/cards/decision-connection-auth-view.test.tsx
+++ b/apps/web/src/features/rooms/cards/decision-connection-auth-view.test.tsx
@@ -90,6 +90,14 @@ async function setup(
return { runtime, decision, connection };
}
+// Actions render disabled until the connections load, and a click before then
+// is ignored; that happens whenever a test is the first to load the card.
+async function enabledButton(name: string) {
+ const button = await screen.findByRole("button", { name });
+ await waitFor(() => expect(button).toBeEnabled());
+ return button;
+}
+
describe("Chat connection authorization", () => {
afterEach(() => vi.restoreAllMocks());
@@ -108,9 +116,7 @@ describe("Chat connection authorization", () => {
).toHaveLength(1);
expect(document.querySelector(".card-prompt")).toBeNull();
expect(screen.queryByText(/Asks you|Authorizing/)).not.toBeInTheDocument();
- fireEvent.click(
- await screen.findByRole("button", { name: "Allow Project Writer" }),
- );
+ fireEvent.click(await enabledButton("Allow Project Writer"));
await waitFor(() =>
expect(decision).toHaveBeenCalledWith(
expect.objectContaining({
@@ -191,9 +197,7 @@ describe("Chat connection authorization", () => {
status: "pending",
connect_url: "https://connect.example.test/notion",
});
- fireEvent.click(
- await screen.findByRole("button", { name: "Connect Notion" }),
- );
+ fireEvent.click(await enabledButton("Connect Notion"));
await waitFor(() =>
expect(decision).toHaveBeenCalledWith(
expect.objectContaining({
@@ -230,9 +234,7 @@ describe("Chat connection authorization", () => {
id: "notion-2",
connect_url: "https://connect.example.test/notion",
});
- fireEvent.click(
- await screen.findByRole("button", { name: "Connect Notion" }),
- );
+ fireEvent.click(await enabledButton("Connect Notion"));
await waitFor(() =>
expect(decision).toHaveBeenCalledWith(
expect.objectContaining({
@@ -267,9 +269,7 @@ describe("Chat connection authorization", () => {
connect_expires_at: "2999-01-01T00:00:00Z",
});
const create = vi.spyOn(runtime.client, "createExternalConnection");
- fireEvent.click(
- await screen.findByRole("button", { name: "Connect Notion" }),
- );
+ fireEvent.click(await enabledButton("Connect Notion"));
await waitFor(() =>
expect(window.open).toHaveBeenCalledWith(
"https://connect.example.test/resume",
@@ -338,9 +338,7 @@ describe("Chat connection authorization", () => {
fireEvent.click(
screen.getByRole("option", { name: "Connect a new account" }),
);
- fireEvent.click(
- await screen.findByRole("button", { name: "Connect Notion" }),
- );
+ fireEvent.click(await enabledButton("Connect Notion"));
await waitFor(() =>
expect(decision).toHaveBeenCalledWith(
expect.objectContaining({ connectionId: "notion-new" }),
@@ -388,9 +386,7 @@ describe("Chat connection authorization", () => {
expect(
screen.queryByRole("combobox", { name: "Notion account" }),
).not.toBeInTheDocument();
- fireEvent.click(
- await screen.findByRole("button", { name: "Connect Notion" }),
- );
+ fireEvent.click(await enabledButton("Connect Notion"));
await waitFor(() =>
expect(window.open).toHaveBeenCalledWith(
"https://connect.example.test/open",
@@ -426,9 +422,7 @@ describe("Chat connection authorization", () => {
status: "pending",
connect_url: "https://connect.example.test/new",
});
- fireEvent.click(
- await screen.findByRole("button", { name: "Connect Notion" }),
- );
+ fireEvent.click(await enabledButton("Connect Notion"));
await waitFor(() =>
expect(decision).toHaveBeenCalledWith(
expect.objectContaining({ connectionId: "notion-new" }),
@@ -525,9 +519,7 @@ describe("Chat connection authorization", () => {
accept = resolve;
}),
);
- fireEvent.click(
- await screen.findByRole("button", { name: "Connect Notion" }),
- );
+ fireEvent.click(await enabledButton("Connect Notion"));
await waitFor(() => expect(decision).toHaveBeenCalledOnce());
expect(window.open).not.toHaveBeenCalled();
accept();
diff --git a/apps/web/src/features/rooms/chat/direct-agent-model-switch.test.tsx b/apps/web/src/features/rooms/chat/direct-agent-model-switch.test.tsx
index c979f3e1..d84f7e95 100644
--- a/apps/web/src/features/rooms/chat/direct-agent-model-switch.test.tsx
+++ b/apps/web/src/features/rooms/chat/direct-agent-model-switch.test.tsx
@@ -99,7 +99,10 @@ describe("Direct Agent runtime settings", () => {
fireEvent.click(
await screen.findByRole("button", { name: "5.4 Sol Medium" }),
);
- expect(screen.getByRole("button", { name: "Save Runtime" })).toBeDisabled();
+ // The settings dialog is a lazy chunk on its first open.
+ expect(
+ await screen.findByRole("button", { name: "Save Runtime" }),
+ ).toBeDisabled();
fireEvent.click(screen.getByRole("button", { name: "Cancel" }));
expect(updateTenantAgent).not.toHaveBeenCalled();
});
diff --git a/apps/web/src/features/rooms/chat/message-reactions/message-reactions.test.tsx b/apps/web/src/features/rooms/chat/message-reactions/message-reactions.test.tsx
index 42f00b82..12d92875 100644
--- a/apps/web/src/features/rooms/chat/message-reactions/message-reactions.test.tsx
+++ b/apps/web/src/features/rooms/chat/message-reactions/message-reactions.test.tsx
@@ -15,6 +15,7 @@ import {
import type { ComponentProps, ReactNode } from "react";
import { MemoryRouter } from "react-router";
import { describe, expect, it, vi } from "vitest";
+import { defineGlobalProperty } from "@/test/global-properties";
import {
roomMessageQueryKey,
@@ -505,7 +506,7 @@ describe("Agent cheer on Reactions", () => {
cancel: vi.fn(),
finished: new Promise(() => undefined),
}));
- Object.defineProperty(HTMLElement.prototype, "animate", {
+ defineGlobalProperty(HTMLElement.prototype, "animate", {
configurable: true,
value: animate,
});
@@ -519,9 +520,6 @@ describe("Agent cheer on Reactions", () => {
await react("Thumbs Up");
expect(floating()).toEqual(["✨", "✨", "✨", "✨", "✨"]);
- // @ts-expect-error -- remove the stub so other tests see jsdom's Element.
- delete HTMLElement.prototype.animate;
- vi.unstubAllGlobals();
});
it("stays still for other Reactions, removals, and people's Messages", async () => {
diff --git a/apps/web/src/features/rooms/chat/use-room-timeline-scroll.ts b/apps/web/src/features/rooms/chat/use-room-timeline-scroll.ts
index 1bbdb6bc..c9a90e94 100644
--- a/apps/web/src/features/rooms/chat/use-room-timeline-scroll.ts
+++ b/apps/web/src/features/rooms/chat/use-room-timeline-scroll.ts
@@ -12,6 +12,10 @@ const readingPositions = new Map<
}
>();
+export function resetRoomTimelineReadingPositionsForTest() {
+ readingPositions.clear();
+}
+
/** Content changes this soon after the reader's own input are theirs to keep. */
const INPUT_SETTLE_MS = 1_000;
diff --git a/apps/web/src/features/rooms/chat/voice-mode/file-voice-material-button.test.tsx b/apps/web/src/features/rooms/chat/voice-mode/file-voice-material-button.test.tsx
index 95eb88b4..1ba496a1 100644
--- a/apps/web/src/features/rooms/chat/voice-mode/file-voice-material-button.test.tsx
+++ b/apps/web/src/features/rooms/chat/voice-mode/file-voice-material-button.test.tsx
@@ -1,6 +1,7 @@
import { fireEvent, render, screen } from "@testing-library/react";
import { useEffect } from "react";
import { beforeEach, describe, expect, it } from "vitest";
+import { defineGlobalProperty } from "@/test/global-properties";
import { isVoiceDocumentSelection } from "../../room-drafts";
import { FileVoiceMaterialButton } from "./file-voice-material-button";
@@ -41,7 +42,7 @@ function renderButton(entered: boolean) {
describe("FileVoiceMaterialButton", () => {
// Voice materials persist in the Room draft; start every case empty.
beforeEach(() => {
- Object.defineProperty(window, "localStorage", {
+ defineGlobalProperty(window, "localStorage", {
configurable: true,
value: createTestStorage(),
});
diff --git a/apps/web/src/features/rooms/chat/voice-mode/voice-materials-context.test.tsx b/apps/web/src/features/rooms/chat/voice-mode/voice-materials-context.test.tsx
index efe5b45b..4858d3bc 100644
--- a/apps/web/src/features/rooms/chat/voice-mode/voice-materials-context.test.tsx
+++ b/apps/web/src/features/rooms/chat/voice-mode/voice-materials-context.test.tsx
@@ -1,5 +1,6 @@
import { act, render } from "@testing-library/react";
import { beforeEach, describe, expect, it } from "vitest";
+import { defineGlobalProperty } from "@/test/global-properties";
import { readRoomComposerDraft } from "../../room-drafts";
import {
@@ -15,7 +16,7 @@ const voiceRoom = {
};
beforeEach(() => {
- Object.defineProperty(window, "localStorage", {
+ defineGlobalProperty(window, "localStorage", {
configurable: true,
value: createTestStorage(),
});
diff --git a/apps/web/src/features/rooms/chat/voice-mode/voice-mode-room-sender.test.ts b/apps/web/src/features/rooms/chat/voice-mode/voice-mode-room-sender.test.ts
index 8ff5abe4..4ebfcc40 100644
--- a/apps/web/src/features/rooms/chat/voice-mode/voice-mode-room-sender.test.ts
+++ b/apps/web/src/features/rooms/chat/voice-mode/voice-mode-room-sender.test.ts
@@ -1,6 +1,7 @@
// @vitest-environment jsdom
import { QueryClient } from "@tanstack/react-query";
import { beforeEach, describe, expect, it, vi } from "vitest";
+import { defineGlobalProperty } from "@/test/global-properties";
import { roomMessageSender } from "../room-message-sender";
import {
@@ -46,7 +47,7 @@ const scope = {
const prefix = { body: "", documentReferences: [], mentions: [] };
beforeEach(() => {
- Object.defineProperty(window, "localStorage", {
+ defineGlobalProperty(window, "localStorage", {
configurable: true,
value: createTestStorage(),
});
diff --git a/apps/web/src/features/rooms/chat/voice-mode/voice-pip.test.ts b/apps/web/src/features/rooms/chat/voice-mode/voice-pip.test.ts
index 95fd772a..2ceee02c 100644
--- a/apps/web/src/features/rooms/chat/voice-mode/voice-pip.test.ts
+++ b/apps/web/src/features/rooms/chat/voice-mode/voice-pip.test.ts
@@ -1,5 +1,6 @@
// @vitest-environment jsdom
import { afterEach, describe, expect, it, vi } from "vitest";
+import { defineGlobalProperty } from "@/test/global-properties";
import {
closeVoicePip,
@@ -25,7 +26,7 @@ function installFakeVoicePip() {
close: vi.fn(() => listeners.splice(0).forEach((listener) => listener())),
};
const requestWindow = vi.fn(async () => pipWindow as unknown as Window);
- Object.defineProperty(window, "documentPictureInPicture", {
+ defineGlobalProperty(window, "documentPictureInPicture", {
configurable: true,
value: { requestWindow },
});
diff --git a/apps/web/src/features/rooms/chat/voice-mode/voice-ui-bridge.test.ts b/apps/web/src/features/rooms/chat/voice-mode/voice-ui-bridge.test.ts
index b305a471..79a12e61 100644
--- a/apps/web/src/features/rooms/chat/voice-mode/voice-ui-bridge.test.ts
+++ b/apps/web/src/features/rooms/chat/voice-mode/voice-ui-bridge.test.ts
@@ -1,5 +1,6 @@
// @vitest-environment jsdom
import { afterEach, describe, expect, it, vi } from "vitest";
+import { defineGlobalProperty } from "@/test/global-properties";
import {
collectVoiceElements,
@@ -582,42 +583,21 @@ describe("Voice Mode screen actions", () => {
it("scrolls the page itself when the middle of the screen is not in a scrolling area", () => {
const sidebar = pane("sidebar");
+ // The document element outlives the test, so every patch on it is
+ // restored after the test.
const page = document.documentElement;
- Object.defineProperty(document, "scrollingElement", {
- configurable: true,
- value: page,
- });
- Object.defineProperty(page, "scrollHeight", {
- configurable: true,
- value: 3000,
- });
- Object.defineProperty(page, "clientHeight", {
- configurable: true,
- value: 800,
- });
- page.scrollBy = vi.fn();
+ defineGlobalProperty(document, "scrollingElement", { value: page });
+ defineGlobalProperty(page, "scrollHeight", { value: 3000 });
+ defineGlobalProperty(page, "clientHeight", { value: 800 });
+ const scrollBy = vi.fn();
+ defineGlobalProperty(page, "scrollBy", { value: scrollBy });
const content = document.createElement("main");
document.body.append(content);
- document.elementsFromPoint = () => [content, document.body];
- try {
- expect(voiceScroll("down")).toBe(true);
- expect(page.scrollBy).toHaveBeenCalled();
- expect(sidebar.scrollBy).not.toHaveBeenCalled();
- } finally {
- // @ts-expect-error jsdom has no elementsFromPoint
- delete document.elementsFromPoint;
- Object.defineProperty(document, "scrollingElement", {
- configurable: true,
- value: null,
- });
- Object.defineProperty(page, "scrollHeight", {
- configurable: true,
- value: 0,
- });
- Object.defineProperty(page, "clientHeight", {
- configurable: true,
- value: 0,
- });
- }
+ defineGlobalProperty(document, "elementsFromPoint", {
+ value: () => [content, document.body],
+ });
+ expect(voiceScroll("down")).toBe(true);
+ expect(scrollBy).toHaveBeenCalled();
+ expect(sidebar.scrollBy).not.toHaveBeenCalled();
});
});
diff --git a/apps/web/src/features/rooms/documents/document-voice-selection-control.test.tsx b/apps/web/src/features/rooms/documents/document-voice-selection-control.test.tsx
index 23896d3b..a93d3842 100644
--- a/apps/web/src/features/rooms/documents/document-voice-selection-control.test.tsx
+++ b/apps/web/src/features/rooms/documents/document-voice-selection-control.test.tsx
@@ -299,8 +299,22 @@ describe("Document voice material selection", () => {
});
it("keeps the subscription across presentation rerenders and cleans up on identity change and unmount", () => {
+ // React adds its own document selectionchange listener the first time it
+ // renders, so count only the listeners the control also binds to its root.
+ const rootListen = vi.spyOn(HTMLElement.prototype, "addEventListener");
const subscribe = vi.spyOn(document, "addEventListener");
const unsubscribe = vi.spyOn(document, "removeEventListener");
+ const controlCalls = (spy: typeof subscribe) => {
+ const controlListeners = new Set(
+ rootListen.mock.calls
+ .filter(([name]) => name === "mouseup")
+ .map(([, listener]) => listener),
+ );
+ return spy.mock.calls.filter(
+ ([name, listener]) =>
+ name === "selectionchange" && controlListeners.has(listener),
+ );
+ };
const { rootRef, rerender, unmount, content } = createSurface();
const tree = (documentId: string, title: string) => (
<section ref={rootRef}>
@@ -313,21 +327,13 @@ describe("Document voice material selection", () => {
</section>
);
rerender(tree("document-one", "Renamed title"));
- expect(
- subscribe.mock.calls.filter(([name]) => name === "selectionchange"),
- ).toHaveLength(1);
+ expect(controlCalls(subscribe)).toHaveLength(1);
select(screen.getByText("Review this sentence"));
rerender(tree("document-two", "New document"));
expect(screen.queryByRole("button", { name: actionName })).toBeNull();
- expect(
- subscribe.mock.calls.filter(([name]) => name === "selectionchange"),
- ).toHaveLength(2);
- expect(
- unsubscribe.mock.calls.filter(([name]) => name === "selectionchange"),
- ).toHaveLength(1);
+ expect(controlCalls(subscribe)).toHaveLength(2);
+ expect(controlCalls(unsubscribe)).toHaveLength(1);
unmount();
- expect(
- unsubscribe.mock.calls.filter(([name]) => name === "selectionchange"),
- ).toHaveLength(2);
+ expect(controlCalls(unsubscribe)).toHaveLength(2);
});
});
diff --git a/apps/web/src/features/rooms/documents/room-document-surface.test.tsx b/apps/web/src/features/rooms/documents/room-document-surface.test.tsx
index cf9e6cc4..3316ec92 100644
--- a/apps/web/src/features/rooms/documents/room-document-surface.test.tsx
+++ b/apps/web/src/features/rooms/documents/room-document-surface.test.tsx
@@ -1489,7 +1489,10 @@ describe("Unified Document page", () => {
screen.queryByRole("button", { name: "Duplicate Document" }),
).not.toBeInTheDocument();
await chooseDocumentAction("Page history");
- expect(screen.getByRole("heading", { name: "Page history" })).toBeVisible();
+ // The history dialog is a lazy chunk on its first open.
+ expect(
+ await screen.findByRole("heading", { name: "Page history" }),
+ ).toBeVisible();
expect(await screen.findByText("No page history saved yet.")).toBeVisible();
expect(screen.queryByRole("tab")).not.toBeInTheDocument();
});
diff --git a/apps/web/src/features/rooms/members/agent-avatar.test.ts b/apps/web/src/features/rooms/members/agent-avatar.test.ts
index 63eefb16..f5bab945 100644
--- a/apps/web/src/features/rooms/members/agent-avatar.test.ts
+++ b/apps/web/src/features/rooms/members/agent-avatar.test.ts
@@ -1,6 +1,7 @@
// @vitest-environment jsdom
import { beforeEach, describe, expect, it } from "vitest";
+import { defineGlobalProperty } from "@/test/global-properties";
import {
AGENT_AVATAR_KEYS,
@@ -15,7 +16,7 @@ import {
describe("Agent avatar persistence", () => {
beforeEach(() => {
- Object.defineProperty(window, "localStorage", {
+ defineGlobalProperty(window, "localStorage", {
configurable: true,
value: createTestStorage(),
});
diff --git a/apps/web/src/features/rooms/pocket-notes/pocket-note-editor.test.tsx b/apps/web/src/features/rooms/pocket-notes/pocket-note-editor.test.tsx
index e3c41227..dd3cde27 100644
--- a/apps/web/src/features/rooms/pocket-notes/pocket-note-editor.test.tsx
+++ b/apps/web/src/features/rooms/pocket-notes/pocket-note-editor.test.tsx
@@ -1,6 +1,7 @@
import { act, fireEvent, render, screen } from "@testing-library/react";
import { createRef } from "react";
import { beforeEach, describe, expect, it, vi } from "vitest";
+import { defineGlobalProperty } from "@/test/global-properties";
import {
PocketNoteEditor,
@@ -10,9 +11,11 @@ import {
describe("PocketNoteEditor", () => {
beforeEach(() => {
// JSDOM has no text-range layout; browser coverage exercises caret scrolling.
- Object.defineProperties(Range.prototype, {
- getClientRects: { configurable: true, value: () => [] },
- getBoundingClientRect: { configurable: true, value: () => new DOMRect() },
+ defineGlobalProperty(Range.prototype, "getClientRects", {
+ value: () => [],
+ });
+ defineGlobalProperty(Range.prototype, "getBoundingClientRect", {
+ value: () => new DOMRect(),
});
});
it("renders headings and maps dictation offsets to the saved Markdown", () => {
diff --git a/apps/web/src/features/rooms/room-create-dialog.test.tsx b/apps/web/src/features/rooms/room-create-dialog.test.tsx
index 7cac580d..838a98e7 100644
--- a/apps/web/src/features/rooms/room-create-dialog.test.tsx
+++ b/apps/web/src/features/rooms/room-create-dialog.test.tsx
@@ -13,6 +13,7 @@ import {
import { RoomAddMembersDialog } from "./members/room-add-members-dialog";
import { MemoryRouter } from "react-router";
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
+import { defineGlobalProperty } from "@/test/global-properties";
import { createAppQueryClient } from "@/app/query-client";
import {
@@ -33,7 +34,7 @@ import { RoomCreateDialog } from "./room-create-dialog";
describe("Room creation", () => {
beforeEach(() => {
- Object.defineProperty(HTMLElement.prototype, "showPopover", {
+ defineGlobalProperty(HTMLElement.prototype, "showPopover", {
configurable: true,
value: function (this: HTMLElement) {
this.style.display = "flex";
@@ -50,7 +51,6 @@ describe("Room creation", () => {
afterEach(() => {
onlineManager.setOnline(true);
vi.unstubAllGlobals();
- Reflect.deleteProperty(HTMLElement.prototype, "showPopover");
});
it("uses the authored compact form without a secondary cancel action", async () => {
diff --git a/apps/web/src/features/rooms/room-drafts.test.ts b/apps/web/src/features/rooms/room-drafts.test.ts
index 884a4240..cb5b3776 100644
--- a/apps/web/src/features/rooms/room-drafts.test.ts
+++ b/apps/web/src/features/rooms/room-drafts.test.ts
@@ -1,5 +1,6 @@
// @vitest-environment jsdom
import { beforeEach, describe, expect, it, vi } from "vitest";
+import { defineGlobalProperty } from "@/test/global-properties";
import {
clearRoomDrafts,
@@ -16,7 +17,7 @@ const firstRoom = {
describe("Room drafts", () => {
beforeEach(() => {
- Object.defineProperty(window, "localStorage", {
+ defineGlobalProperty(window, "localStorage", {
configurable: true,
value: createTestStorage(),
});
diff --git a/apps/web/src/features/rooms/room-navigation.test.tsx b/apps/web/src/features/rooms/room-navigation.test.tsx
index e560575b..0b9bff7d 100644
--- a/apps/web/src/features/rooms/room-navigation.test.tsx
+++ b/apps/web/src/features/rooms/room-navigation.test.tsx
@@ -1,5 +1,6 @@
import { QueryClient, QueryClientProvider } from "@tanstack/react-query";
import {
+ cleanup,
fireEvent,
render,
screen,
@@ -7,7 +8,7 @@ import {
within,
} from "@testing-library/react";
import { MemoryRouter, Route, Routes, useLocation } from "react-router";
-import { describe, expect, it, vi } from "vitest";
+import { beforeAll, describe, expect, it, vi } from "vitest";
import { createTestTeamHubRuntime } from "@/test/teamhub-test-runtime";
import { TeamHubRuntimeProvider } from "@/features/teamhub/teamhub-runtime";
@@ -16,6 +17,14 @@ import { RoomNavigation } from "./room-navigation";
import { teamHubData } from "@/features/teamhub/teamhub-api";
describe("Room navigation", () => {
+ // The Room list is a lazy chunk and most tests query it synchronously, so
+ // load it once before any test regardless of the order they run in.
+ beforeAll(async () => {
+ renderNavigation(await navigationFixture(), new QueryClient());
+ await screen.findByRole("navigation", { name: "Room navigation" });
+ cleanup();
+ });
+
it("opens the Room list at the threads sidebar width and preserves resize preferences", async () => {
const fixture = await navigationFixture();
const key = `linger:room-list-width:${fixture.tenant.id}`;
diff --git a/apps/web/src/features/rooms/room-shell.test.tsx b/apps/web/src/features/rooms/room-shell.test.tsx
index 0a9054a2..48a46d5e 100644
--- a/apps/web/src/features/rooms/room-shell.test.tsx
+++ b/apps/web/src/features/rooms/room-shell.test.tsx
@@ -623,7 +623,8 @@ describe("Room shell Tenant transition", () => {
);
expect(await screen.findByText("Current Room content")).toBeVisible();
- fireEvent.click(screen.getByRole("link", { name: "gtm-launch" }));
+ // The Room list is a lazy chunk that can settle after the Room content.
+ fireEvent.click(await screen.findByRole("link", { name: "gtm-launch" }));
await waitFor(() =>
expect(router.state.location.pathname).toBe(
"/t/tenant-northstar/rooms/room-gtm-launch/chat",
diff --git a/apps/web/src/features/rooms/sharing/room-history-share-dialog.test.tsx b/apps/web/src/features/rooms/sharing/room-history-share-dialog.test.tsx
index e5a6b69b..f05b1571 100644
--- a/apps/web/src/features/rooms/sharing/room-history-share-dialog.test.tsx
+++ b/apps/web/src/features/rooms/sharing/room-history-share-dialog.test.tsx
@@ -1,6 +1,7 @@
import { QueryClient, QueryClientProvider } from "@tanstack/react-query";
import { fireEvent, render, screen, waitFor } from "@testing-library/react";
import { beforeEach, describe, expect, it, vi } from "vitest";
+import { defineGlobalProperty } from "@/test/global-properties";
import type { TeamHubClient } from "@/features/teamhub/teamhub-client";
import { TeamHubRuntimeProvider } from "@/features/teamhub/teamhub-runtime";
@@ -38,8 +39,8 @@ function renderDialog(roomHistory: Partial<TeamHubClient["roomHistory"]>) {
describe("Room history share dialog", () => {
beforeEach(() => {
vi.stubGlobal("open", vi.fn().mockReturnValue(null));
- Object.assign(navigator, {
- clipboard: { writeText: vi.fn().mockResolvedValue(undefined) },
+ defineGlobalProperty(navigator, "clipboard", {
+ value: { writeText: vi.fn().mockResolvedValue(undefined) },
});
});
diff --git a/apps/web/src/features/rooms/task-sidebar/panel-tab-store.test.ts b/apps/web/src/features/rooms/task-sidebar/panel-tab-store.test.ts
index 2a2533a7..e59645b8 100644
--- a/apps/web/src/features/rooms/task-sidebar/panel-tab-store.test.ts
+++ b/apps/web/src/features/rooms/task-sidebar/panel-tab-store.test.ts
@@ -1,4 +1,5 @@
import { beforeEach, describe, expect, it } from "vitest";
+import { defineGlobalProperty } from "@/test/global-properties";
import {
closePanelTab,
@@ -19,7 +20,7 @@ const scope = {
describe("panel tab store", () => {
beforeEach(() => {
const store = new Map<string, string>();
- Object.defineProperty(globalThis, "localStorage", {
+ defineGlobalProperty(globalThis, "localStorage", {
configurable: true,
value: {
get length() {
diff --git a/apps/web/src/features/rooms/task-sidebar/panel-width.test.ts b/apps/web/src/features/rooms/task-sidebar/panel-width.test.ts
index 3f724856..bd1feed1 100644
--- a/apps/web/src/features/rooms/task-sidebar/panel-width.test.ts
+++ b/apps/web/src/features/rooms/task-sidebar/panel-width.test.ts
@@ -1,5 +1,6 @@
// @vitest-environment jsdom
import { beforeEach, describe, expect, it } from "vitest";
+import { defineGlobalProperty } from "@/test/global-properties";
import {
clampPanelSidebarWidth,
@@ -13,7 +14,7 @@ import {
describe("panel sidebar width", () => {
beforeEach(() => {
const store = new Map<string, string>();
- Object.defineProperty(globalThis, "localStorage", {
+ defineGlobalProperty(globalThis, "localStorage", {
configurable: true,
value: {
get length() {
diff --git a/apps/web/src/features/rooms/task-sidebar/task-sidebar.test.tsx b/apps/web/src/features/rooms/task-sidebar/task-sidebar.test.tsx
index 808edc89..e45f5a9b 100644
--- a/apps/web/src/features/rooms/task-sidebar/task-sidebar.test.tsx
+++ b/apps/web/src/features/rooms/task-sidebar/task-sidebar.test.tsx
@@ -10,6 +10,7 @@ import {
import type { ReactElement } from "react";
import { MemoryRouter } from "react-router";
import { beforeEach, describe, expect, it, vi } from "vitest";
+import { defineGlobalProperty } from "@/test/global-properties";
import {
createDocumentTestRuntime,
@@ -91,7 +92,7 @@ describe("TaskSidebar", () => {
beforeEach(() => {
const store = new Map<string, string>();
- Object.defineProperty(globalThis, "localStorage", {
+ defineGlobalProperty(globalThis, "localStorage", {
configurable: true,
value: {
get length() {
diff --git a/apps/web/src/features/rooms/voice-control/recording-window.test.tsx b/apps/web/src/features/rooms/voice-control/recording-window.test.tsx
index a334c6e9..2384130f 100644
--- a/apps/web/src/features/rooms/voice-control/recording-window.test.tsx
+++ b/apps/web/src/features/rooms/voice-control/recording-window.test.tsx
@@ -10,6 +10,7 @@ import {
} from "@testing-library/react";
import { MemoryRouter, Route, Routes } from "react-router";
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
+import { defineGlobalProperty } from "@/test/global-properties";
import { createTestTeamHubRuntime } from "@/test/teamhub-test-runtime";
import { TeamHubRuntimeProvider } from "@/features/teamhub/teamhub-runtime";
@@ -912,7 +913,7 @@ function stubPictureInPicture() {
}),
};
const requestWindow = vi.fn(async () => pipWindow);
- Object.defineProperty(window, "documentPictureInPicture", {
+ defineGlobalProperty(window, "documentPictureInPicture", {
configurable: true,
value: { requestWindow },
});
diff --git a/apps/web/src/features/rooms/voice-control/voice-focus-surface.test.tsx b/apps/web/src/features/rooms/voice-control/voice-focus-surface.test.tsx
index 61922ec6..5e0eb6c5 100644
--- a/apps/web/src/features/rooms/voice-control/voice-focus-surface.test.tsx
+++ b/apps/web/src/features/rooms/voice-control/voice-focus-surface.test.tsx
@@ -1,6 +1,7 @@
import { act, fireEvent, render, screen, within } from "@testing-library/react";
import { StrictMode } from "react";
import { afterEach, describe, expect, it, vi } from "vitest";
+import { defineGlobalProperty } from "@/test/global-properties";
import {
VoiceControlContext,
@@ -721,7 +722,7 @@ describe("VoiceFocusSurface", () => {
});
function stubMicrophonePermission(result: Promise<PermissionStatus>) {
- Object.defineProperty(navigator, "permissions", {
+ defineGlobalProperty(navigator, "permissions", {
configurable: true,
value: { query: vi.fn(() => result) },
});
diff --git a/apps/web/src/features/search/global-search-dialog.test.tsx b/apps/web/src/features/search/global-search-dialog.test.tsx
index c78b4c65..b56d3e5a 100644
--- a/apps/web/src/features/search/global-search-dialog.test.tsx
+++ b/apps/web/src/features/search/global-search-dialog.test.tsx
@@ -9,6 +9,7 @@ import {
} from "@testing-library/react";
import { createMemoryRouter, RouterProvider, useLocation } from "react-router";
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
+import { defineGlobalProperty } from "@/test/global-properties";
import { createAppQueryClient } from "@/app/query-client";
import {
@@ -48,7 +49,7 @@ const results = () => within(screen.getByRole("listbox"));
describe("Global search dialog", () => {
beforeEach(() => {
- Object.defineProperty(window, "localStorage", {
+ defineGlobalProperty(window, "localStorage", {
configurable: true,
value: createTestStorage(),
});
diff --git a/apps/web/src/features/settings/settings-pages.test.tsx b/apps/web/src/features/settings/settings-pages.test.tsx
index 8c170814..984a786e 100644
--- a/apps/web/src/features/settings/settings-pages.test.tsx
+++ b/apps/web/src/features/settings/settings-pages.test.tsx
@@ -9,6 +9,7 @@ import {
} from "@testing-library/react";
import { createMemoryRouter, RouterProvider, useLocation } from "react-router";
import { beforeAll, beforeEach, describe, expect, it, vi } from "vitest";
+import { defineGlobalProperty } from "@/test/global-properties";
import {
createTestTeamHubRuntime,
@@ -35,7 +36,7 @@ beforeAll(async () => {
beforeEach(() => {
const values = new Map<string, string>();
- Object.defineProperty(window, "localStorage", {
+ defineGlobalProperty(window, "localStorage", {
configurable: true,
value: {
clear: () => values.clear(),
diff --git a/apps/web/src/features/wiki/wiki-page.test.tsx b/apps/web/src/features/wiki/wiki-page.test.tsx
index 321aba79..6fe043a2 100644
--- a/apps/web/src/features/wiki/wiki-page.test.tsx
+++ b/apps/web/src/features/wiki/wiki-page.test.tsx
@@ -1,5 +1,6 @@
import { fireEvent, screen, waitFor, within } from "@testing-library/react";
-import { afterEach, describe, expect, it, vi } from "vitest";
+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
+import { defineGlobalProperty } from "@/test/global-properties";
import {
deferred,
@@ -17,9 +18,8 @@ afterEach(() => {
});
// jsdom supplies no scroll geometry for the Daily card track.
-Object.defineProperty(HTMLElement.prototype, "scrollTo", {
- configurable: true,
- value: vi.fn(),
+beforeEach(() => {
+ defineGlobalProperty(HTMLElement.prototype, "scrollTo", { value: vi.fn() });
});
describe("Wiki source commands and shared file tree", () => {
diff --git a/apps/web/src/features/wiki/wiki-profile-sources.test.tsx b/apps/web/src/features/wiki/wiki-profile-sources.test.tsx
index f49a2d18..347d74c5 100644
--- a/apps/web/src/features/wiki/wiki-profile-sources.test.tsx
+++ b/apps/web/src/features/wiki/wiki-profile-sources.test.tsx
@@ -9,6 +9,7 @@ import {
} from "@testing-library/react";
import { createMemoryRouter, RouterProvider } from "react-router";
import { beforeEach, describe, expect, it, vi } from "vitest";
+import { defineGlobalProperty } from "@/test/global-properties";
import { createTestTeamHubRuntime } from "@/test/teamhub-test-runtime";
import type { TeamHubPersonalProfileGeneration } from "@/features/teamhub/teamhub-types";
@@ -29,7 +30,7 @@ const generation: TeamHubPersonalProfileGeneration = {
beforeEach(() => {
const values = new Map<string, string>();
- Object.defineProperty(window, "localStorage", {
+ defineGlobalProperty(window, "localStorage", {
configurable: true,
value: {
clear: () => values.clear(),
@@ -722,7 +723,7 @@ describe("Wiki Profile sources", () => {
.spyOn(runtime.client, "createPersonalProfileGeneration")
.mockResolvedValue(generation);
const writeText = vi.fn().mockResolvedValue(undefined);
- Object.defineProperty(window.navigator, "clipboard", {
+ defineGlobalProperty(window.navigator, "clipboard", {
configurable: true,
value: { writeText },
});
diff --git a/apps/web/src/features/wiki/wiki-resilience.test.tsx b/apps/web/src/features/wiki/wiki-resilience.test.tsx
index 16781126..a77b0773 100644
--- a/apps/web/src/features/wiki/wiki-resilience.test.tsx
+++ b/apps/web/src/features/wiki/wiki-resilience.test.tsx
@@ -1,5 +1,6 @@
import { act, fireEvent, screen, waitFor } from "@testing-library/react";
-import { afterEach, describe, expect, it, vi } from "vitest";
+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
+import { defineGlobalProperty } from "@/test/global-properties";
import {
deferred,
@@ -24,9 +25,8 @@ function moveDocumentToTenant(
}
// The seeded graph renders the Timeline cards; jsdom has no scroll geometry.
-Object.defineProperty(HTMLElement.prototype, "scrollTo", {
- configurable: true,
- value: vi.fn(),
+beforeEach(() => {
+ defineGlobalProperty(HTMLElement.prototype, "scrollTo", { value: vi.fn() });
});
afterEach(() => {
diff --git a/apps/web/src/lib/clipboard.test.ts b/apps/web/src/lib/clipboard.test.ts
index 3e030430..ae0e62ab 100644
--- a/apps/web/src/lib/clipboard.test.ts
+++ b/apps/web/src/lib/clipboard.test.ts
@@ -1,25 +1,13 @@
// @vitest-environment jsdom
import { afterEach, describe, expect, it, vi } from "vitest";
+import { defineGlobalProperty } from "@/test/global-properties";
import { writeClipboardText } from "./clipboard";
-const originalClipboard = Object.getOwnPropertyDescriptor(
- Navigator.prototype,
- "clipboard",
-);
const originalExecCommand = document.execCommand;
describe("clipboard fallback", () => {
afterEach(() => {
- if (originalClipboard) {
- Object.defineProperty(
- Navigator.prototype,
- "clipboard",
- originalClipboard,
- );
- } else {
- Reflect.deleteProperty(Navigator.prototype, "clipboard");
- }
document.execCommand = originalExecCommand;
document.body.replaceChildren();
vi.restoreAllMocks();
@@ -27,7 +15,7 @@ describe("clipboard fallback", () => {
it("uses the browser copy command when Clipboard API access is rejected", async () => {
const writeText = vi.fn().mockRejectedValue(new Error("Permission denied"));
- Object.defineProperty(Navigator.prototype, "clipboard", {
+ defineGlobalProperty(Navigator.prototype, "clipboard", {
configurable: true,
value: { writeText },
});
@@ -41,7 +29,7 @@ describe("clipboard fallback", () => {
});
it("keeps the fallback control inside the active modal dialog", async () => {
- Object.defineProperty(Navigator.prototype, "clipboard", {
+ defineGlobalProperty(Navigator.prototype, "clipboard", {
configurable: true,
value: undefined,
});
@@ -73,7 +61,7 @@ describe("clipboard fallback", () => {
])(
"restores focus and selection when execCommand %s",
async (_label, execCommand) => {
- Object.defineProperty(Navigator.prototype, "clipboard", {
+ defineGlobalProperty(Navigator.prototype, "clipboard", {
configurable: true,
value: undefined,
});
diff --git a/apps/web/src/test/global-properties.ts b/apps/web/src/test/global-properties.ts
new file mode 100644
index 00000000..5e1b24bd
--- /dev/null
+++ b/apps/web/src/test/global-properties.ts
@@ -0,0 +1,24 @@
+// Test files without module mocks share one window per worker, so a property
+// a test defines on a global or a prototype would reach every later file. This
+// records the original descriptor so src/test/setup.ts restores it after the
+// test, the way vi.stubGlobal does for globalThis keys.
+const restores: (() => void)[] = [];
+
+export function defineGlobalProperty(
+ target: object,
+ key: PropertyKey,
+ descriptor: PropertyDescriptor,
+): void {
+ const original = Object.getOwnPropertyDescriptor(target, key);
+ restores.push(() => {
+ if (original) Object.defineProperty(target, key, original);
+ else Reflect.deleteProperty(target, key);
+ });
+ Object.defineProperty(target, key, { configurable: true, ...descriptor });
+}
+
+export function restoreGlobalProperties(): void {
+ for (let restore = restores.pop(); restore; restore = restores.pop()) {
+ restore();
+ }
+}
diff --git a/apps/web/src/test/setup.ts b/apps/web/src/test/setup.ts
index 87880a12..7f9224e4 100644
--- a/apps/web/src/test/setup.ts
+++ b/apps/web/src/test/setup.ts
@@ -1,7 +1,9 @@
+import { focusManager, onlineManager } from "@tanstack/react-query";
import { afterEach, vi } from "vitest";
import { resetComposerAttachmentDraftsForTest } from "@/features/rooms/chat/composer-attachment-drafts";
import { setRoomDiagnosticsEnabledForTest } from "@/lib/room-diagnostics";
+import { restoreGlobalProperties } from "@/test/global-properties";
import { assertNoUnhandledTestRoutes } from "@/test/teamhub-test-server";
// Tests assert the Room timing diagnostics, which are off by default in browsers.
@@ -9,6 +11,7 @@ setRoomDiagnosticsEnabledForTest(true);
// Pure logic tests opt into Node and do not need the React/DOM harness.
let cleanupRenderedComponents: (() => void) | undefined;
+let resetRoomTimelineReadingPositions: (() => void) | undefined;
if (typeof document !== "undefined") {
await import("@testing-library/jest-dom/vitest");
// motion-utils owns the global config motion/react reads; loading all of
@@ -21,6 +24,11 @@ if (typeof document !== "undefined") {
configure({ asyncUtilTimeout: 5_000 });
MotionGlobalConfig.skipAnimations = true;
cleanupRenderedComponents = cleanup;
+ // Reading positions are kept per Room in a module map; a test must not open
+ // a Room scrolled where an earlier test left it.
+ ({
+ resetRoomTimelineReadingPositionsForTest: resetRoomTimelineReadingPositions,
+ } = await import("@/features/rooms/chat/use-room-timeline-scroll"));
// jsdom has no layout observer. Geometry tests supply measured entries;
// other component tests only need the browser API's lifecycle.
@@ -73,12 +81,55 @@ vi.waitFor = (callback, options) =>
typeof options === "number" ? options : { timeout: 5_000, ...options },
);
+// Files without module mocks share one window per worker (see
+// vitest.config.ts), so each test returns the globals it may touch to the state
+// the next file expects from a fresh environment.
+const initialHeadNodes =
+ typeof document === "undefined" ? [] : [...document.head.childNodes];
+const initialUrl = typeof window === "undefined" ? "" : window.location.href;
+
+function resetDocumentGlobals() {
+ if (typeof document === "undefined") return;
+ // A test may stub storage with a plain object; vi.stubGlobal restores the
+ // real one afterwards, which that test never wrote to.
+ for (const storage of [localStorage, sessionStorage]) {
+ if (storage instanceof Storage) storage.clear();
+ }
+ document.body.replaceChildren();
+ for (const attribute of [...document.body.attributes]) {
+ document.body.removeAttribute(attribute.name);
+ }
+ for (const node of [...document.head.childNodes]) {
+ if (!initialHeadNodes.includes(node)) node.remove();
+ }
+ for (const attribute of [...document.documentElement.attributes]) {
+ document.documentElement.removeAttribute(attribute.name);
+ }
+ document.title = "";
+ if (window.location.href !== initialUrl) {
+ window.history.replaceState(null, "", initialUrl);
+ }
+}
+
afterEach(() => {
try {
cleanupRenderedComponents?.();
+ // Shared modules such as Motion's frame loop keep a "frame requested" flag
+ // until their callback runs; dropping a fake frame or timer would stall
+ // them for every later file in this worker, so pending ones run first.
+ if (vi.isFakeTimers()) vi.runOnlyPendingTimers();
} finally {
+ vi.useRealTimers();
vi.unstubAllEnvs();
+ restoreGlobalProperties();
+ // TanStack Query keeps focus and network state in module singletons that a
+ // test drives through browser events; a stale "offline" or "unfocused"
+ // would pause every later file's queries in this worker.
+ focusManager.setFocused(undefined);
+ onlineManager.setOnline(true);
+ resetDocumentGlobals();
resetComposerAttachmentDraftsForTest();
+ resetRoomTimelineReadingPositions?.();
assertNoUnhandledTestRoutes();
}
});
diff --git a/apps/web/src/test/vitest-isolation.test.ts b/apps/web/src/test/vitest-isolation.test.ts
new file mode 100644
index 00000000..92a31a88
--- /dev/null
+++ b/apps/web/src/test/vitest-isolation.test.ts
@@ -0,0 +1,23 @@
+import { fileURLToPath } from "node:url";
+import { describe, expect, it } from "vitest";
+
+import { partitionTestFiles, usesModuleMocks } from "../../vitest.isolation";
+
+describe("Vitest isolation partition", () => {
+ it("keeps every file that replaces modules out of the shared projects", () => {
+ expect(usesModuleMocks('vi.mock("./x", () => ({}));')).toBe(true);
+ expect(usesModuleMocks("vi.doMock('./x');")).toBe(true);
+ expect(usesModuleMocks("vi.resetModules();")).toBe(true);
+ expect(usesModuleMocks("vi.fn(); vi.spyOn(window, 'open');")).toBe(false);
+ });
+
+ it("splits the real test files without losing any", () => {
+ const root = fileURLToPath(new URL("../..", import.meta.url));
+ const { isolated, shared } = partitionTestFiles(root, "src/**/*.test.tsx");
+ expect(isolated).toContain(
+ "src/features/rooms/documents/document-voice-selection-control.test.tsx",
+ );
+ expect(shared).toContain("src/features/rooms/room-navigation.test.tsx");
+ expect(isolated.filter((file) => shared.includes(file))).toEqual([]);
+ });
+});
diff --git a/apps/web/vitest.config.ts b/apps/web/vitest.config.ts
index 74b4d0af..c7afba1e 100644
--- a/apps/web/vitest.config.ts
+++ b/apps/web/vitest.config.ts
@@ -2,6 +2,11 @@ import react from "@vitejs/plugin-react";
import { fileURLToPath } from "node:url";
import { configDefaults, defineConfig } from "vitest/config";
import { hugeiconsPerIconImports } from "./vitest.hugeicons-imports";
+import { partitionTestFiles } from "./vitest.isolation";
+
+const root = fileURLToPath(new URL(".", import.meta.url));
+const nodeFiles = partitionTestFiles(root, "src/**/*.test.ts");
+const domFiles = partitionTestFiles(root, "src/**/*.test.tsx");
export default defineConfig({
plugins: [react(), hugeiconsPerIconImports()],
@@ -10,19 +15,35 @@ export default defineConfig({
hookTimeout: 15_000,
setupFiles: ["src/test/setup.ts"],
exclude: [...configDefaults.exclude, "src/**/*.build.test.ts"],
+ // Files sharing a worker must not see each other's stubs, spies, or env.
+ unstubGlobals: true,
+ unstubEnvs: true,
+ restoreMocks: true,
// Four workers leave room for the dev stack.
maxWorkers: 4,
// Threads share one process: about half the system CPU of forks.
pool: "threads",
// Logic tests (.ts) skip the jsdom environment; a .ts file that needs the
// DOM opts in with `// @vitest-environment jsdom`.
+ // Creating a jsdom window and importing the app graph costs more than most
+ // files' tests, so files without module mocks share one environment and
+ // module cache per worker. src/test/setup.ts resets the globals they touch.
projects: [
{
extends: true,
test: {
name: "node",
environment: "node",
- include: ["src/**/*.test.ts"],
+ include: nodeFiles.shared,
+ isolate: false,
+ },
+ },
+ {
+ extends: true,
+ test: {
+ name: "node-isolated",
+ environment: "node",
+ include: nodeFiles.isolated,
},
},
{
@@ -30,7 +51,16 @@ export default defineConfig({
test: {
name: "jsdom",
environment: "jsdom",
- include: ["src/**/*.test.tsx"],
+ include: domFiles.shared,
+ isolate: false,
+ },
+ },
+ {
+ extends: true,
+ test: {
+ name: "jsdom-isolated",
+ environment: "jsdom",
+ include: domFiles.isolated,
},
},
],
diff --git a/apps/web/vitest.isolation.ts b/apps/web/vitest.isolation.ts
new file mode 100644
index 00000000..7d6b55a4
--- /dev/null
+++ b/apps/web/vitest.isolation.ts
@@ -0,0 +1,30 @@
+import { globSync, readFileSync } from "node:fs";
+import { join } from "node:path";
+
+// A module cache shared across files makes a later file's vi.mock ineffective
+// once an earlier file imported the real module, so files that mock modules
+// keep a fresh module graph. Detecting them from the source at config load
+// means a new mocking file can never land in a shared project by omission.
+const MODULE_MOCK_PATTERN = /\bvi\.(mock|doMock|resetModules)\(/;
+
+export function usesModuleMocks(source: string): boolean {
+ return MODULE_MOCK_PATTERN.test(source);
+}
+
+export interface TestFilePartition {
+ isolated: string[];
+ shared: string[];
+}
+
+export function partitionTestFiles(
+ root: string,
+ pattern: string,
+): TestFilePartition {
+ const isolated: string[] = [];
+ const shared: string[] = [];
+ for (const file of globSync(pattern, { cwd: root }).sort()) {
+ const source = readFileSync(join(root, file), "utf8");
+ (usesModuleMocks(source) ? isolated : shared).push(file);
+ }
+ return { isolated, shared };
+}