Skip to content
TypeScript

test(web): migrate the last .ts browser tests and stop wrapping userEvent in act (#22424)

Julius Marmingef7f9e217857e
diff --git a/apps/web/src/components/ChatMarkdown.browser.test.tsx b/apps/web/src/components/ChatMarkdown.browser.test.tsx
index 75ccf03b8a6..01a343282cf 100644
--- a/apps/web/src/components/ChatMarkdown.browser.test.tsx
+++ b/apps/web/src/components/ChatMarkdown.browser.test.tsx
@@ -1420,7 +1420,7 @@ describe("ChatMarkdown math", () => {
});
const [preview, after] = container.querySelectorAll("button");
preview!.focus();
- await act(() => userEvent.tab());
+ await userEvent.tab();
expect(document.activeElement).toBe(after);
if (formula.includes("notACommand")) {
expect(page.getByRole("button", { name: /notACommand/ }).element()).toBe(preview);
@@ -1439,7 +1439,7 @@ describe("ChatMarkdown math", () => {
);
const { container } = screen;
container.querySelector("button")!.focus();
- await act(() => userEvent.tab());
+ await userEvent.tab();
expect(document.activeElement).toBe(
container.querySelector('[aria-label="Scroll inline equation"]'),
);
diff --git a/apps/web/src/components/ComposerPromptEditorTiptap.input.browser.test.tsx b/apps/web/src/components/ComposerPromptEditorTiptap.input.browser.test.tsx
index 6b4884efdc9..a5c1a1e87a1 100644
--- a/apps/web/src/components/ComposerPromptEditorTiptap.input.browser.test.tsx
+++ b/apps/web/src/components/ComposerPromptEditorTiptap.input.browser.test.tsx
@@ -484,7 +484,7 @@ describe("composer context undo lifetime", () => {
const nextEditor = composer.editor();
expect(nextEditor).not.toBe(previousEditor);
expect(document.activeElement).toBe(nextEditor.view.dom);
- await act(async () => userEvent.keyboard("x"));
+ await userEvent.keyboard("x");
expect(composer.draft().value).toBe("xDraft B");
const button = document.createElement("button");
diff --git a/apps/web/src/components/ThreadStatusIndicators.subscriptions.browser.test.tsx b/apps/web/src/components/ThreadStatusIndicators.subscriptions.browser.test.tsx
index 9e2aa3f0cc3..7b426d756b4 100644
--- a/apps/web/src/components/ThreadStatusIndicators.subscriptions.browser.test.tsx
+++ b/apps/web/src/components/ThreadStatusIndicators.subscriptions.browser.test.tsx
@@ -200,7 +200,7 @@ it("keeps a long PR hover list in the viewport and lets the last row be selected
/>
</div>,
);
- await act(() => userEvent.hover(screen.container.querySelector("button")!));
+ await userEvent.hover(screen.container.querySelector("button")!);
const popup = () => document.querySelector<HTMLElement>('[data-slot="tooltip-popup"]')!;
await expect.poll(() => popup()?.querySelectorAll("a").length).toBe(40);
await expect.poll(() => popup().getBoundingClientRect().top).toBeGreaterThanOrEqual(0);
@@ -212,13 +212,13 @@ it("keeps a long PR hover list in the viewport and lets the last row be selected
expect(lastRow.getBoundingClientRect().top).toBeGreaterThan(
popup().getBoundingClientRect().bottom,
);
- await act(() => userEvent.wheel(popup(), { delta: { y: 10_000 } }));
+ await userEvent.wheel(popup(), { delta: { y: 10_000 } });
await expect
.poll(() => lastRow.getBoundingClientRect().bottom)
.toBeLessThanOrEqual(popup().getBoundingClientRect().bottom);
expect(lastRow.getBoundingClientRect().top).toBeGreaterThanOrEqual(
popup().getBoundingClientRect().top,
);
- await act(() => userEvent.click(lastRow));
+ await userEvent.click(lastRow);
expect(onOpenPullRequest).toHaveBeenCalledExactlyOnceWith(expect.anything(), lastRow.href);
});
diff --git a/apps/web/src/components/chat/ComposerBannerStack.browser.test.tsx b/apps/web/src/components/chat/ComposerBannerStack.browser.test.tsx
index 51bb2d4e642..01a1ed13fdc 100644
--- a/apps/web/src/components/chat/ComposerBannerStack.browser.test.tsx
+++ b/apps/web/src/components/chat/ComposerBannerStack.browser.test.tsx
@@ -84,12 +84,12 @@ it("keeps only the usage limit attached while an active goal waits in the collap
"Usage limit reached",
);
- await act(async () => page.getByRole("button", { name: "Show other notices" }).click());
+ await page.getByRole("button", { name: "Show other notices" }).click();
await expect.element(goal).toBeVisible();
await expect.element(limit).toBeVisible();
await expect.poll(visibleBanners).toHaveLength(2);
- await act(async () => userEvent.keyboard("{Escape}"));
+ await userEvent.keyboard("{Escape}");
await expect.element(goal).not.toBeVisible();
await expect.element(limit).toBeVisible();
expect(visibleBanners()).toHaveLength(1);
diff --git a/apps/web/src/components/chat/ComposerStashMenu.browser.test.tsx b/apps/web/src/components/chat/ComposerStashMenu.browser.test.tsx
index 752ec8af46f..01dae940a8e 100644
--- a/apps/web/src/components/chat/ComposerStashMenu.browser.test.tsx
+++ b/apps/web/src/components/chat/ComposerStashMenu.browser.test.tsx
@@ -66,7 +66,7 @@ const editor = () => page.getByRole("textbox", { name: "Message" });
const stash = () => page.getByRole("list", { name: "Stashed prompts" });
const restore = (prompt: string) =>
page.getByRole("button", { name: `Restore stashed prompt: ${prompt}` });
-const press = (keys: string) => act(async () => userEvent.keyboard(keys));
+const press = (keys: string) => userEvent.keyboard(keys);
const focus = (element: Element) => act(async () => (element as HTMLElement).focus());
it("leaves dialog, unrelated input and question button shortcuts alone while the stash is open", async () => {
@@ -128,7 +128,7 @@ it("navigates, deletes and restores stashed prompts from the composer and drawer
await press("{Escape}");
await expect.element(stash()).not.toBeInTheDocument();
- await act(async () => userEvent.click(page.getByRole("button", { name: "Open stash" })));
+ await userEvent.click(page.getByRole("button", { name: "Open stash" }));
await expect.element(restore("first prompt")).not.toBeInTheDocument();
expect(stash().element().textContent).toContain("second prompt");
await focus(editor().element());
diff --git a/apps/web/src/components/chat/MessagesTimeline.browser.test.tsx b/apps/web/src/components/chat/MessagesTimeline.browser.test.tsx
index 7b99f41dad7..665eb5e16f6 100644
--- a/apps/web/src/components/chat/MessagesTimeline.browser.test.tsx
+++ b/apps/web/src/components/chat/MessagesTimeline.browser.test.tsx
@@ -215,10 +215,8 @@ describe("MessagesTimeline work rows", () => {
);
const row = screen.container.querySelector<HTMLElement>('[data-v2-item-type="file_change"]')!;
const press = async (target: HTMLElement) => {
- await act(async () => {
- target.focus();
- await userEvent.keyboard(key);
- });
+ target.focus();
+ await userEvent.keyboard(key);
};
expect(row.getAttribute("aria-expanded")).toBe("false");
await press(row);
diff --git a/apps/web/src/components/chat/ProviderModelPicker.browser.test.tsx b/apps/web/src/components/chat/ProviderModelPicker.browser.test.tsx
index 21a39de1f76..95b2d99e4ce 100644
--- a/apps/web/src/components/chat/ProviderModelPicker.browser.test.tsx
+++ b/apps/web/src/components/chat/ProviderModelPicker.browser.test.tsx
@@ -12,7 +12,7 @@ import { page, userEvent } from "vite-plus/test/browser";
import "~/index.css";
-import { act, render as renderUi } from "../../../test/render";
+import { render as renderUi } from "../../../test/render";
import { deriveProviderInstanceEntries } from "../../providerInstances";
import { ProviderModelPicker } from "./ProviderModelPicker";
import type { ModelEsque } from "./providerIconUtils";
@@ -85,7 +85,7 @@ function renderPicker(input: {
}
async function click(target: Parameters<typeof userEvent.click>[0]) {
- await act(async () => userEvent.click(target));
+ await userEvent.click(target);
}
async function openLegacyPicker(activeModel: string) {
diff --git a/apps/web/src/components/chat/QueuedRunsControl.browser.test.tsx b/apps/web/src/components/chat/QueuedRunsControl.browser.test.tsx
index 14a68afcb43..58da8b82f2a 100644
--- a/apps/web/src/components/chat/QueuedRunsControl.browser.test.tsx
+++ b/apps/web/src/components/chat/QueuedRunsControl.browser.test.tsx
@@ -30,7 +30,7 @@ vi.mock(import("../../assets/assetUrls"), async (importOriginal) => ({
resources.map((resource) => `https://assets.test/${resource.attachmentId}`)) as never,
}));
-import { act, render as renderUi } from "../../../test/render";
+import { render as renderUi } from "../../../test/render";
import { QueuedRunsControl } from "./QueuedRunsControl";
function setup() {
@@ -204,9 +204,7 @@ it("previews assistant quotes as readable text and preserves the citation when e
.element(page.getByText(`${quotedText} Why per worktree?`, { exact: true }))
.toBeVisible();
- await act(async () => {
- await page.getByRole("button", { name: "Edit queued message", exact: true }).nth(1).click();
- });
+ await page.getByRole("button", { name: "Edit queued message", exact: true }).nth(1).click();
expect(onEditQueuedRun).toHaveBeenCalledExactlyOnceWith(
expect.objectContaining({ text: quoteAndText }),
);
diff --git a/apps/web/src/components/chat/ThreadErrorBanner.browser.test.tsx b/apps/web/src/components/chat/ThreadErrorBanner.browser.test.tsx
index a25bb6eb6e6..0097c191d82 100644
--- a/apps/web/src/components/chat/ThreadErrorBanner.browser.test.tsx
+++ b/apps/web/src/components/chat/ThreadErrorBanner.browser.test.tsx
@@ -1,4 +1,4 @@
-import { act, render as renderUi } from "../../../test/render";
+import { render as renderUi } from "../../../test/render";
import "../../index.css";
import { expect, it } from "vite-plus/test";
@@ -15,13 +15,13 @@ it("expands even a short JSON error to its exact diagnostics and collapses back
await expect.element(page.getByText("Turn failed", { exact: true })).toBeVisible();
expect(container.textContent).not.toContain("unsupported_value");
- await act(async () => page.getByRole("button", { name: "Show full error" }).click());
+ await page.getByRole("button", { name: "Show full error" }).click();
const diagnostics = page.getByText(error, { exact: true });
await expect.element(diagnostics).toBeVisible();
expect(diagnostics.element().textContent).toBe(error);
- await act(async () => page.getByRole("button", { name: "Show less" }).click());
+ await page.getByRole("button", { name: "Show less" }).click();
await expect.element(page.getByText("Turn failed", { exact: true })).toBeVisible();
expect(container.textContent).not.toContain("unsupported_value");
diff --git a/apps/web/src/components/chat/composerFocusRedirect.browser.test.ts b/apps/web/src/components/chat/composerFocusRedirect.browser.test.ts
index d0e0f78dce5..8f5f195ae84 100644
--- a/apps/web/src/components/chat/composerFocusRedirect.browser.test.ts
+++ b/apps/web/src/components/chat/composerFocusRedirect.browser.test.ts
@@ -1,4 +1,4 @@
-import { afterEach, describe, expect, it } from "vite-plus/test";
+import { describe, expect, it } from "vite-plus/test";
import { shouldTypeToFocusComposer } from "./composerFocusRedirect";
@@ -15,14 +15,15 @@ function typeOn(target: Element, key: string): boolean {
return redirected;
}
-afterEach(() => {
- document.body.replaceChildren();
-});
+function attach(element: Element): Disposable {
+ document.body.append(element);
+ return { [Symbol.dispose]: () => element.remove() };
+}
describe("shouldTypeToFocusComposer", () => {
it("sends letters typed on the chat to the composer", () => {
const chat = document.createElement("div");
- document.body.append(chat);
+ using _chat = attach(chat);
expect(typeOn(chat, "a")).toBe(true);
});
@@ -31,7 +32,7 @@ describe("shouldTypeToFocusComposer", () => {
const deviceScreen = document.createElement("div");
deviceScreen.setAttribute("role", "application");
deviceScreen.tabIndex = 0;
- document.body.append(deviceScreen);
+ using _deviceScreen = attach(deviceScreen);
expect(typeOn(deviceScreen, "a")).toBe(false);
});
diff --git a/apps/web/src/components/chat/threadFindPosition.browser.test.ts b/apps/web/src/components/chat/threadFindPosition.browser.test.ts
index 792cdba1fcb..60ef3068557 100644
--- a/apps/web/src/components/chat/threadFindPosition.browser.test.ts
+++ b/apps/web/src/components/chat/threadFindPosition.browser.test.ts
@@ -1,15 +1,7 @@
-import { afterEach, beforeEach, describe, expect, it, vi } from "vite-plus/test";
+import { describe, expect, it, vi } from "vite-plus/test";
import { readThreadFindPosition } from "./threadFindPosition";
-afterEach(() => vi.restoreAllMocks());
-beforeEach(() => {
- Object.defineProperty(Range.prototype, "getBoundingClientRect", {
- configurable: true,
- writable: true,
- value: () => new DOMRect(),
- });
-});
-
+// The container stays detached, so unmocked ranges measure as an empty rect.
function viewport(text = "COD4 COD4") {
const container = document.createElement("div");
container.innerHTML = `<div data-timeline-row-id="above"><div data-thread-find-text>COD4</div></div>
@@ -27,7 +19,9 @@ function viewport(text = "COD4 COD4") {
describe("reading position for find", () => {
it("skips earlier rows and occurrences above the viewport within the current message", () => {
const container = viewport();
- vi.spyOn(Range.prototype, "getBoundingClientRect").mockImplementation(function (this: Range) {
+ using _ranges = vi.spyOn(Range.prototype, "getBoundingClientRect").mockImplementation(function (
+ this: Range,
+ ) {
return new DOMRect(0, this.startOffset === 0 ? 60 : 160, 40, 20);
});
expect(readThreadFindPosition(container, "COD4", (id) => id, 100)).toEqual({
@@ -38,7 +32,9 @@ describe("reading position for find", () => {
it("starts after the current message when all its occurrences are above the viewport", () => {
const container = viewport();
- vi.spyOn(Range.prototype, "getBoundingClientRect").mockReturnValue(new DOMRect(0, 60, 40, 20));
+ using _ranges = vi
+ .spyOn(Range.prototype, "getBoundingClientRect")
+ .mockReturnValue(new DOMRect(0, 60, 40, 20));
expect(readThreadFindPosition(container, "COD4", (id) => id, 100)).toEqual({
entryId: "reading",
occurrence: 2,
diff --git a/apps/web/src/components/desktop/SnapShotCoordinator.browser.test.ts b/apps/web/src/components/desktop/SnapShotCoordinator.browser.test.ts
index b38e2f7018d..2c590111609 100644
--- a/apps/web/src/components/desktop/SnapShotCoordinator.browser.test.ts
+++ b/apps/web/src/components/desktop/SnapShotCoordinator.browser.test.ts
@@ -9,9 +9,10 @@ import {
ProjectId,
ThreadId,
} from "@t3tools/contracts";
-import { act, createElement } from "react";
-import { createRoot, type Root } from "react-dom/client";
-import { afterEach, beforeEach, describe, expect, it, vi } from "vite-plus/test";
+import { createElement } from "react";
+import { describe, expect, it, vi } from "vite-plus/test";
+
+import { act, fakeTimers, render, type Screen } from "../../../test/render";
import { DraftId, useComposerDraftStore } from "../../composerDraftStore";
import type { DesktopSnapShotBridge } from "../../lib/desktopSnapShot";
@@ -66,7 +67,8 @@ const storage = vi.hoisted(() => {
const environmentId = EnvironmentId.make("snap-shot-environment");
const projectRef = scopeProjectRef(environmentId, ProjectId.make("snap-shot-project"));
-beforeEach(() => {
+// Tests stub globals and spy on module exports freely; disposing restores all of them.
+function setup(): Disposable {
storage.clear();
vi.stubGlobal("localStorage", storage);
useComposerDraftStore.setState({
@@ -76,17 +78,18 @@ beforeEach(() => {
stickyModelSelectionByProvider: {},
stickyActiveProvider: null,
});
-});
-
-afterEach(() => {
- dismissAllSnapShotAnimations();
- vi.useRealTimers();
- vi.unstubAllGlobals();
- vi.restoreAllMocks();
-});
+ return {
+ [Symbol.dispose]() {
+ dismissAllSnapShotAnimations();
+ vi.unstubAllGlobals();
+ vi.restoreAllMocks();
+ },
+ };
+}
describe("window capture failures", () => {
it("dismisses an older failed capture without disturbing a newer capture", async () => {
+ using _env = setup();
const target = DraftId.make("snap-shot-draft");
const pendingStarts = new Set<string>();
const soundedIds = new Set(["older", "newer"]);
@@ -113,6 +116,7 @@ describe("window capture failures", () => {
});
it("does not resurrect a failed capture when its draft becomes ready later", async () => {
+ using _env = setup();
const target = DraftId.make("snap-shot-draft");
let resolveTarget: ((target: DraftId) => void) | undefined;
const targetReady = new Promise<DraftId>((resolve) => {
@@ -133,6 +137,7 @@ describe("window capture failures", () => {
});
it("keeps global failures dismissing all active and pending captures", async () => {
+ using _env = setup();
const target = DraftId.make("snap-shot-draft");
let resolveTarget: ((target: DraftId) => void) | undefined;
const targetReady = new Promise<DraftId>((resolve) => {
@@ -168,10 +173,7 @@ describe("pending snapshot processing", () => {
},
};
const target = scopeThreadRef(environmentId, ThreadId.make("enabled-thread"));
- let root: Root;
- let container: HTMLDivElement;
-
- function setup(routeThreadRef: typeof target | null = target) {
+ function coordinatorFixture(routeThreadRef: typeof target | null = target) {
let currentSettings = {
...DEFAULT_CLIENT_SETTINGS,
snapShotEnabled: true,
@@ -212,43 +214,44 @@ describe("pending snapshot processing", () => {
const sound = vi.spyOn(snapShotSound, "playSnapShotSound").mockImplementation(() => undefined);
const toast = vi.spyOn(toastManager, "add").mockReturnValue("toast-id");
vi.stubGlobal("desktopBridge", bridge);
- vi.stubGlobal("IS_REACT_ACT_ENVIRONMENT", true);
- container = document.createElement("div");
- document.body.append(container);
- root = createRoot(container);
- const render = () => act(async () => root.render(createElement(SnapShotCoordinator)));
+ let screen: Screen | undefined;
+ // Settings and route changes rerender the same coordinator instead of remounting it.
+ const renderCoordinator = async () => {
+ if (screen) await screen.rerender(createElement(SnapShotCoordinator));
+ // useHandleNewThread is mocked above, so nothing in the coordinator touches the router.
+ else screen = await render(createElement(SnapShotCoordinator), { router: false });
+ };
return {
bridge,
route,
sound,
toast,
- render,
+ render: renderCoordinator,
setPending: (items: typeof pending) => {
pending = items;
},
setEnabled: async (snapShotEnabled: boolean) => {
currentSettings = { ...currentSettings, snapShotEnabled };
- await render();
+ await renderCoordinator();
},
emit: (event: DesktopSnapShotEvent) =>
act(async () => {
for (const listener of listeners) listener(event);
}),
+ [Symbol.asyncDispose]: async () => {
+ await screen?.[Symbol.asyncDispose]();
+ },
};
}
- afterEach(async () => {
- await act(async () => root?.unmount());
- container?.remove();
- });
-
const focus = () =>
act(async () => {
window.dispatchEvent(new Event("focus"));
});
it("leaves captures untouched while disabled and resumes them when enabled again", async () => {
- const fixture = setup();
+ using _env = setup();
+ await using fixture = coordinatorFixture();
const { bridge, sound, toast } = fixture;
await fixture.setEnabled(false);
await focus();
@@ -287,7 +290,8 @@ describe("pending snapshot processing", () => {
});
it("reports each pending capture failure once, allows a new failure kind, and resets after success", async () => {
- const fixture = setup(null);
+ using _env = setup();
+ await using fixture = coordinatorFixture(null);
const { bridge, sound, toast, route } = fixture;
await fixture.render();
await focus();
@@ -337,7 +341,8 @@ describe("pending snapshot processing", () => {
});
it("suppresses deferred failures while disabled and reports fresh failures after re-enable", async () => {
- const fixture = setup();
+ using _env = setup();
+ await using fixture = coordinatorFixture();
const { bridge, sound, toast } = fixture;
let rejectRead: ((error: Error) => void) | undefined;
bridge.readSnapShot.mockReturnValueOnce(
@@ -404,7 +409,8 @@ describe("pending snapshot processing", () => {
});
it("keeps a capture pending when disabled during target resolution, then retries on re-enable", async () => {
- const fixture = setup(null);
+ using _env = setup();
+ await using fixture = coordinatorFixture(null);
const { bridge, route } = fixture;
route.defaultProjectRef = projectRef;
const draftId = DraftId.make("resolving-snapshot");
@@ -432,7 +438,8 @@ describe("pending snapshot processing", () => {
});
it("finishes and acknowledges delivery already reading when disabled", async () => {
- const fixture = setup();
+ using _env = setup();
+ await using fixture = coordinatorFixture();
let finishReading: ((value: typeof capture) => void) | undefined;
const reading = new Promise<typeof capture>((resolve) => {
finishReading = resolve;
@@ -467,7 +474,8 @@ describe("window capture delivery", () => {
])(
"preserves capture contents for $target before a stalled animation finishes ($accessibleText)",
async ({ target, accessibleText }) => {
- vi.useFakeTimers();
+ using _env = setup();
+ using _timers = fakeTimers();
const never = new Promise<void>(() => undefined);
const animationFrames: Array<FrameRequestCallback> = [];
const acknowledgeSnapShot = vi.fn(async () => undefined);
@@ -574,6 +582,7 @@ describe("window capture delivery", () => {
describe("window capture target resolution", () => {
it("shares bare-route draft creation between animation start and capture drain", async () => {
+ using _env = setup();
const draftId = DraftId.make("snap-shot-draft");
let finishResolution: ((target: DraftId) => void) | undefined;
const resolveTarget = vi.fn(
@@ -595,6 +604,7 @@ describe("window capture target resolution", () => {
});
it("follows a draft to its promoted server thread", () => {
+ using _env = setup();
const draftId = DraftId.make("snap-shot-draft");
const promotedRef = scopeThreadRef(environmentId, ThreadId.make("snap-shot-promoted-thread"));
const store = useComposerDraftStore.getState();
@@ -607,6 +617,7 @@ describe("window capture target resolution", () => {
});
it("keeps the routed server thread before its shell loads", () => {
+ using _env = setup();
const routeThreadRef = scopeThreadRef(environmentId, ThreadId.make("snap-shot-routed-thread"));
expect(resolveExistingSnapShotTarget(routeThreadRef, routeThreadRef)).toEqual(routeThreadRef);
@@ -638,6 +649,7 @@ describe("open question delivery", () => {
};
it("attaches a capture to the open question draft and leaves the thread draft alone", async () => {
+ using _env = setup();
const pins = new Map();
const untrack = trackOpenQuestionAttachmentDraft(threadRef, request);
try {
@@ -655,6 +667,7 @@ describe("open question delivery", () => {
});
it("falls back to the thread when a newer question replaces the pinned one during compression", async () => {
+ using _env = setup();
const pins = new Map();
const untrackFirst = trackOpenQuestionAttachmentDraft(threadRef, request);
let untrackSecond = () => {};
@@ -686,6 +699,7 @@ describe("open question delivery", () => {
});
it("keeps a capture pinned before any question off a question that opens during the read", async () => {
+ using _env = setup();
const pins = new Map();
const resolveTarget = () => resolveSnapShotAttachmentTarget(pins, capture.id, threadRef);
// The drain pins a capture it never saw requested before reading it.
@@ -707,6 +721,7 @@ describe("open question delivery", () => {
});
it("refuses a capture once the request's other questions hold the shared limit", async () => {
+ using _env = setup();
useComposerDraftStore.getState().addImages(
first,
Array.from({ length: PROVIDER_SEND_TURN_MAX_ATTACHMENTS }, (_, index) => ({
@@ -739,6 +754,7 @@ describe("durable snapshot delivery", () => {
it.each([false, true])(
"retains a capture on quota failure and retries without duplicates (staged: %s)",
async (staged) => {
+ using _env = setup();
const target = scopeThreadRef(environmentId, ThreadId.make("quota-thread"));
const capture = {
id: "12345678-1234-1234-1234-123456789abc",
@@ -798,6 +814,7 @@ describe("snapshot destination ownership", () => {
it.each(["unmount", "blur", "disabled animations"])(
"keeps the original environment and thread after %s",
async (reason) => {
+ using _env = setup();
const original = scopeThreadRef(environmentId, ThreadId.make("original"));
const next = scopeThreadRef(EnvironmentId.make("another-environment"), ThreadId.make("next"));
const targets = new Map<string, Promise<typeof original | null>>();
diff --git a/apps/web/src/components/preview/PreviewPanelShell.a11y.browser.test.tsx b/apps/web/src/components/preview/PreviewPanelShell.a11y.browser.test.tsx
index 09613f4d578..23ff1bb4d5b 100644
--- a/apps/web/src/components/preview/PreviewPanelShell.a11y.browser.test.tsx
+++ b/apps/web/src/components/preview/PreviewPanelShell.a11y.browser.test.tsx
@@ -59,7 +59,7 @@ function nextFrame() {
async function enterFocusScope() {
const toggle = document.querySelector<HTMLElement>('[aria-label="Toggle right panel"]')!;
await act(async () => toggle.focus());
- await act(() => userEvent.tab());
+ await userEvent.tab();
await act(nextFrame);
}
diff --git a/apps/web/src/components/preview/previewSessionSync.browser.test.ts b/apps/web/src/components/preview/previewSessionSync.browser.test.ts
index ba6a60cdbb4..ac19c95f4fd 100644
--- a/apps/web/src/components/preview/previewSessionSync.browser.test.ts
+++ b/apps/web/src/components/preview/previewSessionSync.browser.test.ts
@@ -7,9 +7,10 @@ import {
} from "@t3tools/contracts";
import * as Cause from "effect/Cause";
import { AsyncResult, Atom } from "effect/reactivity";
-import { act, createElement } from "react";
-import { createRoot, type Root } from "react-dom/client";
-import { afterEach, beforeEach, describe, expect, it, vi } from "vite-plus/test";
+import { createElement } from "react";
+import { describe, expect, it, vi } from "vite-plus/test";
+
+import { act, render } from "../../../test/render";
// Only the transport is substituted. The hook, atom registry and preview
// store run unchanged, including lazy evaluation and refresh notifications.
@@ -78,71 +79,70 @@ import { AppAtomRegistryProvider, appAtomRegistry } from "~/rpc/atomRegistry";
import { previewEnvironment } from "~/state/preview";
import { useDesktopHostedPreviewSessions, usePreviewSession } from "./usePreviewSession";
-let root: Root | null = null;
-let container: HTMLDivElement | null = null;
-let sequence = 0;
-let ref: ScopedThreadRef;
-
-function SessionSync() {
- usePreviewSession(ref);
- return null;
-}
-
-const listAtom = () => {
- previewEnvironment.list({ environmentId: ref.environmentId, input: { threadId: ref.threadId } });
- return harness.lists.get(ref.threadId)!.atom;
-};
-const result = (
- revision: number,
- tabIds: string[],
- serverEpoch = "epoch-1",
-): PreviewListResult => ({
- serverEpoch,
- revision,
- sessions: tabIds.map((tabId) => ({
- threadId: ref.threadId,
- tabId,
- navStatus: { _tag: "Idle" },
- canGoBack: false,
- canGoForward: false,
- updatedAt: "2026-10-02T00:00:00.000Z",
- })),
-});
-
-function DesktopSessionSync() {
- useDesktopHostedPreviewSessions(ref.environmentId);
- return null;
-}
+function setup() {
+ harness.lists.clear();
+ harness.events.clear();
+ resetPreviewStateForTests();
+ // The app atom registry outlives each test, so every test gets its own environment and thread.
+ const testName = expect.getState().currentTestName!;
+ const ref: ScopedThreadRef = {
+ environmentId: EnvironmentId.make(`preview-sync ${testName}`),
+ threadId: ThreadId.make(`thread-sync ${testName}`),
+ };
-async function mount(Component = SessionSync) {
- container = document.body.appendChild(document.createElement("div"));
- root = createRoot(container);
- await act(async () => {
- root!.render(createElement(AppAtomRegistryProvider, null, createElement(Component)));
+ const listAtom = () => {
+ previewEnvironment.list({
+ environmentId: ref.environmentId,
+ input: { threadId: ref.threadId },
+ });
+ return harness.lists.get(ref.threadId)!.atom;
+ };
+ const result = (
+ revision: number,
+ tabIds: string[],
+ serverEpoch = "epoch-1",
+ ): PreviewListResult => ({
+ serverEpoch,
+ revision,
+ sessions: tabIds.map((tabId) => ({
+ threadId: ref.threadId,
+ tabId,
+ navStatus: { _tag: "Idle" },
+ canGoBack: false,
+ canGoForward: false,
+ updatedAt: "2026-10-02T00:00:00.000Z",
+ })),
});
-}
-beforeEach(() => {
- vi.stubGlobal("IS_REACT_ACT_ENVIRONMENT", true);
- sequence += 1;
- ref = {
- environmentId: EnvironmentId.make(`preview-sync-${sequence}`),
- threadId: ThreadId.make(`thread-sync-${sequence}`),
- };
-});
+ function SessionSync() {
+ usePreviewSession(ref);
+ return null;
+ }
+ function DesktopSessionSync() {
+ useDesktopHostedPreviewSessions(ref.environmentId);
+ return null;
+ }
+ // The session hooks render nothing and never read or change the route.
+ const mount = (Component: () => null = SessionSync) =>
+ render(createElement(AppAtomRegistryProvider, null, createElement(Component)), {
+ router: false,
+ });
-afterEach(async () => {
- await act(async () => root?.unmount());
- root = null;
- container?.remove();
- container = null;
- resetPreviewStateForTests();
- vi.unstubAllGlobals();
-});
+ return {
+ ref,
+ listAtom,
+ result,
+ mount,
+ DesktopSessionSync,
+ [Symbol.dispose]: () => resetPreviewStateForTests(),
+ };
+}
describe("native preview session synchronization", () => {
it("discovers and closes a server tab in a background thread without mounting its chat", async () => {
- await mount(DesktopSessionSync);
+ using sync = setup();
+ const { ref, listAtom, result } = sync;
+ await using _screen = await sync.mount(sync.DesktopSessionSync);
expect(readThreadPreviewState(ref).sessions).toEqual({});
previewEnvironment.events({ environmentId: ref.environmentId, input: {} });
const events = harness.events.get(ref.environmentId)!;
@@ -183,18 +183,22 @@ describe("native preview session synchronization", () => {
});
it("evaluates the lazy list once and restores sessions that predate mounting", async () => {
+ using sync = setup();
+ const { ref, listAtom, result } = sync;
const atom = listAtom();
- await mount();
+ await using _screen = await sync.mount();
expect(harness.lists.get(ref.threadId)?.box.requests).toBe(1);
appAtomRegistry.set(atom, AsyncResult.success(result(1, ["restored"])));
expect(readThreadPreviewState(ref).activeTabId).toBe("restored");
});
it("preserves a local tab while cached absence is waiting for a fresh response", async () => {
+ using sync = setup();
+ const { ref, listAtom, result } = sync;
const atom = listAtom();
appAtomRegistry.set(atom, AsyncResult.waiting(AsyncResult.success(result(1, []))));
applyPreviewServerSnapshot(ref, result(1, ["local"]).sessions[0]!);
- await mount();
+ await using _screen = await sync.mount();
expect(readThreadPreviewState(ref).activeTabId).toBe("local");
expect(harness.lists.get(ref.threadId)?.box.requests).toBe(0);
appAtomRegistry.set(atom, AsyncResult.success(result(2, ["local"])));
@@ -204,6 +208,8 @@ describe("native preview session synchronization", () => {
});
it("refreshes a completed cache without treating its old absence as authoritative", async () => {
+ using sync = setup();
+ const { ref, listAtom, result } = sync;
const atom = listAtom();
appAtomRegistry.set(atom, AsyncResult.success(result(1, [])));
reconcilePreviewServerSessions(ref, result(1, []));
@@ -221,7 +227,7 @@ describe("native preview session synchronization", () => {
controller: "human",
favicon: null,
});
- await mount();
+ await using _screen = await sync.mount();
expect(harness.lists.get(ref.threadId)?.box.requests).toBe(1);
expect(readThreadPreviewState(ref).activeTabId).toBe("local");
expect(readThreadPreviewState(ref).desktopOverlay?.zoomFactor).toBe(1.5);
@@ -231,8 +237,10 @@ describe("native preview session synchronization", () => {
});
it("retains newer event state when an older list response completes, then retries the list", async () => {
+ using sync = setup();
+ const { ref, listAtom, result } = sync;
const atom = listAtom();
- await mount();
+ await using _screen = await sync.mount();
const snapshot = result(2, ["opened"]).sessions[0]!;
previewEnvironment.events({ environmentId: ref.environmentId, input: {} });
appAtomRegistry.set(
@@ -261,9 +269,11 @@ describe("native preview session synchronization", () => {
});
it("keeps the local snapshot on a completed failure and reconciles a later success", async () => {
+ using sync = setup();
+ const { ref, listAtom, result } = sync;
const atom = listAtom();
applyPreviewServerSnapshot(ref, result(1, ["local"]).sessions[0]!);
- await mount();
+ await using _screen = await sync.mount();
appAtomRegistry.set(atom, AsyncResult.failure(Cause.die("offline")));
expect(readThreadPreviewState(ref).activeTabId).toBe("local");
appAtomRegistry.set(atom, AsyncResult.success(result(2, [])));
diff --git a/apps/web/src/components/pullRequest/PullRequestCandidatePicker.browser.test.tsx b/apps/web/src/components/pullRequest/PullRequestCandidatePicker.browser.test.tsx
index b6b6cb6248b..7952157a948 100644
--- a/apps/web/src/components/pullRequest/PullRequestCandidatePicker.browser.test.tsx
+++ b/apps/web/src/components/pullRequest/PullRequestCandidatePicker.browser.test.tsx
@@ -1,4 +1,4 @@
-import { act, render } from "../../../test/render";
+import { render } from "../../../test/render";
import { describe, expect, it, vi } from "vite-plus/test";
import { userEvent } from "vite-plus/test/browser";
@@ -40,21 +40,19 @@ describe("disabled candidate picker", () => {
'button[aria-label="Request reviewers"]',
)!;
if (input === "keyboard") {
- await act(() => userEvent.tab());
+ await userEvent.tab();
expect(document.activeElement).toBe(trigger);
} else {
- await act(() => userEvent.hover(trigger));
+ await userEvent.hover(trigger);
}
await expect
.poll(() => document.querySelector('[data-slot="tooltip-popup"][data-open]')?.textContent)
.toContain("Only collaborators can request reviewers.");
- await act(async () => {
- trigger.focus();
- await userEvent.keyboard("{Enter}");
- await userEvent.keyboard(" ");
- // Playwright skips aria-disabled targets; the click must still land to prove it is inert.
- await userEvent.click(trigger, { force: true });
- });
+ trigger.focus();
+ await userEvent.keyboard("{Enter}");
+ await userEvent.keyboard(" ");
+ // Playwright skips aria-disabled targets; the click must still land to prove it is inert.
+ await userEvent.click(trigger, { force: true });
expect(onOpenChange).not.toHaveBeenCalled();
expect(onSelect).not.toHaveBeenCalled();
},
diff --git a/apps/web/src/components/settings/AddProviderInstanceDialog.environment.browser.test.tsx b/apps/web/src/components/settings/AddProviderInstanceDialog.environment.browser.test.tsx
index 1a11e8e0ebc..7fc7520cb52 100644
--- a/apps/web/src/components/settings/AddProviderInstanceDialog.environment.browser.test.tsx
+++ b/apps/web/src/components/settings/AddProviderInstanceDialog.environment.browser.test.tsx
@@ -122,7 +122,7 @@ const input = (selector: string) => {
return found!;
};
async function type(selector: string, value: string) {
- await act(async () => userEvent.fill(input(selector), value));
+ await userEvent.fill(input(selector), value);
await act(async () => input(selector).blur());
}
const signInStep = () => document.querySelector('[aria-label="Sign-in step"]');
diff --git a/apps/web/src/components/settings/CaptureShortcutConfig.browser.test.tsx b/apps/web/src/components/settings/CaptureShortcutConfig.browser.test.tsx
index 3fc121d19e2..0dc5432dee7 100644
--- a/apps/web/src/components/settings/CaptureShortcutConfig.browser.test.tsx
+++ b/apps/web/src/components/settings/CaptureShortcutConfig.browser.test.tsx
@@ -85,8 +85,8 @@ async function renderConfig(desktop: "niri" | "hyprland" = "niri") {
await act(async () => target!.click());
},
async recordKeys(keys: string) {
- await act(async () => userEvent.click(recorder()));
- await act(async () => userEvent.keyboard(keys));
+ await userEvent.click(recorder());
+ await userEvent.keyboard(keys);
},
});
}
@@ -184,9 +184,9 @@ it.each(["Escape", "blur"])(
using _env = setup();
await using screen = await renderConfig();
await screen.click("Review changes");
- await act(async () => userEvent.click(screen.recorder()));
+ await userEvent.click(screen.recorder());
expect(screen.button("Save shortcut")?.disabled).toBe(true);
- if (cancel === "Escape") await act(async () => userEvent.keyboard("{Escape}"));
+ if (cancel === "Escape") await userEvent.keyboard("{Escape}");
else await act(async () => screen.recorder().blur());
expect(screen.button("Save shortcut")?.disabled).toBe(false);
expect(bridge.previewSnapShotConfig).toHaveBeenCalledOnce();
diff --git a/apps/web/src/components/settings/FontFamilyPicker.browser.test.tsx b/apps/web/src/components/settings/FontFamilyPicker.browser.test.tsx
index 1a2495f0c37..fa4327da432 100644
--- a/apps/web/src/components/settings/FontFamilyPicker.browser.test.tsx
+++ b/apps/web/src/components/settings/FontFamilyPicker.browser.test.tsx
@@ -48,10 +48,10 @@ describe("FontFamilyPicker", () => {
const input = document.querySelector<HTMLInputElement>('input[placeholder="Search fonts…"]');
expect(input).not.toBeNull();
- const press = (key: string) => act(() => userEvent.keyboard(`{${key}}`));
+ const press = (key: string) => userEvent.keyboard(`{${key}}`);
// Both matches were already rendered further down the unfiltered list.
- await act(() => userEvent.type(input!, "co"));
+ await userEvent.type(input!, "co");
await expect.poll(highlightedOptions).toEqual(["Courier New"]);
await press("ArrowDown");
diff --git a/apps/web/src/components/settings/ProjectSettingsPanel.browser.test.tsx b/apps/web/src/components/settings/ProjectSettingsPanel.browser.test.tsx
index 4a47a353dbe..5f7137ca5b3 100644
--- a/apps/web/src/components/settings/ProjectSettingsPanel.browser.test.tsx
+++ b/apps/web/src/components/settings/ProjectSettingsPanel.browser.test.tsx
@@ -438,19 +438,19 @@ describe("project settings scope", () => {
const primaryOption = () => page.getByRole("menuitemradio", { name: /^primary/ });
const remoteOption = () => page.getByRole("menuitemradio", { name: /^remote/ });
- await act(async () => userEvent.click(environmentMenu()));
+ await userEvent.click(environmentMenu());
await expect.element(primaryOption()).toBeVisible();
await expect.element(remoteOption()).toBeVisible();
- await act(async () => userEvent.keyboard("{Escape}"));
+ await userEvent.keyboard("{Escape}");
await act(async () =>
screen.router.navigate({ to: "/settings/projects", search: () => ({ project: key }) }),
);
await expect.element(page.getByRole("textbox", { name: "Project name" })).toBeVisible();
- await act(async () => userEvent.click(environmentMenu()));
+ await userEvent.click(environmentMenu());
await expect.element(primaryOption()).toBeVisible();
await expect.element(remoteOption()).not.toBeInTheDocument();
- await act(async () => userEvent.keyboard("{Escape}"));
+ await userEvent.keyboard("{Escape}");
await act(async () =>
screen.router.navigate({
@@ -458,10 +458,10 @@ describe("project settings scope", () => {
search: () => ({ project: "removed-project" }),
}),
);
- await act(async () => userEvent.click(environmentMenu()));
+ await userEvent.click(environmentMenu());
await expect.element(primaryOption()).toBeVisible();
await expect.element(remoteOption()).toBeVisible();
- await act(async () => userEvent.click(remoteOption()));
+ await userEvent.click(remoteOption());
await vi.waitFor(() =>
expect(screen.router.state.location.search).toEqual({
project: "removed-project",
@@ -491,9 +491,7 @@ describe("project settings scope", () => {
await expect
.element(page.getByRole("button", { name: "Environment scope: remote" }))
.toBeVisible();
- await act(async () =>
- userEvent.click(page.getByRole("button", { name: "Show all environments" })),
- );
+ await userEvent.click(page.getByRole("button", { name: "Show all environments" }));
await expect
.element(page.getByRole("textbox", { name: "Project name" }))
@@ -517,7 +515,7 @@ it("returns to the project overview after removal, clearing the selection but ke
(button) => button.textContent === "Remove project",
)!;
- await act(async () => userEvent.click(removeProject));
+ await userEvent.click(removeProject);
await vi.waitFor(() => {
expect(screen.router.state.location.pathname).toBe("/settings/projects");
diff --git a/apps/web/src/components/settings/ProviderSetupSection.browser.test.tsx b/apps/web/src/components/settings/ProviderSetupSection.browser.test.tsx
index a02de7ed5b7..d3e25b90159 100644
--- a/apps/web/src/components/settings/ProviderSetupSection.browser.test.tsx
+++ b/apps/web/src/components/settings/ProviderSetupSection.browser.test.tsx
@@ -195,7 +195,7 @@ describe("Antigravity setup", () => {
resetSetup();
const callbackUrl = "http://127.0.0.1:5555/?state=test-only&code=test-only";
await using screen = await renderSetup();
- await act(async () => userEvent.fill(screen.callbackInput(), callbackUrl));
+ await userEvent.fill(screen.callbackInput(), callbackUrl);
await screen.click("Continue");
expect(setup.completeAuth).toHaveBeenCalledWith({
@@ -244,11 +244,9 @@ describe("Antigravity setup", () => {
};
setup.auth = authState({ interaction });
await using screen = await renderSetup();
- await act(async () =>
- userEvent.fill(
- screen.callbackInput(),
- "http://127.0.0.1:5555/?state=old-flow&code=test-only",
- ),
+ await userEvent.fill(
+ screen.callbackInput(),
+ "http://127.0.0.1:5555/?state=old-flow&code=test-only",
);
setup.auth = authState({ flowId: "flow-2", interaction });
await publish();
diff --git a/apps/web/src/components/settings/SnapShotSettings.browser.test.tsx b/apps/web/src/components/settings/SnapShotSettings.browser.test.tsx
index 67b144d0112..f2ae1fefe8b 100644
--- a/apps/web/src/components/settings/SnapShotSettings.browser.test.tsx
+++ b/apps/web/src/components/settings/SnapShotSettings.browser.test.tsx
@@ -186,13 +186,14 @@ it.each(["direct", "gnome-extension", "kde"] as const)(
"Record snapshot shortcut, currently Ctrl+Shift+2",
);
}
- await act(async () => userEvent.click(recorder()));
- await act(async () => userEvent.keyboard("{Control>}{Alt>}y{/Alt}{/Control}"));
+ await userEvent.click(recorder());
+ await userEvent.keyboard("{Control>}{Alt>}y{/Alt}{/Control}");
expect(bridge.checkSnapShotShortcut).toHaveBeenCalledOnce();
- expect(container.textContent).toContain("Ready to save.");
- expect(recorder().getAttribute("aria-label")).toBe(
- "Record snapshot shortcut, currently Ctrl+Alt+Y",
- );
+ // The status and label update only after the awaited shortcut check resolves.
+ await expect.poll(() => container.textContent).toContain("Ready to save.");
+ await expect
+ .poll(() => recorder().getAttribute("aria-label"))
+ .toBe("Record snapshot shortcut, currently Ctrl+Alt+Y");
await click("Save");
expect(settingsStore.update).toHaveBeenCalledWith({
snapShotShortcut: expect.objectContaining({ key: "y", modKey: true, altKey: true }),
@@ -233,9 +234,9 @@ it("keeps the approved desktop shortcut when recording is cancelled in setup", a
expect(recorder().getAttribute("aria-label")).toBe(
"Record snapshot shortcut, currently Ctrl+Alt+8",
);
- await act(async () => userEvent.click(recorder()));
+ await userEvent.click(recorder());
expect(recorder().textContent).toBe("Press shortcut…");
- await act(async () => userEvent.keyboard("{Escape}"));
+ await userEvent.keyboard("{Escape}");
expect(dialog()).not.toBeNull();
expect(recorder().getAttribute("aria-label")).toBe(
"Record snapshot shortcut, currently Ctrl+Alt+8",
@@ -273,7 +274,7 @@ it("keeps older portal shortcuts editable without offering unsupported permissio
const { button, recorder } = screen;
expect(button("Shortcut permissions")).toBeNull();
expect(bridge.setupSnapShot).not.toHaveBeenCalled();
- await act(async () => userEvent.click(recorder()));
+ await userEvent.click(recorder());
expect(recorder().textContent).toBe("Press shortcut…");
});
diff --git a/apps/web/src/components/settings/useSnapShotShortcutRecorder.browser.test.tsx b/apps/web/src/components/settings/useSnapShotShortcutRecorder.browser.test.tsx
index b463ed296d6..bd2a3a54337 100644
--- a/apps/web/src/components/settings/useSnapShotShortcutRecorder.browser.test.tsx
+++ b/apps/web/src/components/settings/useSnapShotShortcutRecorder.browser.test.tsx
@@ -1,6 +1,5 @@
import { act, render } from "../../../test/render";
import { DEFAULT_CLIENT_SETTINGS } from "@t3tools/contracts";
-import { useEffect } from "react";
import { userEvent } from "vite-plus/test/browser";
import { expect, it, vi } from "vite-plus/test";
@@ -22,7 +21,6 @@ function deferred<T>() {
const recorded = vi.fn();
const error = vi.fn();
-let recording = false;
function Recorder(props: { allowModifierPairs?: boolean; shortcutLabel?: string }) {
const recorder = useSnapShotShortcutRecorder({
@@ -32,9 +30,6 @@ function Recorder(props: { allowModifierPairs?: boolean; shortcutLabel?: string
onRecord: recorded,
onError: error,
});
- useEffect(() => {
- recording = recorder.recording;
- });
return recorder.input;
}
@@ -42,22 +37,25 @@ function setup() {
suppress.mockReset().mockResolvedValue(undefined);
recorded.mockReset();
error.mockReset();
- recording = false;
}
async function renderRecorder(props: Parameters<typeof Recorder>[0] = {}) {
const screen = await render(<Recorder {...props} />);
const button = () =>
screen.container.querySelector<HTMLButtonElement>("[data-keybinding-capture]")!;
+ // aria-pressed mirrors the hook's recording state, which flips once suppression resolves.
+ const expectRecording = (recording: boolean) =>
+ expect.element(screen.getByRole("button")).toHaveAttribute("aria-pressed", String(recording));
return {
...screen,
button,
+ expectRecording,
async start() {
- await act(() => userEvent.click(button()));
- expect(recording).toBe(true);
+ await userEvent.click(button());
+ await expectRecording(true);
},
};
}
-const press = (keys: string) => act(async () => userEvent.keyboard(keys));
+const press = (keys: string) => userEvent.keyboard(keys);
it("suppresses capture while recording and uses the physical key for shifted digits", async () => {
setup();
@@ -77,7 +75,7 @@ it("suppresses capture while recording and uses the physical key for shifted dig
shiftKey: true,
});
expect(suppress).toHaveBeenLastCalledWith(false);
- expect(recording).toBe(false);
+ await screen.expectRecording(false);
});
it("lets users replace an unrecognized desktop label without displaying guessed keys", async () => {
@@ -88,7 +86,7 @@ it("lets users replace an unrecognized desktop label without displaying guessed
const { button } = screen;
expect(button().textContent).toBe("Change shortcut");
expect(button().getAttribute("aria-label")).toBe("Change snapshot shortcut");
- await act(async () => userEvent.click(button()));
+ await userEvent.click(button());
expect(button().textContent).toBe("Press shortcut…");
await press("{Control>}{Shift>}2{/Shift}{/Control}");
expect(recorded).toHaveBeenCalledWith(
@@ -124,7 +122,7 @@ it.each(["Escape", "blur", "unmount"])("cancels on %s without selecting keys", a
else await screen.unmount();
expect(suppress).toHaveBeenLastCalledWith(false);
expect(recorded).not.toHaveBeenCalled();
- if (cancel !== "unmount") expect(recording).toBe(false);
+ if (cancel !== "unmount") await screen.expectRecording(false);
});
it("ignores late suppression acknowledgements after cancellation", async () => {
@@ -134,10 +132,10 @@ it("ignores late suppression acknowledgements after cancellation", async () => {
suppress.mockImplementation((enabled) => (enabled ? pending.promise : Promise.resolve()));
await using screen = await renderRecorder();
const { button } = screen;
- await act(async () => userEvent.click(button()));
+ await userEvent.click(button());
await act(async () => button().blur());
await act(async () => pending.resolve());
- expect(recording).toBe(false);
+ await screen.expectRecording(false);
expect(suppress).toHaveBeenLastCalledWith(false);
expect(recorded).not.toHaveBeenCalled();
});
@@ -148,8 +146,8 @@ it("reports suppression failures instead of arming the recorder", async () => {
suppress.mockRejectedValue(new Error("Couldn't pause capture"));
await using screen = await renderRecorder();
const { button } = screen;
- await act(async () => userEvent.click(button()));
- expect(recording).toBe(false);
+ await userEvent.click(button());
+ await screen.expectRecording(false);
expect(error).toHaveBeenCalledWith("Couldn't pause capture");
});
@@ -162,7 +160,7 @@ it("does not record Tab, unmodified keys, or modifier keys on their own", async
await press("y");
await press("{Control>}{/Control}");
expect(recorded).not.toHaveBeenCalled();
- expect(recording).toBe(true);
+ await screen.expectRecording(true);
await press("{Tab}");
expect(document.activeElement).not.toBe(button());
});
@@ -176,7 +174,7 @@ it("rejects modifier pairs on Wayland but accepts the next key chord", async ()
await press("{ShiftLeft>}{ShiftRight>}{/ShiftRight}{/ShiftLeft}");
expect(recorded).not.toHaveBeenCalled();
expect(error).toHaveBeenCalledWith(expect.stringContaining("Add a letter, number"));
- expect(recording).toBe(true);
+ await screen.expectRecording(true);
await press("{Control>}{Alt>}y{/Alt}{/Control}");
expect(recorded).toHaveBeenCalledOnce();
});
diff --git a/apps/web/src/components/usage/UsageLimitsPooled.browser.test.tsx b/apps/web/src/components/usage/UsageLimitsPooled.browser.test.tsx
index a70900c189d..b5b6f034151 100644
--- a/apps/web/src/components/usage/UsageLimitsPooled.browser.test.tsx
+++ b/apps/web/src/components/usage/UsageLimitsPooled.browser.test.tsx
@@ -81,7 +81,7 @@ async function click(label: string) {
(node) => node.textContent === label || node.getAttribute("aria-label")?.startsWith(label),
);
expect(button).toBeDefined();
- await act(() => userEvent.click(button!));
+ await userEvent.click(button!);
}
/**
@@ -225,24 +225,24 @@ it("moves the one limit popover between windows on hover", async () => {
const session = segment("Alpha: 60%");
const weekly = segment("Alpha: 68%");
- await act(() => userEvent.click(session));
+ await userEvent.click(session);
await expect.poll(popups).toEqual([expect.stringContaining("Left60%")]);
- await act(() => userEvent.hover(weekly));
+ await userEvent.hover(weekly);
await expect.poll(popups).toEqual([expect.stringContaining("Left68%")]);
// Weekly's popover now sits over the middle of the Session bar; come back in at its edge.
- await act(() => userEvent.hover(session, { position: { x: 4, y: 4 } }));
+ await userEvent.hover(session, { position: { x: 4, y: 4 } });
await expect.poll(popups).toEqual([expect.stringContaining("Left60%")]);
await expectDismissedInPlace(() =>
act(() => screen.rerender(<UsageLimitsPooled presentations={new Map()} now={0} />)),
);
- await act(() => userEvent.hover(container, { position: { x: 4, y: 4 } }));
+ await userEvent.hover(container, { position: { x: 4, y: 4 } });
await act(() => screen.rerender(<UsageLimitsPooled presentations={twoWindows} now={0} />));
await expect.poll(popups).toEqual([]);
- await act(() => userEvent.click(segment("Alpha: 60%")));
+ await userEvent.click(segment("Alpha: 60%"));
await expect.poll(popups).toEqual([expect.stringContaining("Left60%")]);
});
diff --git a/apps/web/src/composer-list-split.browser.test.ts b/apps/web/src/composer-list-split.browser.test.ts
index ed672464c7c..5201c11203c 100644
--- a/apps/web/src/composer-list-split.browser.test.ts
+++ b/apps/web/src/composer-list-split.browser.test.ts
@@ -2,7 +2,7 @@ import { Editor } from "@tiptap/core";
import { TaskList } from "@tiptap/extension-task-list";
import { TextSelection } from "@tiptap/pm/state";
import StarterKit from "@tiptap/starter-kit";
-import { afterEach, describe, expect, it } from "vite-plus/test";
+import { describe, expect, it } from "vite-plus/test";
import {
backspaceAcrossList,
@@ -19,13 +19,8 @@ import {
} from "./composer-rich-text-doc";
// ProseMirror's DOM observer can flush on a timer after a test ends, which
-// throws once its DOM is gone, so every editor is destroyed after its test.
-const editors: Editor[] = [];
-afterEach(() => {
- for (const editor of editors.splice(0)) editor.destroy();
-});
-
-function makeEditor(value: string) {
+// throws once its DOM is gone, so every editor is acquired with `using`.
+function makeEditor(value: string): Editor & Disposable {
const editor = new Editor({
extensions: [
StarterKit.configure({
@@ -47,12 +42,11 @@ function makeEditor(value: string) {
],
content: buildDocJson(value, (name) => ({ label: name, description: null })),
});
- editors.push(editor);
- return editor;
+ return Object.assign(editor, { [Symbol.dispose]: () => editor.destroy() });
}
function splitLastItem(value: string, type: "listItem" | "taskItem", overrides: object) {
- const editor = makeEditor(value);
+ using editor = makeEditor(value);
editor.view.dispatch(editor.state.tr.setSelection(TextSelection.atEnd(editor.state.doc)));
editor.commands.splitListItem(type, overrides);
editor.view.dispatch(editor.state.tr.insertText("b"));
@@ -88,7 +82,8 @@ function placeCaret(editor: Editor, text: string, offset = 0) {
function storedDraft(editor: Editor) {
const stored = serializeEditorDoc(editor.state.doc).value;
- expect(makeEditor(stored).state.doc.toString()).toBe(editor.state.doc.toString());
+ using reloaded = makeEditor(stored);
+ expect(reloaded.state.doc.toString()).toBe(editor.state.doc.toString());
return stored;
}
@@ -102,7 +97,7 @@ describe("Shift+Enter twice on an item", () => {
["- [ ] a\n - [ ] x", "- [ ] a\n - [ ] x\n- [ ] b"],
["- [x] a\n - [ ] x\n- [ ] c", "- [x] a\n - [ ] x\n- [ ] b\n- [ ] c"],
])("after x in %j writes %j", (value, expected) => {
- const editor = makeEditor(value);
+ using editor = makeEditor(value);
let caret = -1;
editor.state.doc.descendants((node, pos) => {
if (node.isText && node.text === "x") caret = pos + 1;
@@ -115,7 +110,8 @@ describe("Shift+Enter twice on an item", () => {
editor.view.dispatch(editor.state.tr.insertText("b"));
const stored = serializeEditorDoc(editor.state.doc).value;
expect(stored).toBe(expected);
- expect(makeEditor(stored).state.doc.toString()).toBe(editor.state.doc.toString());
+ using reloaded = makeEditor(stored);
+ expect(reloaded.state.doc.toString()).toBe(editor.state.doc.toString());
});
});
@@ -125,7 +121,7 @@ describe("Shift+Enter in the middle of an ordered list", () => {
["1) a\n2) x\n3) c", "1) a\n2) x\n3) b\n4) c"],
["1. a\n 1. x\n 2. c\n2. d", "1. a\n 1. x\n 2. b\n 3. c\n2. d"],
])("after x in %j writes %j", (value, expected) => {
- const editor = makeEditor(value);
+ using editor = makeEditor(value);
placeCaret(editor, "x", 1);
expect(splitOrLiftListItem(editor)).toBe(true);
editor.view.dispatch(editor.state.tr.insertText("b"));
@@ -135,7 +131,7 @@ describe("Shift+Enter in the middle of an ordered list", () => {
describe("Shift+Enter on an empty task under a bullet", () => {
it.each(["- a\n - [ ] x", "- [ ] a\n - x"])("in %j keeps the draft honest", (value) => {
- const editor = makeEditor(value);
+ using editor = makeEditor(value);
placeCaret(editor, "x", 1);
splitOrLiftListItem(editor);
splitOrLiftListItem(editor);
@@ -153,7 +149,7 @@ describe("Backspace at the start of a line", () => {
["- a\n - x\nb", "b", "- a\n - xb"],
["1. a\nb", "b", "1. ab"],
])("in %j at %s writes %j", (value, at, expected) => {
- const editor = makeEditor(value);
+ using editor = makeEditor(value);
placeCaret(editor, at);
expect(backspaceAcrossList(editor)).toBe(true);
expect(storedDraft(editor)).toBe(expected);
@@ -163,7 +159,7 @@ describe("Backspace at the start of a line", () => {
["- a\n```\nl1\nl2\n```", "- a\nl1\nl2"],
["p\n```ts\nl1\n```", "p\nl1"],
])("removes the fence of %j rather than joining its code up", (value, expected) => {
- const editor = makeEditor(value);
+ using editor = makeEditor(value);
placeCaret(editor, "l1");
editor.commands.keyboardShortcut("Backspace");
expect(storedDraft(editor)).toBe(expected);
@@ -176,14 +172,14 @@ describe("Delete at the end of a line", () => {
["- a\n - x\n- c", "- ax\n- c"],
["- a\n\nb", "- a\nb"],
])("in %j writes %j", (value, expected) => {
- const editor = makeEditor(value);
+ using editor = makeEditor(value);
placeCaret(editor, "a", 1);
expect(deleteAcrossList(editor)).toBe(true);
expect(storedDraft(editor)).toBe(expected);
});
it.each(["- a\n```\nl1\n```", "a\n```\nl1\n```"])("leaves the fence in %j alone", (value) => {
- const editor = makeEditor(value);
+ using editor = makeEditor(value);
placeCaret(editor, "a", 1);
editor.commands.keyboardShortcut("Delete");
expect(storedDraft(editor)).toBe(value);
@@ -192,7 +188,7 @@ describe("Delete at the end of a line", () => {
describe("blocks that a list item or quote cannot hold", () => {
it("puts lines pasted at the end of an item after the list", () => {
- const editor = makeEditor("- a");
+ using editor = makeEditor("- a");
editor.view.dispatch(editor.state.tr.setSelection(TextSelection.atEnd(editor.state.doc)));
const lines = buildTiptapContent("one\ntwo", (name) => ({ label: name, description: null }));
editor.commands.insertContent(lines);
@@ -200,7 +196,7 @@ describe("blocks that a list item or quote cannot hold", () => {
});
it("will not make a task list inside a quote", () => {
- const editor = makeEditor("> q");
+ using editor = makeEditor("> q");
placeCaret(editor, "q");
expect(editor.commands.wrapInList("taskList")).toBe(false);
expect(storedDraft(editor)).toBe("> q");
@@ -216,7 +212,7 @@ describe("[ ] typed at the start of a bullet item", () => {
["- [ ]x\n - y", "- [ ] x\n - y"],
["- [ ]x", "- [ ] x"],
])("makes the item in %j a task where it stands", (value, expected) => {
- const editor = makeEditor(value);
+ using editor = makeEditor(value);
placeCaret(editor, "[ ]x");
const from = editor.state.selection.from;
editor.view.dispatch(
@@ -233,7 +229,7 @@ describe("[ ] typed at the start of a bullet item", () => {
describe("a rule at the end of the draft", () => {
it("keeps an empty line after it to type on", () => {
- const editor = makeEditor("a\n---");
+ using editor = makeEditor("a\n---");
editor.view.dispatch(
editor.state.tr.delete(editor.state.doc.content.size - 2, editor.state.doc.content.size),
);
diff --git a/apps/web/src/lib/editableFocus.browser.test.ts b/apps/web/src/lib/editableFocus.browser.test.ts
index ea09ef792aa..9491ffeeacc 100644
--- a/apps/web/src/lib/editableFocus.browser.test.ts
+++ b/apps/web/src/lib/editableFocus.browser.test.ts
@@ -1,11 +1,7 @@
-import { afterEach, describe, expect, it } from "vite-plus/test";
+import { describe, expect, it } from "vite-plus/test";
import { isEditableFocused } from "./editableFocus";
-afterEach(() => {
- document.body.replaceChildren();
-});
-
describe("isEditableFocused", () => {
it("sees a text field focused inside an open shadow root", () => {
// A key event from a shadow input is retargeted to its host, so the host is
@@ -14,6 +10,7 @@ describe("isEditableFocused", () => {
const input = document.createElement("input");
host.attachShadow({ mode: "open" }).append(input);
document.body.append(host);
+ using _host = { [Symbol.dispose]: () => host.remove() };
expect(isEditableFocused(host)).toBe(false);
input.focus();
diff --git a/apps/web/src/shortcutModifierState.browser.test.ts b/apps/web/src/shortcutModifierState.browser.test.ts
index e017369ff4a..575f590747c 100644
--- a/apps/web/src/shortcutModifierState.browser.test.ts
+++ b/apps/web/src/shortcutModifierState.browser.test.ts
@@ -1,6 +1,7 @@
-import { act, createElement } from "react";
-import { createRoot, type Root } from "react-dom/client";
-import { afterEach, beforeEach, describe, expect, it, vi } from "vite-plus/test";
+import { createElement } from "react";
+import { describe, expect, it, vi } from "vite-plus/test";
+
+import { act, render } from "../test/render";
import {
areShortcutModifierStatesEqual,
@@ -17,33 +18,16 @@ const emptyState = (): ShortcutModifierState => ({
});
describe("useShortcutModifierState", () => {
- 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);
- });
-
- afterEach(async () => {
- await act(async () => root.unmount());
- container.remove();
- vi.unstubAllGlobals();
- });
-
it.each(["keyup", "paste", "blur"] as const)(
"does not render for unchanged modifiers after %s resets the state",
async (reset) => {
- const render = vi.fn();
+ const onRender = vi.fn();
function Consumer() {
- render(useShortcutModifierState());
+ onRender(useShortcutModifierState());
return null;
}
- await act(async () => {
- root.render(createElement(Consumer));
- });
+ // The test counts the hook's renders, and the hook never reads a route.
+ await using _screen = await render(createElement(Consumer), { router: false });
const press = async (type: "keydown" | "keyup", key: string, shiftKey = false) => {
await act(async () => {
window.dispatchEvent(new KeyboardEvent(type, { key, shiftKey }));
@@ -51,7 +35,7 @@ describe("useShortcutModifierState", () => {
};
await press("keydown", "Shift", true);
- expect(render).toHaveBeenLastCalledWith({ ...emptyState(), shiftKey: true });
+ expect(onRender).toHaveBeenLastCalledWith({ ...emptyState(), shiftKey: true });
if (reset === "keyup") {
await press("keyup", "Shift");
} else {
@@ -59,8 +43,8 @@ describe("useShortcutModifierState", () => {
window.dispatchEvent(new Event(reset));
});
}
- expect(render).toHaveBeenLastCalledWith(emptyState());
- render.mockClear();
+ expect(onRender).toHaveBeenLastCalledWith(emptyState());
+ onRender.mockClear();
for (const key of "typing") {
await press("keydown", key);
@@ -70,9 +54,9 @@ describe("useShortcutModifierState", () => {
window.dispatchEvent(new Event("paste"));
window.dispatchEvent(new Event("blur"));
});
- expect(render).not.toHaveBeenCalled();
+ expect(onRender).not.toHaveBeenCalled();
await press("keydown", "Shift", true);
- expect(render).toHaveBeenCalledExactlyOnceWith({ ...emptyState(), shiftKey: true });
+ expect(onRender).toHaveBeenCalledExactlyOnceWith({ ...emptyState(), shiftKey: true });
},
);
});
diff --git a/oxlint-plugin-t3code/rules/require-disposable-render.test.ts b/oxlint-plugin-t3code/rules/require-disposable-render.test.ts
index bc69f362c01..92dbb5c21bf 100644
--- a/oxlint-plugin-t3code/rules/require-disposable-render.test.ts
+++ b/oxlint-plugin-t3code/rules/require-disposable-render.test.ts
@@ -9,6 +9,9 @@ const unitTest = createOxlintRuleHarness("t3code/require-disposable-render", {
filename: "widget.test.tsx",
});
+const reportsInputInAct = (output: string) =>
+ assert.match(output, /Do not wrap real input \(userEvent or a locator's click\/fill\) in act/);
+
describe("t3code/require-disposable-render", () => {
browserTest.valid(
"allows the disposable helper",
@@ -19,6 +22,7 @@ describe("t3code/require-disposable-render", () => {
" await using screen = await render(null);",
" await act(() => screen.rerender(null));",
' await userEvent.click(screen.getByRole("button"));',
+ " await act(() => store.setState({ open: true }));",
"});",
].join("\n"),
);
@@ -44,13 +48,99 @@ describe("t3code/require-disposable-render", () => {
"rejects userEvent wrapped in act from react",
[
'import { act } from "react";',
+ 'import { userEvent } from "vite-plus/test/browser";',
'it("clicks", async () => {',
" await act(async () => {",
" await userEvent.click(document.body);",
" });",
"});",
].join("\n"),
- (output) => assert.match(output, /Do not wrap userEvent in React's act/),
+ reportsInputInAct,
+ );
+ browserTest.invalid(
+ "rejects userEvent wrapped in the render helper's act",
+ [
+ 'import { act } from "../../test/render";',
+ 'import { userEvent } from "vite-plus/test/browser";',
+ 'it("types", async () => {',
+ ' await act(() => userEvent.type(document.body, "a"));',
+ "});",
+ ].join("\n"),
+ reportsInputInAct,
+ );
+ browserTest.invalid(
+ "rejects userEvent wrapped in a renamed render helper act",
+ [
+ 'import { act as flush } from "../test/render.tsx";',
+ 'import { userEvent } from "vite-plus/test/browser";',
+ 'it("clicks", async () => {',
+ " await flush(async () => {",
+ " await userEvent.click(document.body);",
+ " });",
+ "});",
+ ].join("\n"),
+ reportsInputInAct,
+ );
+ browserTest.invalid(
+ "rejects a renamed userEvent wrapped in act",
+ [
+ 'import { act } from "../test/render";',
+ 'import { userEvent as ue } from "vite-plus/test/browser";',
+ 'it("clicks", async () => {',
+ " await act(() => ue.click(document.body));",
+ "});",
+ ].join("\n"),
+ reportsInputInAct,
+ );
+ browserTest.invalid(
+ "rejects a locator click wrapped in act",
+ [
+ 'import { act } from "../test/render";',
+ 'import { page } from "vite-plus/test/browser";',
+ 'it("clicks", async () => {',
+ ' await act(async () => page.getByRole("button", { name: "Save" }).nth(0).click());',
+ "});",
+ ].join("\n"),
+ reportsInputInAct,
+ );
+ browserTest.invalid(
+ "rejects React.act from a namespace import",
+ [
+ 'import * as React from "react";',
+ 'it("renders", async () => {',
+ " await React.act(async () => {});",
+ "});",
+ ].join("\n"),
+ (output) => assert.match(output, /import `act` from there/),
+ );
+ browserTest.invalid(
+ "rejects userEvent wrapped in React.act",
+ [
+ 'import * as React from "react";',
+ 'import { userEvent } from "vite-plus/test/browser";',
+ 'it("clicks", async () => {',
+ " await React.act(() => userEvent.click(document.body));",
+ "});",
+ ].join("\n"),
+ reportsInputInAct,
+ );
+ browserTest.valid(
+ "allows act around a DOM click and userEvent in a function act only defines",
+ [
+ 'import { act } from "../test/render";',
+ 'import { page, userEvent } from "vite-plus/test/browser";',
+ 'it("clicks", async () => {',
+ ' await act(async () => page.getByRole("button").element().click());',
+ " await act(async () => {",
+ " const later = () => userEvent.click(document.body);",
+ " store.setState({ later });",
+ " });",
+ "});",
+ ].join("\n"),
+ );
+ browserTest.invalid(
+ "rejects lifecycle hooks through a test runner namespace",
+ ['import * as vt from "vitest";', "vt.beforeEach(() => {});"].join("\n"),
);
browserTest.invalid(
"rejects importing lifecycle hooks from the test runner",
diff --git a/oxlint-plugin-t3code/rules/require-disposable-render.ts b/oxlint-plugin-t3code/rules/require-disposable-render.ts
index fe8bd4c80de..f27420276f8 100644
--- a/oxlint-plugin-t3code/rules/require-disposable-render.ts
+++ b/oxlint-plugin-t3code/rules/require-disposable-render.ts
@@ -8,14 +8,31 @@ const LIFECYCLE_HOOKS = new Set(["afterAll", "afterEach", "beforeAll", "beforeEa
const TEST_RUNNERS = new Set(["@effect/vitest", "vite-plus/test", "vitest"]);
const REACT_ACT_EXPORTS = new Set(["act", "unstable_act"]);
const ACT_ENVIRONMENT = "IS_REACT_ACT_ENVIRONMENT";
+const RENDER_HELPER = /(?:^|\/)test\/render(?:\.tsx)?$/u;
+const LOCATOR_QUERY = /^getBy/u;
+// Locator methods that dispatch real input through the browser provider.
+const LOCATOR_INPUT = new Set([
+ "clear",
+ "click",
+ "dblClick",
+ "dropTo",
+ "fill",
+ "hover",
+ "selectOptions",
+ "tripleClick",
+ "unhover",
+ "upload",
+]);
+// These leave the locator for a DOM element, whose click() is synthetic and fine inside act.
+const LOCATOR_EXITS = new Set(["element", "elements", "query"]);
const HELPER = "Render with `await using screen = await render(...)` from apps/web/test/render.tsx";
const MESSAGES = {
reactDomClient: `${HELPER}; it owns the React root and unmounts it on dispose.`,
reactAct: `${HELPER} and import \`act\` from there; it enables React's act environment only while act runs.`,
actEnvironment: `${HELPER}; its act() sets ${ACT_ENVIRONMENT} for exactly as long as it runs.`,
- actAroundUserEvent:
- "Do not wrap userEvent in React's act; real input is not an act scope. Await the userEvent call directly.",
+ actAroundInput:
+ "Do not wrap real input (userEvent or a locator's click/fill) in act; the browser runner flushes React updates after real input. Await the input directly.",
lifecycleHook:
"Browser tests acquire what they need with `using`/`await using` instead of lifecycle hooks, so nothing outlives the test that created it.",
};
@@ -23,6 +40,32 @@ const MESSAGES = {
const stringValue = (node: ESTree.Node | null | undefined) =>
node?.type === "Literal" && typeof node.value === "string" ? node.value : undefined;
+const importedName = (specifier: ESTree.ImportSpecifier) =>
+ specifier.imported.type === "Identifier" ? specifier.imported.name : specifier.imported.value;
+
+const isFunction = (node: ESTree.Node) =>
+ node.type === "ArrowFunctionExpression" ||
+ node.type === "FunctionExpression" ||
+ node.type === "FunctionDeclaration";
+
+// Walks a.b().c().d back to its root, reporting whether a getBy* query built a locator on the way
+// without leaving it through element()/query().
+const isLocatorChain = (node: ESTree.Node): boolean => {
+ let sawQuery = false;
+ for (let current: ESTree.Node | undefined = node; current;) {
+ if (current.type === "CallExpression") {
+ current = current.callee;
+ continue;
+ }
+ if (current.type !== "MemberExpression") break;
+ const name = Option.getOrUndefined(getPropertyName(current.property));
+ if (name !== undefined && LOCATOR_EXITS.has(name)) return false;
+ if (name !== undefined && LOCATOR_QUERY.test(name)) sawQuery = true;
+ current = current.object;
+ }
+ return sawQuery;
+};
+
const namesActEnvironment = (node: unknown) => {
const target = unwrapExpression(node);
if (Option.isNone(target)) return false;
@@ -44,49 +87,94 @@ export default defineRule({
},
create(context) {
const isBrowserTest = BROWSER_TEST_FILE.test(context.filename);
- const reactActNames = new Set<string>();
+ // Local names bound to React's act or the render helper's act.
+ const actNames = new Set<string>();
+ const reactNamespaces = new Set<string>();
+ const runnerNamespaces = new Set<string>();
+ const userEventNames = new Set<string>();
+
+ const namespaceMember = (node: ESTree.Node, namespaces: ReadonlySet<string>) =>
+ node.type === "MemberExpression" &&
+ node.object.type === "Identifier" &&
+ namespaces.has(node.object.name)
+ ? Option.getOrUndefined(getPropertyName(node.property))
+ : undefined;
+
+ const isReactNamespaceAct = (callee: ESTree.Node) => {
+ const member = namespaceMember(callee, reactNamespaces);
+ return member !== undefined && REACT_ACT_EXPORTS.has(member);
+ };
- const isInsideReactAct = (node: ESTree.Node) => {
+ const isActCall = (node: ESTree.Node) =>
+ node.type === "CallExpression" &&
+ ((node.callee.type === "Identifier" && actNames.has(node.callee.name)) ||
+ isReactNamespaceAct(node.callee));
+
+ // A function defined inside act but not passed straight to a call may run after act settles.
+ const isInsideAct = (node: ESTree.Node) => {
for (let current = node.parent; current; current = current.parent) {
+ if (isActCall(current)) return true;
if (
- current.type === "CallExpression" &&
- current.callee.type === "Identifier" &&
- reactActNames.has(current.callee.name)
+ isFunction(current) &&
+ !(
+ current.parent?.type === "CallExpression" &&
+ (current.parent.arguments as ReadonlyArray<ESTree.Node>).includes(current)
+ )
) {
- return true;
+ return false;
}
}
return false;
};
+ const isRealInput = (callee: ESTree.MemberExpression) => {
+ if (callee.object.type === "Identifier" && userEventNames.has(callee.object.name)) {
+ return true;
+ }
+ const method = Option.getOrUndefined(getPropertyName(callee.property));
+ return method !== undefined && LOCATOR_INPUT.has(method) && isLocatorChain(callee.object);
+ };
+
return {
ImportDeclaration(node) {
+ for (const specifier of node.specifiers) {
+ if (specifier.type === "ImportSpecifier" && importedName(specifier) === "userEvent") {
+ userEventNames.add(specifier.local.name);
+ }
+ }
if (isBrowserTest && TEST_RUNNERS.has(node.source.value)) {
for (const specifier of node.specifiers) {
+ if (specifier.type === "ImportNamespaceSpecifier") {
+ runnerNamespaces.add(specifier.local.name);
+ continue;
+ }
if (specifier.type !== "ImportSpecifier") continue;
- const imported =
- specifier.imported.type === "Identifier"
- ? specifier.imported.name
- : specifier.imported.value;
- if (LIFECYCLE_HOOKS.has(imported)) {
+ if (LIFECYCLE_HOOKS.has(importedName(specifier))) {
context.report({ node: specifier, message: MESSAGES.lifecycleHook });
}
}
return;
}
+ if (RENDER_HELPER.test(node.source.value)) {
+ for (const specifier of node.specifiers) {
+ if (specifier.type === "ImportSpecifier" && importedName(specifier) === "act") {
+ actNames.add(specifier.local.name);
+ }
+ }
+ return;
+ }
if (node.source.value === "react-dom/client") {
context.report({ node: node.source, message: MESSAGES.reactDomClient });
return;
}
if (node.source.value !== "react") return;
for (const specifier of node.specifiers) {
- if (specifier.type !== "ImportSpecifier") continue;
- const imported =
- specifier.imported.type === "Identifier"
- ? specifier.imported.name
- : specifier.imported.value;
- if (REACT_ACT_EXPORTS.has(imported)) {
- reactActNames.add(specifier.local.name);
+ if (specifier.type !== "ImportSpecifier") {
+ reactNamespaces.add(specifier.local.name);
+ continue;
+ }
+ if (REACT_ACT_EXPORTS.has(importedName(specifier))) {
+ actNames.add(specifier.local.name);
context.report({ node: specifier, message: MESSAGES.reactAct });
}
}
@@ -102,12 +190,19 @@ export default defineRule({
if (callee.value.type === "MemberExpression") {
// vi.stubGlobal("IS_REACT_ACT_ENVIRONMENT", true) leaves the flag on for the whole test.
const method = getPropertyName(callee.value.property);
- if (
- callee.value.object.type === "Identifier" &&
- callee.value.object.name === "userEvent" &&
- isInsideReactAct(node)
- ) {
- context.report({ node, message: MESSAGES.actAroundUserEvent });
+ if (isReactNamespaceAct(callee.value)) {
+ context.report({ node: node.callee, message: MESSAGES.reactAct });
+ return;
+ }
+ if (isBrowserTest) {
+ const hook = namespaceMember(callee.value, runnerNamespaces);
+ if (hook !== undefined && LIFECYCLE_HOOKS.has(hook)) {
+ context.report({ node: node.callee, message: MESSAGES.lifecycleHook });
+ return;
+ }
+ }
+ if (isRealInput(callee.value) && isInsideAct(node)) {
+ context.report({ node, message: MESSAGES.actAroundInput });
return;
}
if (
diff --git a/vite.config.ts b/vite.config.ts
index 3c63eae544e..b6d286e307f 100644
--- a/vite.config.ts
+++ b/vite.config.ts
@@ -188,7 +188,7 @@ export default defineConfig({
rules: { "t3code/prefer-effect-fn": "off" },
},
{
- files: ["apps/web/**/*.test.tsx"],
+ files: ["apps/web/**/*.test.{ts,tsx}"],
rules: { "t3code/require-disposable-render": "error" },
},
{