The best way to control Claude Code, Codex and more from any computer or phone
test(web): migrate the last .ts browser tests and stop wrapping userEvent in act (#22424)
Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
Julius Marminge committed
Oct 20, 2026 at 11:14 UTC
f7f9e217857ecb5c25ec9164e2b490801e74b514
29 files changed
+469
-294
apps/web/src/components/ChatMarkdown.browser.test.tsx
+2
-2
@@ -1420,7 +1420,7 @@ describe("ChatMarkdown math", () => {
1420
});
1421
const [preview, after] = container.querySelectorAll("button");
1422
preview!.focus();
1423
- await act(() => userEvent.tab());
1423
+ await userEvent.tab();
1424
expect(document.activeElement).toBe(after);
1425
if (formula.includes("notACommand")) {
1426
expect(page.getByRole("button", { name: /notACommand/ }).element()).toBe(preview);
@@ -1439,7 +1439,7 @@ describe("ChatMarkdown math", () => {
1439
);
1440
const { container } = screen;
1441
container.querySelector("button")!.focus();
1442
- await act(() => userEvent.tab());
1442
+ await userEvent.tab();
1443
expect(document.activeElement).toBe(
1444
container.querySelector('[aria-label="Scroll inline equation"]'),
1445
);
apps/web/src/components/ComposerPromptEditorTiptap.input.browser.test.tsx
+1
-1
@@ -484,7 +484,7 @@ describe("composer context undo lifetime", () => {
484
const nextEditor = composer.editor();
485
expect(nextEditor).not.toBe(previousEditor);
486
expect(document.activeElement).toBe(nextEditor.view.dom);
487
- await act(async () => userEvent.keyboard("x"));
487
+ await userEvent.keyboard("x");
488
expect(composer.draft().value).toBe("xDraft B");
489
490
const button = document.createElement("button");
apps/web/src/components/ThreadStatusIndicators.subscriptions.browser.test.tsx
+3
-3
@@ -200,7 +200,7 @@ it("keeps a long PR hover list in the viewport and lets the last row be selected
200
/>
201
</div>,
202
);
203
- await act(() => userEvent.hover(screen.container.querySelector("button")!));
203
+ await userEvent.hover(screen.container.querySelector("button")!);
204
const popup = () => document.querySelector<HTMLElement>('[data-slot="tooltip-popup"]')!;
205
await expect.poll(() => popup()?.querySelectorAll("a").length).toBe(40);
206
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
212
expect(lastRow.getBoundingClientRect().top).toBeGreaterThan(
213
popup().getBoundingClientRect().bottom,
214
);
215
- await act(() => userEvent.wheel(popup(), { delta: { y: 10_000 } }));
215
+ await userEvent.wheel(popup(), { delta: { y: 10_000 } });
216
await expect
217
.poll(() => lastRow.getBoundingClientRect().bottom)
218
.toBeLessThanOrEqual(popup().getBoundingClientRect().bottom);
219
expect(lastRow.getBoundingClientRect().top).toBeGreaterThanOrEqual(
220
popup().getBoundingClientRect().top,
221
);
222
- await act(() => userEvent.click(lastRow));
222
+ await userEvent.click(lastRow);
223
expect(onOpenPullRequest).toHaveBeenCalledExactlyOnceWith(expect.anything(), lastRow.href);
224
});
apps/web/src/components/chat/ComposerBannerStack.browser.test.tsx
+2
-2
@@ -84,12 +84,12 @@ it("keeps only the usage limit attached while an active goal waits in the collap
84
"Usage limit reached",
85
);
86
87
- await act(async () => page.getByRole("button", { name: "Show other notices" }).click());
87
+ await page.getByRole("button", { name: "Show other notices" }).click();
88
await expect.element(goal).toBeVisible();
89
await expect.element(limit).toBeVisible();
90
await expect.poll(visibleBanners).toHaveLength(2);
91
92
- await act(async () => userEvent.keyboard("{Escape}"));
92
+ await userEvent.keyboard("{Escape}");
93
await expect.element(goal).not.toBeVisible();
94
await expect.element(limit).toBeVisible();
95
expect(visibleBanners()).toHaveLength(1);
apps/web/src/components/chat/ComposerStashMenu.browser.test.tsx
+2
-2
@@ -66,7 +66,7 @@ const editor = () => page.getByRole("textbox", { name: "Message" });
66
const stash = () => page.getByRole("list", { name: "Stashed prompts" });
67
const restore = (prompt: string) =>
68
page.getByRole("button", { name: `Restore stashed prompt: ${prompt}` });
69
-const press = (keys: string) => act(async () => userEvent.keyboard(keys));
69
+const press = (keys: string) => userEvent.keyboard(keys);
70
const focus = (element: Element) => act(async () => (element as HTMLElement).focus());
71
72
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
128
await press("{Escape}");
129
await expect.element(stash()).not.toBeInTheDocument();
130
131
- await act(async () => userEvent.click(page.getByRole("button", { name: "Open stash" })));
131
+ await userEvent.click(page.getByRole("button", { name: "Open stash" }));
132
await expect.element(restore("first prompt")).not.toBeInTheDocument();
133
expect(stash().element().textContent).toContain("second prompt");
134
await focus(editor().element());
apps/web/src/components/chat/MessagesTimeline.browser.test.tsx
+2
-4
@@ -215,10 +215,8 @@ describe("MessagesTimeline work rows", () => {
215
);
216
const row = screen.container.querySelector<HTMLElement>('[data-v2-item-type="file_change"]')!;
217
const press = async (target: HTMLElement) => {
218
- await act(async () => {
219
- target.focus();
220
- await userEvent.keyboard(key);
221
- });
218
+ target.focus();
219
+ await userEvent.keyboard(key);
220
};
221
expect(row.getAttribute("aria-expanded")).toBe("false");
222
await press(row);
apps/web/src/components/chat/ProviderModelPicker.browser.test.tsx
+2
-2
@@ -12,7 +12,7 @@ import { page, userEvent } from "vite-plus/test/browser";
12
13
import "~/index.css";
14
15
-import { act, render as renderUi } from "../../../test/render";
15
+import { render as renderUi } from "../../../test/render";
16
import { deriveProviderInstanceEntries } from "../../providerInstances";
17
import { ProviderModelPicker } from "./ProviderModelPicker";
18
import type { ModelEsque } from "./providerIconUtils";
@@ -85,7 +85,7 @@ function renderPicker(input: {
85
}
86
87
async function click(target: Parameters<typeof userEvent.click>[0]) {
88
- await act(async () => userEvent.click(target));
88
+ await userEvent.click(target);
89
}
90
91
async function openLegacyPicker(activeModel: string) {
apps/web/src/components/chat/QueuedRunsControl.browser.test.tsx
+2
-4
@@ -30,7 +30,7 @@ vi.mock(import("../../assets/assetUrls"), async (importOriginal) => ({
30
resources.map((resource) => `https://assets.test/${resource.attachmentId}`)) as never,
31
}));
32
33
-import { act, render as renderUi } from "../../../test/render";
33
+import { render as renderUi } from "../../../test/render";
34
import { QueuedRunsControl } from "./QueuedRunsControl";
35
36
function setup() {
@@ -204,9 +204,7 @@ it("previews assistant quotes as readable text and preserves the citation when e
204
.element(page.getByText(`${quotedText} Why per worktree?`, { exact: true }))
205
.toBeVisible();
206
207
- await act(async () => {
208
- await page.getByRole("button", { name: "Edit queued message", exact: true }).nth(1).click();
209
- });
207
+ await page.getByRole("button", { name: "Edit queued message", exact: true }).nth(1).click();
208
expect(onEditQueuedRun).toHaveBeenCalledExactlyOnceWith(
209
expect.objectContaining({ text: quoteAndText }),
210
);
apps/web/src/components/chat/ThreadErrorBanner.browser.test.tsx
+3
-3
@@ -1,4 +1,4 @@
1
-import { act, render as renderUi } from "../../../test/render";
1
+import { render as renderUi } from "../../../test/render";
2
import "../../index.css";
3
4
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
15
await expect.element(page.getByText("Turn failed", { exact: true })).toBeVisible();
16
expect(container.textContent).not.toContain("unsupported_value");
17
18
- await act(async () => page.getByRole("button", { name: "Show full error" }).click());
18
+ await page.getByRole("button", { name: "Show full error" }).click();
19
20
const diagnostics = page.getByText(error, { exact: true });
21
await expect.element(diagnostics).toBeVisible();
22
expect(diagnostics.element().textContent).toBe(error);
23
24
- await act(async () => page.getByRole("button", { name: "Show less" }).click());
24
+ await page.getByRole("button", { name: "Show less" }).click();
25
26
await expect.element(page.getByText("Turn failed", { exact: true })).toBeVisible();
27
expect(container.textContent).not.toContain("unsupported_value");
apps/web/src/components/chat/composerFocusRedirect.browser.test.ts
+7
-6
@@ -1,4 +1,4 @@
1
-import { afterEach, describe, expect, it } from "vite-plus/test";
1
+import { describe, expect, it } from "vite-plus/test";
2
3
import { shouldTypeToFocusComposer } from "./composerFocusRedirect";
4
@@ -15,14 +15,15 @@ function typeOn(target: Element, key: string): boolean {
15
return redirected;
16
}
17
18
-afterEach(() => {
19
- document.body.replaceChildren();
20
-});
18
+function attach(element: Element): Disposable {
19
+ document.body.append(element);
20
+ return { [Symbol.dispose]: () => element.remove() };
21
+}
22
23
describe("shouldTypeToFocusComposer", () => {
24
it("sends letters typed on the chat to the composer", () => {
25
const chat = document.createElement("div");
25
- document.body.append(chat);
26
+ using _chat = attach(chat);
27
28
expect(typeOn(chat, "a")).toBe(true);
29
});
@@ -31,7 +32,7 @@ describe("shouldTypeToFocusComposer", () => {
32
const deviceScreen = document.createElement("div");
33
deviceScreen.setAttribute("role", "application");
34
deviceScreen.tabIndex = 0;
34
- document.body.append(deviceScreen);
35
+ using _deviceScreen = attach(deviceScreen);
36
37
expect(typeOn(deviceScreen, "a")).toBe(false);
38
});
apps/web/src/components/chat/threadFindPosition.browser.test.ts
+8
-12
@@ -1,15 +1,7 @@
1
-import { afterEach, beforeEach, describe, expect, it, vi } from "vite-plus/test";
1
+import { describe, expect, it, vi } from "vite-plus/test";
2
import { readThreadFindPosition } from "./threadFindPosition";
3
4
-afterEach(() => vi.restoreAllMocks());
5
-beforeEach(() => {
6
- Object.defineProperty(Range.prototype, "getBoundingClientRect", {
7
- configurable: true,
8
- writable: true,
9
- value: () => new DOMRect(),
10
- });
11
-});
12
-
4
+// The container stays detached, so unmocked ranges measure as an empty rect.
5
function viewport(text = "COD4 COD4") {
6
const container = document.createElement("div");
7
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") {
19
describe("reading position for find", () => {
20
it("skips earlier rows and occurrences above the viewport within the current message", () => {
21
const container = viewport();
30
- vi.spyOn(Range.prototype, "getBoundingClientRect").mockImplementation(function (this: Range) {
22
+ using _ranges = vi.spyOn(Range.prototype, "getBoundingClientRect").mockImplementation(function (
23
+ this: Range,
24
+ ) {
25
return new DOMRect(0, this.startOffset === 0 ? 60 : 160, 40, 20);
26
});
27
expect(readThreadFindPosition(container, "COD4", (id) => id, 100)).toEqual({
@@ -38,7 +32,9 @@ describe("reading position for find", () => {
32
33
it("starts after the current message when all its occurrences are above the viewport", () => {
34
const container = viewport();
41
- vi.spyOn(Range.prototype, "getBoundingClientRect").mockReturnValue(new DOMRect(0, 60, 40, 20));
35
+ using _ranges = vi
36
+ .spyOn(Range.prototype, "getBoundingClientRect")
37
+ .mockReturnValue(new DOMRect(0, 60, 40, 20));
38
expect(readThreadFindPosition(container, "COD4", (id) => id, 100)).toEqual({
39
entryId: "reading",
40
occurrence: 2,
apps/web/src/components/desktop/SnapShotCoordinator.browser.test.ts
+51
-34
@@ -9,9 +9,10 @@ import {
9
ProjectId,
10
ThreadId,
11
} from "@t3tools/contracts";
12
-import { act, createElement } from "react";
13
-import { createRoot, type Root } from "react-dom/client";
14
-import { afterEach, beforeEach, describe, expect, it, vi } from "vite-plus/test";
12
+import { createElement } from "react";
13
+import { describe, expect, it, vi } from "vite-plus/test";
14
+
15
+import { act, fakeTimers, render, type Screen } from "../../../test/render";
16
17
import { DraftId, useComposerDraftStore } from "../../composerDraftStore";
18
import type { DesktopSnapShotBridge } from "../../lib/desktopSnapShot";
@@ -66,7 +67,8 @@ const storage = vi.hoisted(() => {
67
const environmentId = EnvironmentId.make("snap-shot-environment");
68
const projectRef = scopeProjectRef(environmentId, ProjectId.make("snap-shot-project"));
69
69
-beforeEach(() => {
70
+// Tests stub globals and spy on module exports freely; disposing restores all of them.
71
+function setup(): Disposable {
72
storage.clear();
73
vi.stubGlobal("localStorage", storage);
74
useComposerDraftStore.setState({
@@ -76,17 +78,18 @@ beforeEach(() => {
78
stickyModelSelectionByProvider: {},
79
stickyActiveProvider: null,
80
});
79
-});
80
-
81
-afterEach(() => {
82
- dismissAllSnapShotAnimations();
83
- vi.useRealTimers();
84
- vi.unstubAllGlobals();
85
- vi.restoreAllMocks();
86
-});
81
+ return {
82
+ [Symbol.dispose]() {
83
+ dismissAllSnapShotAnimations();
84
+ vi.unstubAllGlobals();
85
+ vi.restoreAllMocks();
86
+ },
87
+ };
88
+}
89
90
describe("window capture failures", () => {
91
it("dismisses an older failed capture without disturbing a newer capture", async () => {
92
+ using _env = setup();
93
const target = DraftId.make("snap-shot-draft");
94
const pendingStarts = new Set<string>();
95
const soundedIds = new Set(["older", "newer"]);
@@ -113,6 +116,7 @@ describe("window capture failures", () => {
116
});
117
118
it("does not resurrect a failed capture when its draft becomes ready later", async () => {
119
+ using _env = setup();
120
const target = DraftId.make("snap-shot-draft");
121
let resolveTarget: ((target: DraftId) => void) | undefined;
122
const targetReady = new Promise<DraftId>((resolve) => {
@@ -133,6 +137,7 @@ describe("window capture failures", () => {
137
});
138
139
it("keeps global failures dismissing all active and pending captures", async () => {
140
+ using _env = setup();
141
const target = DraftId.make("snap-shot-draft");
142
let resolveTarget: ((target: DraftId) => void) | undefined;
143
const targetReady = new Promise<DraftId>((resolve) => {
@@ -168,10 +173,7 @@ describe("pending snapshot processing", () => {
173
},
174
};
175
const target = scopeThreadRef(environmentId, ThreadId.make("enabled-thread"));
171
- let root: Root;
172
- let container: HTMLDivElement;
173
-
174
- function setup(routeThreadRef: typeof target | null = target) {
176
+ function coordinatorFixture(routeThreadRef: typeof target | null = target) {
177
let currentSettings = {
178
...DEFAULT_CLIENT_SETTINGS,
179
snapShotEnabled: true,
@@ -212,43 +214,44 @@ describe("pending snapshot processing", () => {
214
const sound = vi.spyOn(snapShotSound, "playSnapShotSound").mockImplementation(() => undefined);
215
const toast = vi.spyOn(toastManager, "add").mockReturnValue("toast-id");
216
vi.stubGlobal("desktopBridge", bridge);
215
- vi.stubGlobal("IS_REACT_ACT_ENVIRONMENT", true);
216
- container = document.createElement("div");
217
- document.body.append(container);
218
- root = createRoot(container);
219
- const render = () => act(async () => root.render(createElement(SnapShotCoordinator)));
217
+ let screen: Screen | undefined;
218
+ // Settings and route changes rerender the same coordinator instead of remounting it.
219
+ const renderCoordinator = async () => {
220
+ if (screen) await screen.rerender(createElement(SnapShotCoordinator));
221
+ // useHandleNewThread is mocked above, so nothing in the coordinator touches the router.
222
+ else screen = await render(createElement(SnapShotCoordinator), { router: false });
223
+ };
224
return {
225
bridge,
226
route,
227
sound,
228
toast,
225
- render,
229
+ render: renderCoordinator,
230
setPending: (items: typeof pending) => {
231
pending = items;
232
},
233
setEnabled: async (snapShotEnabled: boolean) => {
234
currentSettings = { ...currentSettings, snapShotEnabled };
231
- await render();
235
+ await renderCoordinator();
236
},
237
emit: (event: DesktopSnapShotEvent) =>
238
act(async () => {
239
for (const listener of listeners) listener(event);
240
}),
241
+ [Symbol.asyncDispose]: async () => {
242
+ await screen?.[Symbol.asyncDispose]();
243
+ },
244
};
245
}
246
240
- afterEach(async () => {
241
- await act(async () => root?.unmount());
242
- container?.remove();
243
- });
244
-
247
const focus = () =>
248
act(async () => {
249
window.dispatchEvent(new Event("focus"));
250
});
251
252
it("leaves captures untouched while disabled and resumes them when enabled again", async () => {
251
- const fixture = setup();
253
+ using _env = setup();
254
+ await using fixture = coordinatorFixture();
255
const { bridge, sound, toast } = fixture;
256
await fixture.setEnabled(false);
257
await focus();
@@ -287,7 +290,8 @@ describe("pending snapshot processing", () => {
290
});
291
292
it("reports each pending capture failure once, allows a new failure kind, and resets after success", async () => {
290
- const fixture = setup(null);
293
+ using _env = setup();
294
+ await using fixture = coordinatorFixture(null);
295
const { bridge, sound, toast, route } = fixture;
296
await fixture.render();
297
await focus();
@@ -337,7 +341,8 @@ describe("pending snapshot processing", () => {
341
});
342
343
it("suppresses deferred failures while disabled and reports fresh failures after re-enable", async () => {
340
- const fixture = setup();
344
+ using _env = setup();
345
+ await using fixture = coordinatorFixture();
346
const { bridge, sound, toast } = fixture;
347
let rejectRead: ((error: Error) => void) | undefined;
348
bridge.readSnapShot.mockReturnValueOnce(
@@ -404,7 +409,8 @@ describe("pending snapshot processing", () => {
409
});
410
411
it("keeps a capture pending when disabled during target resolution, then retries on re-enable", async () => {
407
- const fixture = setup(null);
412
+ using _env = setup();
413
+ await using fixture = coordinatorFixture(null);
414
const { bridge, route } = fixture;
415
route.defaultProjectRef = projectRef;
416
const draftId = DraftId.make("resolving-snapshot");
@@ -432,7 +438,8 @@ describe("pending snapshot processing", () => {
438
});
439
440
it("finishes and acknowledges delivery already reading when disabled", async () => {
435
- const fixture = setup();
441
+ using _env = setup();
442
+ await using fixture = coordinatorFixture();
443
let finishReading: ((value: typeof capture) => void) | undefined;
444
const reading = new Promise<typeof capture>((resolve) => {
445
finishReading = resolve;
@@ -467,7 +474,8 @@ describe("window capture delivery", () => {
474
])(
475
"preserves capture contents for $target before a stalled animation finishes ($accessibleText)",
476
async ({ target, accessibleText }) => {
470
- vi.useFakeTimers();
477
+ using _env = setup();
478
+ using _timers = fakeTimers();
479
const never = new Promise<void>(() => undefined);
480
const animationFrames: Array<FrameRequestCallback> = [];
481
const acknowledgeSnapShot = vi.fn(async () => undefined);
@@ -574,6 +582,7 @@ describe("window capture delivery", () => {
582
583
describe("window capture target resolution", () => {
584
it("shares bare-route draft creation between animation start and capture drain", async () => {
585
+ using _env = setup();
586
const draftId = DraftId.make("snap-shot-draft");
587
let finishResolution: ((target: DraftId) => void) | undefined;
588
const resolveTarget = vi.fn(
@@ -595,6 +604,7 @@ describe("window capture target resolution", () => {
604
});
605
606
it("follows a draft to its promoted server thread", () => {
607
+ using _env = setup();
608
const draftId = DraftId.make("snap-shot-draft");
609
const promotedRef = scopeThreadRef(environmentId, ThreadId.make("snap-shot-promoted-thread"));
610
const store = useComposerDraftStore.getState();
@@ -607,6 +617,7 @@ describe("window capture target resolution", () => {
617
});
618
619
it("keeps the routed server thread before its shell loads", () => {
620
+ using _env = setup();
621
const routeThreadRef = scopeThreadRef(environmentId, ThreadId.make("snap-shot-routed-thread"));
622
623
expect(resolveExistingSnapShotTarget(routeThreadRef, routeThreadRef)).toEqual(routeThreadRef);
@@ -638,6 +649,7 @@ describe("open question delivery", () => {
649
};
650
651
it("attaches a capture to the open question draft and leaves the thread draft alone", async () => {
652
+ using _env = setup();
653
const pins = new Map();
654
const untrack = trackOpenQuestionAttachmentDraft(threadRef, request);
655
try {
@@ -655,6 +667,7 @@ describe("open question delivery", () => {
667
});
668
669
it("falls back to the thread when a newer question replaces the pinned one during compression", async () => {
670
+ using _env = setup();
671
const pins = new Map();
672
const untrackFirst = trackOpenQuestionAttachmentDraft(threadRef, request);
673
let untrackSecond = () => {};
@@ -686,6 +699,7 @@ describe("open question delivery", () => {
699
});
700
701
it("keeps a capture pinned before any question off a question that opens during the read", async () => {
702
+ using _env = setup();
703
const pins = new Map();
704
const resolveTarget = () => resolveSnapShotAttachmentTarget(pins, capture.id, threadRef);
705
// The drain pins a capture it never saw requested before reading it.
@@ -707,6 +721,7 @@ describe("open question delivery", () => {
721
});
722
723
it("refuses a capture once the request's other questions hold the shared limit", async () => {
724
+ using _env = setup();
725
useComposerDraftStore.getState().addImages(
726
first,
727
Array.from({ length: PROVIDER_SEND_TURN_MAX_ATTACHMENTS }, (_, index) => ({
@@ -739,6 +754,7 @@ describe("durable snapshot delivery", () => {
754
it.each([false, true])(
755
"retains a capture on quota failure and retries without duplicates (staged: %s)",
756
async (staged) => {
757
+ using _env = setup();
758
const target = scopeThreadRef(environmentId, ThreadId.make("quota-thread"));
759
const capture = {
760
id: "12345678-1234-1234-1234-123456789abc",
@@ -798,6 +814,7 @@ describe("snapshot destination ownership", () => {
814
it.each(["unmount", "blur", "disabled animations"])(
815
"keeps the original environment and thread after %s",
816
async (reason) => {
817
+ using _env = setup();
818
const original = scopeThreadRef(environmentId, ThreadId.make("original"));
819
const next = scopeThreadRef(EnvironmentId.make("another-environment"), ThreadId.make("next"));
820
const targets = new Map<string, Promise<typeof original | null>>();
apps/web/src/components/preview/PreviewPanelShell.a11y.browser.test.tsx
+1
-1
@@ -59,7 +59,7 @@ function nextFrame() {
59
async function enterFocusScope() {
60
const toggle = document.querySelector<HTMLElement>('[aria-label="Toggle right panel"]')!;
61
await act(async () => toggle.focus());
62
- await act(() => userEvent.tab());
62
+ await userEvent.tab();
63
await act(nextFrame);
64
}
65
apps/web/src/components/preview/previewSessionSync.browser.test.ts
+76
-66
@@ -7,9 +7,10 @@ import {
7
} from "@t3tools/contracts";
8
import * as Cause from "effect/Cause";
9
import { AsyncResult, Atom } from "effect/reactivity";
10
-import { act, createElement } from "react";
11
-import { createRoot, type Root } from "react-dom/client";
12
-import { afterEach, beforeEach, describe, expect, it, vi } from "vite-plus/test";
10
+import { createElement } from "react";
11
+import { describe, expect, it, vi } from "vite-plus/test";
12
+
13
+import { act, render } from "../../../test/render";
14
15
// Only the transport is substituted. The hook, atom registry and preview
16
// store run unchanged, including lazy evaluation and refresh notifications.
@@ -78,71 +79,70 @@ import { AppAtomRegistryProvider, appAtomRegistry } from "~/rpc/atomRegistry";
79
import { previewEnvironment } from "~/state/preview";
80
import { useDesktopHostedPreviewSessions, usePreviewSession } from "./usePreviewSession";
81
81
-let root: Root | null = null;
82
-let container: HTMLDivElement | null = null;
83
-let sequence = 0;
84
-let ref: ScopedThreadRef;
85
-
86
-function SessionSync() {
87
- usePreviewSession(ref);
88
- return null;
89
-}
90
-
91
-const listAtom = () => {
92
- previewEnvironment.list({ environmentId: ref.environmentId, input: { threadId: ref.threadId } });
93
- return harness.lists.get(ref.threadId)!.atom;
94
-};
95
-const result = (
96
- revision: number,
97
- tabIds: string[],
98
- serverEpoch = "epoch-1",
99
-): PreviewListResult => ({
100
- serverEpoch,
101
- revision,
102
- sessions: tabIds.map((tabId) => ({
103
- threadId: ref.threadId,
104
- tabId,
105
- navStatus: { _tag: "Idle" },
106
- canGoBack: false,
107
- canGoForward: false,
108
- updatedAt: "2026-10-02T00:00:00.000Z",
109
- })),
110
-});
111
-
112
-function DesktopSessionSync() {
113
- useDesktopHostedPreviewSessions(ref.environmentId);
114
- return null;
115
-}
82
+function setup() {
83
+ harness.lists.clear();
84
+ harness.events.clear();
85
+ resetPreviewStateForTests();
86
+ // The app atom registry outlives each test, so every test gets its own environment and thread.
87
+ const testName = expect.getState().currentTestName!;
88
+ const ref: ScopedThreadRef = {
89
+ environmentId: EnvironmentId.make(`preview-sync ${testName}`),
90
+ threadId: ThreadId.make(`thread-sync ${testName}`),
91
+ };
92
117
-async function mount(Component = SessionSync) {
118
- container = document.body.appendChild(document.createElement("div"));
119
- root = createRoot(container);
120
- await act(async () => {
121
- root!.render(createElement(AppAtomRegistryProvider, null, createElement(Component)));
93
+ const listAtom = () => {
94
+ previewEnvironment.list({
95
+ environmentId: ref.environmentId,
96
+ input: { threadId: ref.threadId },
97
+ });
98
+ return harness.lists.get(ref.threadId)!.atom;
99
+ };
100
+ const result = (
101
+ revision: number,
102
+ tabIds: string[],
103
+ serverEpoch = "epoch-1",
104
+ ): PreviewListResult => ({
105
+ serverEpoch,
106
+ revision,
107
+ sessions: tabIds.map((tabId) => ({
108
+ threadId: ref.threadId,
109
+ tabId,
110
+ navStatus: { _tag: "Idle" },
111
+ canGoBack: false,
112
+ canGoForward: false,
113
+ updatedAt: "2026-10-02T00:00:00.000Z",
114
+ })),
115
});
123
-}
116
125
-beforeEach(() => {
126
- vi.stubGlobal("IS_REACT_ACT_ENVIRONMENT", true);
127
- sequence += 1;
128
- ref = {
129
- environmentId: EnvironmentId.make(`preview-sync-${sequence}`),
130
- threadId: ThreadId.make(`thread-sync-${sequence}`),
131
- };
132
-});
117
+ function SessionSync() {
118
+ usePreviewSession(ref);
119
+ return null;
120
+ }
121
+ function DesktopSessionSync() {
122
+ useDesktopHostedPreviewSessions(ref.environmentId);
123
+ return null;
124
+ }
125
+ // The session hooks render nothing and never read or change the route.
126
+ const mount = (Component: () => null = SessionSync) =>
127
+ render(createElement(AppAtomRegistryProvider, null, createElement(Component)), {
128
+ router: false,
129
+ });
130
134
-afterEach(async () => {
135
- await act(async () => root?.unmount());
136
- root = null;
137
- container?.remove();
138
- container = null;
139
- resetPreviewStateForTests();
140
- vi.unstubAllGlobals();
141
-});
131
+ return {
132
+ ref,
133
+ listAtom,
134
+ result,
135
+ mount,
136
+ DesktopSessionSync,
137
+ [Symbol.dispose]: () => resetPreviewStateForTests(),
138
+ };
139
+}
140
141
describe("native preview session synchronization", () => {
142
it("discovers and closes a server tab in a background thread without mounting its chat", async () => {
145
- await mount(DesktopSessionSync);
143
+ using sync = setup();
144
+ const { ref, listAtom, result } = sync;
145
+ await using _screen = await sync.mount(sync.DesktopSessionSync);
146
expect(readThreadPreviewState(ref).sessions).toEqual({});
147
previewEnvironment.events({ environmentId: ref.environmentId, input: {} });
148
const events = harness.events.get(ref.environmentId)!;
@@ -183,18 +183,22 @@ describe("native preview session synchronization", () => {
183
});
184
185
it("evaluates the lazy list once and restores sessions that predate mounting", async () => {
186
+ using sync = setup();
187
+ const { ref, listAtom, result } = sync;
188
const atom = listAtom();
187
- await mount();
189
+ await using _screen = await sync.mount();
190
expect(harness.lists.get(ref.threadId)?.box.requests).toBe(1);
191
appAtomRegistry.set(atom, AsyncResult.success(result(1, ["restored"])));
192
expect(readThreadPreviewState(ref).activeTabId).toBe("restored");
193
});
194
195
it("preserves a local tab while cached absence is waiting for a fresh response", async () => {
196
+ using sync = setup();
197
+ const { ref, listAtom, result } = sync;
198
const atom = listAtom();
199
appAtomRegistry.set(atom, AsyncResult.waiting(AsyncResult.success(result(1, []))));
200
applyPreviewServerSnapshot(ref, result(1, ["local"]).sessions[0]!);
197
- await mount();
201
+ await using _screen = await sync.mount();
202
expect(readThreadPreviewState(ref).activeTabId).toBe("local");
203
expect(harness.lists.get(ref.threadId)?.box.requests).toBe(0);
204
appAtomRegistry.set(atom, AsyncResult.success(result(2, ["local"])));
@@ -204,6 +208,8 @@ describe("native preview session synchronization", () => {
208
});
209
210
it("refreshes a completed cache without treating its old absence as authoritative", async () => {
211
+ using sync = setup();
212
+ const { ref, listAtom, result } = sync;
213
const atom = listAtom();
214
appAtomRegistry.set(atom, AsyncResult.success(result(1, [])));
215
reconcilePreviewServerSessions(ref, result(1, []));
@@ -221,7 +227,7 @@ describe("native preview session synchronization", () => {
227
controller: "human",
228
favicon: null,
229
});
224
- await mount();
230
+ await using _screen = await sync.mount();
231
expect(harness.lists.get(ref.threadId)?.box.requests).toBe(1);
232
expect(readThreadPreviewState(ref).activeTabId).toBe("local");
233
expect(readThreadPreviewState(ref).desktopOverlay?.zoomFactor).toBe(1.5);
@@ -231,8 +237,10 @@ describe("native preview session synchronization", () => {
237
});
238
239
it("retains newer event state when an older list response completes, then retries the list", async () => {
240
+ using sync = setup();
241
+ const { ref, listAtom, result } = sync;
242
const atom = listAtom();
235
- await mount();
243
+ await using _screen = await sync.mount();
244
const snapshot = result(2, ["opened"]).sessions[0]!;
245
previewEnvironment.events({ environmentId: ref.environmentId, input: {} });
246
appAtomRegistry.set(
@@ -261,9 +269,11 @@ describe("native preview session synchronization", () => {
269
});
270
271
it("keeps the local snapshot on a completed failure and reconciles a later success", async () => {
272
+ using sync = setup();
273
+ const { ref, listAtom, result } = sync;
274
const atom = listAtom();
275
applyPreviewServerSnapshot(ref, result(1, ["local"]).sessions[0]!);
266
- await mount();
276
+ await using _screen = await sync.mount();
277
appAtomRegistry.set(atom, AsyncResult.failure(Cause.die("offline")));
278
expect(readThreadPreviewState(ref).activeTabId).toBe("local");
279
appAtomRegistry.set(atom, AsyncResult.success(result(2, [])));
apps/web/src/components/pullRequest/PullRequestCandidatePicker.browser.test.tsx
+8
-10
@@ -1,4 +1,4 @@
1
-import { act, render } from "../../../test/render";
1
+import { render } from "../../../test/render";
2
import { describe, expect, it, vi } from "vite-plus/test";
3
import { userEvent } from "vite-plus/test/browser";
4
@@ -40,21 +40,19 @@ describe("disabled candidate picker", () => {
40
'button[aria-label="Request reviewers"]',
41
)!;
42
if (input === "keyboard") {
43
- await act(() => userEvent.tab());
43
+ await userEvent.tab();
44
expect(document.activeElement).toBe(trigger);
45
} else {
46
- await act(() => userEvent.hover(trigger));
46
+ await userEvent.hover(trigger);
47
}
48
await expect
49
.poll(() => document.querySelector('[data-slot="tooltip-popup"][data-open]')?.textContent)
50
.toContain("Only collaborators can request reviewers.");
51
- await act(async () => {
52
- trigger.focus();
53
- await userEvent.keyboard("{Enter}");
54
- await userEvent.keyboard(" ");
55
- // Playwright skips aria-disabled targets; the click must still land to prove it is inert.
56
- await userEvent.click(trigger, { force: true });
57
- });
51
+ trigger.focus();
52
+ await userEvent.keyboard("{Enter}");
53
+ await userEvent.keyboard(" ");
54
+ // Playwright skips aria-disabled targets; the click must still land to prove it is inert.
55
+ await userEvent.click(trigger, { force: true });
56
expect(onOpenChange).not.toHaveBeenCalled();
57
expect(onSelect).not.toHaveBeenCalled();
58
},
apps/web/src/components/settings/AddProviderInstanceDialog.environment.browser.test.tsx
+1
-1
@@ -122,7 +122,7 @@ const input = (selector: string) => {
122
return found!;
123
};
124
async function type(selector: string, value: string) {
125
- await act(async () => userEvent.fill(input(selector), value));
125
+ await userEvent.fill(input(selector), value);
126
await act(async () => input(selector).blur());
127
}
128
const signInStep = () => document.querySelector('[aria-label="Sign-in step"]');
apps/web/src/components/settings/CaptureShortcutConfig.browser.test.tsx
+4
-4
@@ -85,8 +85,8 @@ async function renderConfig(desktop: "niri" | "hyprland" = "niri") {
85
await act(async () => target!.click());
86
},
87
async recordKeys(keys: string) {
88
- await act(async () => userEvent.click(recorder()));
89
- await act(async () => userEvent.keyboard(keys));
88
+ await userEvent.click(recorder());
89
+ await userEvent.keyboard(keys);
90
},
91
});
92
}
@@ -184,9 +184,9 @@ it.each(["Escape", "blur"])(
184
using _env = setup();
185
await using screen = await renderConfig();
186
await screen.click("Review changes");
187
- await act(async () => userEvent.click(screen.recorder()));
187
+ await userEvent.click(screen.recorder());
188
expect(screen.button("Save shortcut")?.disabled).toBe(true);
189
- if (cancel === "Escape") await act(async () => userEvent.keyboard("{Escape}"));
189
+ if (cancel === "Escape") await userEvent.keyboard("{Escape}");
190
else await act(async () => screen.recorder().blur());
191
expect(screen.button("Save shortcut")?.disabled).toBe(false);
192
expect(bridge.previewSnapShotConfig).toHaveBeenCalledOnce();
apps/web/src/components/settings/FontFamilyPicker.browser.test.tsx
+2
-2
@@ -48,10 +48,10 @@ describe("FontFamilyPicker", () => {
48
49
const input = document.querySelector<HTMLInputElement>('input[placeholder="Search fonts…"]');
50
expect(input).not.toBeNull();
51
- const press = (key: string) => act(() => userEvent.keyboard(`{${key}}`));
51
+ const press = (key: string) => userEvent.keyboard(`{${key}}`);
52
53
// Both matches were already rendered further down the unfiltered list.
54
- await act(() => userEvent.type(input!, "co"));
54
+ await userEvent.type(input!, "co");
55
await expect.poll(highlightedOptions).toEqual(["Courier New"]);
56
57
await press("ArrowDown");
apps/web/src/components/settings/ProjectSettingsPanel.browser.test.tsx
+8
-10
@@ -438,19 +438,19 @@ describe("project settings scope", () => {
438
const primaryOption = () => page.getByRole("menuitemradio", { name: /^primary/ });
439
const remoteOption = () => page.getByRole("menuitemradio", { name: /^remote/ });
440
441
- await act(async () => userEvent.click(environmentMenu()));
441
+ await userEvent.click(environmentMenu());
442
await expect.element(primaryOption()).toBeVisible();
443
await expect.element(remoteOption()).toBeVisible();
444
- await act(async () => userEvent.keyboard("{Escape}"));
444
+ await userEvent.keyboard("{Escape}");
445
446
await act(async () =>
447
screen.router.navigate({ to: "/settings/projects", search: () => ({ project: key }) }),
448
);
449
await expect.element(page.getByRole("textbox", { name: "Project name" })).toBeVisible();
450
- await act(async () => userEvent.click(environmentMenu()));
450
+ await userEvent.click(environmentMenu());
451
await expect.element(primaryOption()).toBeVisible();
452
await expect.element(remoteOption()).not.toBeInTheDocument();
453
- await act(async () => userEvent.keyboard("{Escape}"));
453
+ await userEvent.keyboard("{Escape}");
454
455
await act(async () =>
456
screen.router.navigate({
@@ -458,10 +458,10 @@ describe("project settings scope", () => {
458
search: () => ({ project: "removed-project" }),
459
}),
460
);
461
- await act(async () => userEvent.click(environmentMenu()));
461
+ await userEvent.click(environmentMenu());
462
await expect.element(primaryOption()).toBeVisible();
463
await expect.element(remoteOption()).toBeVisible();
464
- await act(async () => userEvent.click(remoteOption()));
464
+ await userEvent.click(remoteOption());
465
await vi.waitFor(() =>
466
expect(screen.router.state.location.search).toEqual({
467
project: "removed-project",
@@ -491,9 +491,7 @@ describe("project settings scope", () => {
491
await expect
492
.element(page.getByRole("button", { name: "Environment scope: remote" }))
493
.toBeVisible();
494
- await act(async () =>
495
- userEvent.click(page.getByRole("button", { name: "Show all environments" })),
496
- );
494
+ await userEvent.click(page.getByRole("button", { name: "Show all environments" }));
495
496
await expect
497
.element(page.getByRole("textbox", { name: "Project name" }))
@@ -517,7 +515,7 @@ it("returns to the project overview after removal, clearing the selection but ke
515
(button) => button.textContent === "Remove project",
516
)!;
517
520
- await act(async () => userEvent.click(removeProject));
518
+ await userEvent.click(removeProject);
519
520
await vi.waitFor(() => {
521
expect(screen.router.state.location.pathname).toBe("/settings/projects");
apps/web/src/components/settings/ProviderSetupSection.browser.test.tsx
+4
-6
@@ -195,7 +195,7 @@ describe("Antigravity setup", () => {
195
resetSetup();
196
const callbackUrl = "http://127.0.0.1:5555/?state=test-only&code=test-only";
197
await using screen = await renderSetup();
198
- await act(async () => userEvent.fill(screen.callbackInput(), callbackUrl));
198
+ await userEvent.fill(screen.callbackInput(), callbackUrl);
199
await screen.click("Continue");
200
201
expect(setup.completeAuth).toHaveBeenCalledWith({
@@ -244,11 +244,9 @@ describe("Antigravity setup", () => {
244
};
245
setup.auth = authState({ interaction });
246
await using screen = await renderSetup();
247
- await act(async () =>
248
- userEvent.fill(
249
- screen.callbackInput(),
250
- "http://127.0.0.1:5555/?state=old-flow&code=test-only",
251
- ),
247
+ await userEvent.fill(
248
+ screen.callbackInput(),
249
+ "http://127.0.0.1:5555/?state=old-flow&code=test-only",
250
);
251
setup.auth = authState({ flowId: "flow-2", interaction });
252
await publish();
apps/web/src/components/settings/SnapShotSettings.browser.test.tsx
+10
-9
@@ -186,13 +186,14 @@ it.each(["direct", "gnome-extension", "kde"] as const)(
186
"Record snapshot shortcut, currently Ctrl+Shift+2",
187
);
188
}
189
- await act(async () => userEvent.click(recorder()));
190
- await act(async () => userEvent.keyboard("{Control>}{Alt>}y{/Alt}{/Control}"));
189
+ await userEvent.click(recorder());
190
+ await userEvent.keyboard("{Control>}{Alt>}y{/Alt}{/Control}");
191
expect(bridge.checkSnapShotShortcut).toHaveBeenCalledOnce();
192
- expect(container.textContent).toContain("Ready to save.");
193
- expect(recorder().getAttribute("aria-label")).toBe(
194
- "Record snapshot shortcut, currently Ctrl+Alt+Y",
195
- );
192
+ // The status and label update only after the awaited shortcut check resolves.
193
+ await expect.poll(() => container.textContent).toContain("Ready to save.");
194
+ await expect
195
+ .poll(() => recorder().getAttribute("aria-label"))
196
+ .toBe("Record snapshot shortcut, currently Ctrl+Alt+Y");
197
await click("Save");
198
expect(settingsStore.update).toHaveBeenCalledWith({
199
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
234
expect(recorder().getAttribute("aria-label")).toBe(
235
"Record snapshot shortcut, currently Ctrl+Alt+8",
236
);
236
- await act(async () => userEvent.click(recorder()));
237
+ await userEvent.click(recorder());
238
expect(recorder().textContent).toBe("Press shortcut…");
238
- await act(async () => userEvent.keyboard("{Escape}"));
239
+ await userEvent.keyboard("{Escape}");
240
expect(dialog()).not.toBeNull();
241
expect(recorder().getAttribute("aria-label")).toBe(
242
"Record snapshot shortcut, currently Ctrl+Alt+8",
@@ -273,7 +274,7 @@ it("keeps older portal shortcuts editable without offering unsupported permissio
274
const { button, recorder } = screen;
275
expect(button("Shortcut permissions")).toBeNull();
276
expect(bridge.setupSnapShot).not.toHaveBeenCalled();
276
- await act(async () => userEvent.click(recorder()));
277
+ await userEvent.click(recorder());
278
expect(recorder().textContent).toBe("Press shortcut…");
279
});
280
apps/web/src/components/settings/useSnapShotShortcutRecorder.browser.test.tsx
+16
-18
@@ -1,6 +1,5 @@
1
import { act, render } from "../../../test/render";
2
import { DEFAULT_CLIENT_SETTINGS } from "@t3tools/contracts";
3
-import { useEffect } from "react";
3
import { userEvent } from "vite-plus/test/browser";
4
import { expect, it, vi } from "vite-plus/test";
5
@@ -22,7 +21,6 @@ function deferred<T>() {
21
22
const recorded = vi.fn();
23
const error = vi.fn();
25
-let recording = false;
24
25
function Recorder(props: { allowModifierPairs?: boolean; shortcutLabel?: string }) {
26
const recorder = useSnapShotShortcutRecorder({
@@ -32,9 +30,6 @@ function Recorder(props: { allowModifierPairs?: boolean; shortcutLabel?: string
30
onRecord: recorded,
31
onError: error,
32
});
35
- useEffect(() => {
36
- recording = recorder.recording;
37
- });
33
return recorder.input;
34
}
35
@@ -42,22 +37,25 @@ function setup() {
37
suppress.mockReset().mockResolvedValue(undefined);
38
recorded.mockReset();
39
error.mockReset();
45
- recording = false;
40
}
41
async function renderRecorder(props: Parameters<typeof Recorder>[0] = {}) {
42
const screen = await render(<Recorder {...props} />);
43
const button = () =>
44
screen.container.querySelector<HTMLButtonElement>("[data-keybinding-capture]")!;
45
+ // aria-pressed mirrors the hook's recording state, which flips once suppression resolves.
46
+ const expectRecording = (recording: boolean) =>
47
+ expect.element(screen.getByRole("button")).toHaveAttribute("aria-pressed", String(recording));
48
return {
49
...screen,
50
button,
51
+ expectRecording,
52
async start() {
55
- await act(() => userEvent.click(button()));
56
- expect(recording).toBe(true);
53
+ await userEvent.click(button());
54
+ await expectRecording(true);
55
},
56
};
57
}
60
-const press = (keys: string) => act(async () => userEvent.keyboard(keys));
58
+const press = (keys: string) => userEvent.keyboard(keys);
59
60
it("suppresses capture while recording and uses the physical key for shifted digits", async () => {
61
setup();
@@ -77,7 +75,7 @@ it("suppresses capture while recording and uses the physical key for shifted dig
75
shiftKey: true,
76
});
77
expect(suppress).toHaveBeenLastCalledWith(false);
80
- expect(recording).toBe(false);
78
+ await screen.expectRecording(false);
79
});
80
81
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
86
const { button } = screen;
87
expect(button().textContent).toBe("Change shortcut");
88
expect(button().getAttribute("aria-label")).toBe("Change snapshot shortcut");
91
- await act(async () => userEvent.click(button()));
89
+ await userEvent.click(button());
90
expect(button().textContent).toBe("Press shortcut…");
91
await press("{Control>}{Shift>}2{/Shift}{/Control}");
92
expect(recorded).toHaveBeenCalledWith(
@@ -124,7 +122,7 @@ it.each(["Escape", "blur", "unmount"])("cancels on %s without selecting keys", a
122
else await screen.unmount();
123
expect(suppress).toHaveBeenLastCalledWith(false);
124
expect(recorded).not.toHaveBeenCalled();
127
- if (cancel !== "unmount") expect(recording).toBe(false);
125
+ if (cancel !== "unmount") await screen.expectRecording(false);
126
});
127
128
it("ignores late suppression acknowledgements after cancellation", async () => {
@@ -134,10 +132,10 @@ it("ignores late suppression acknowledgements after cancellation", async () => {
132
suppress.mockImplementation((enabled) => (enabled ? pending.promise : Promise.resolve()));
133
await using screen = await renderRecorder();
134
const { button } = screen;
137
- await act(async () => userEvent.click(button()));
135
+ await userEvent.click(button());
136
await act(async () => button().blur());
137
await act(async () => pending.resolve());
140
- expect(recording).toBe(false);
138
+ await screen.expectRecording(false);
139
expect(suppress).toHaveBeenLastCalledWith(false);
140
expect(recorded).not.toHaveBeenCalled();
141
});
@@ -148,8 +146,8 @@ it("reports suppression failures instead of arming the recorder", async () => {
146
suppress.mockRejectedValue(new Error("Couldn't pause capture"));
147
await using screen = await renderRecorder();
148
const { button } = screen;
151
- await act(async () => userEvent.click(button()));
152
- expect(recording).toBe(false);
149
+ await userEvent.click(button());
150
+ await screen.expectRecording(false);
151
expect(error).toHaveBeenCalledWith("Couldn't pause capture");
152
});
153
@@ -162,7 +160,7 @@ it("does not record Tab, unmodified keys, or modifier keys on their own", async
160
await press("y");
161
await press("{Control>}{/Control}");
162
expect(recorded).not.toHaveBeenCalled();
165
- expect(recording).toBe(true);
163
+ await screen.expectRecording(true);
164
await press("{Tab}");
165
expect(document.activeElement).not.toBe(button());
166
});
@@ -176,7 +174,7 @@ it("rejects modifier pairs on Wayland but accepts the next key chord", async ()
174
await press("{ShiftLeft>}{ShiftRight>}{/ShiftRight}{/ShiftLeft}");
175
expect(recorded).not.toHaveBeenCalled();
176
expect(error).toHaveBeenCalledWith(expect.stringContaining("Add a letter, number"));
179
- expect(recording).toBe(true);
177
+ await screen.expectRecording(true);
178
await press("{Control>}{Alt>}y{/Alt}{/Control}");
179
expect(recorded).toHaveBeenCalledOnce();
180
});
apps/web/src/components/usage/UsageLimitsPooled.browser.test.tsx
+6
-6
@@ -81,7 +81,7 @@ async function click(label: string) {
81
(node) => node.textContent === label || node.getAttribute("aria-label")?.startsWith(label),
82
);
83
expect(button).toBeDefined();
84
- await act(() => userEvent.click(button!));
84
+ await userEvent.click(button!);
85
}
86
87
/**
@@ -225,24 +225,24 @@ it("moves the one limit popover between windows on hover", async () => {
225
const session = segment("Alpha: 60%");
226
const weekly = segment("Alpha: 68%");
227
228
- await act(() => userEvent.click(session));
228
+ await userEvent.click(session);
229
await expect.poll(popups).toEqual([expect.stringContaining("Left60%")]);
230
231
- await act(() => userEvent.hover(weekly));
231
+ await userEvent.hover(weekly);
232
await expect.poll(popups).toEqual([expect.stringContaining("Left68%")]);
233
234
// Weekly's popover now sits over the middle of the Session bar; come back in at its edge.
235
- await act(() => userEvent.hover(session, { position: { x: 4, y: 4 } }));
235
+ await userEvent.hover(session, { position: { x: 4, y: 4 } });
236
await expect.poll(popups).toEqual([expect.stringContaining("Left60%")]);
237
238
await expectDismissedInPlace(() =>
239
act(() => screen.rerender(<UsageLimitsPooled presentations={new Map()} now={0} />)),
240
);
241
- await act(() => userEvent.hover(container, { position: { x: 4, y: 4 } }));
241
+ await userEvent.hover(container, { position: { x: 4, y: 4 } });
242
243
await act(() => screen.rerender(<UsageLimitsPooled presentations={twoWindows} now={0} />));
244
await expect.poll(popups).toEqual([]);
245
- await act(() => userEvent.click(segment("Alpha: 60%")));
245
+ await userEvent.click(segment("Alpha: 60%"));
246
await expect.poll(popups).toEqual([expect.stringContaining("Left60%")]);
247
});
248
apps/web/src/composer-list-split.browser.test.ts
+20
-24
@@ -2,7 +2,7 @@ import { Editor } from "@tiptap/core";
2
import { TaskList } from "@tiptap/extension-task-list";
3
import { TextSelection } from "@tiptap/pm/state";
4
import StarterKit from "@tiptap/starter-kit";
5
-import { afterEach, describe, expect, it } from "vite-plus/test";
5
+import { describe, expect, it } from "vite-plus/test";
6
7
import {
8
backspaceAcrossList,
@@ -19,13 +19,8 @@ import {
19
} from "./composer-rich-text-doc";
20
21
// ProseMirror's DOM observer can flush on a timer after a test ends, which
22
-// throws once its DOM is gone, so every editor is destroyed after its test.
23
-const editors: Editor[] = [];
24
-afterEach(() => {
25
- for (const editor of editors.splice(0)) editor.destroy();
26
-});
27
-
28
-function makeEditor(value: string) {
22
+// throws once its DOM is gone, so every editor is acquired with `using`.
23
+function makeEditor(value: string): Editor & Disposable {
24
const editor = new Editor({
25
extensions: [
26
StarterKit.configure({
@@ -47,12 +42,11 @@ function makeEditor(value: string) {
42
],
43
content: buildDocJson(value, (name) => ({ label: name, description: null })),
44
});
50
- editors.push(editor);
51
- return editor;
45
+ return Object.assign(editor, { [Symbol.dispose]: () => editor.destroy() });
46
}
47
48
function splitLastItem(value: string, type: "listItem" | "taskItem", overrides: object) {
55
- const editor = makeEditor(value);
49
+ using editor = makeEditor(value);
50
editor.view.dispatch(editor.state.tr.setSelection(TextSelection.atEnd(editor.state.doc)));
51
editor.commands.splitListItem(type, overrides);
52
editor.view.dispatch(editor.state.tr.insertText("b"));
@@ -88,7 +82,8 @@ function placeCaret(editor: Editor, text: string, offset = 0) {
82
83
function storedDraft(editor: Editor) {
84
const stored = serializeEditorDoc(editor.state.doc).value;
91
- expect(makeEditor(stored).state.doc.toString()).toBe(editor.state.doc.toString());
85
+ using reloaded = makeEditor(stored);
86
+ expect(reloaded.state.doc.toString()).toBe(editor.state.doc.toString());
87
return stored;
88
}
89
@@ -102,7 +97,7 @@ describe("Shift+Enter twice on an item", () => {
97
["- [ ] a\n - [ ] x", "- [ ] a\n - [ ] x\n- [ ] b"],
98
["- [x] a\n - [ ] x\n- [ ] c", "- [x] a\n - [ ] x\n- [ ] b\n- [ ] c"],
99
])("after x in %j writes %j", (value, expected) => {
105
- const editor = makeEditor(value);
100
+ using editor = makeEditor(value);
101
let caret = -1;
102
editor.state.doc.descendants((node, pos) => {
103
if (node.isText && node.text === "x") caret = pos + 1;
@@ -115,7 +110,8 @@ describe("Shift+Enter twice on an item", () => {
110
editor.view.dispatch(editor.state.tr.insertText("b"));
111
const stored = serializeEditorDoc(editor.state.doc).value;
112
expect(stored).toBe(expected);
118
- expect(makeEditor(stored).state.doc.toString()).toBe(editor.state.doc.toString());
113
+ using reloaded = makeEditor(stored);
114
+ expect(reloaded.state.doc.toString()).toBe(editor.state.doc.toString());
115
});
116
});
117
@@ -125,7 +121,7 @@ describe("Shift+Enter in the middle of an ordered list", () => {
121
["1) a\n2) x\n3) c", "1) a\n2) x\n3) b\n4) c"],
122
["1. a\n 1. x\n 2. c\n2. d", "1. a\n 1. x\n 2. b\n 3. c\n2. d"],
123
])("after x in %j writes %j", (value, expected) => {
128
- const editor = makeEditor(value);
124
+ using editor = makeEditor(value);
125
placeCaret(editor, "x", 1);
126
expect(splitOrLiftListItem(editor)).toBe(true);
127
editor.view.dispatch(editor.state.tr.insertText("b"));
@@ -135,7 +131,7 @@ describe("Shift+Enter in the middle of an ordered list", () => {
131
132
describe("Shift+Enter on an empty task under a bullet", () => {
133
it.each(["- a\n - [ ] x", "- [ ] a\n - x"])("in %j keeps the draft honest", (value) => {
138
- const editor = makeEditor(value);
134
+ using editor = makeEditor(value);
135
placeCaret(editor, "x", 1);
136
splitOrLiftListItem(editor);
137
splitOrLiftListItem(editor);
@@ -153,7 +149,7 @@ describe("Backspace at the start of a line", () => {
149
["- a\n - x\nb", "b", "- a\n - xb"],
150
["1. a\nb", "b", "1. ab"],
151
])("in %j at %s writes %j", (value, at, expected) => {
156
- const editor = makeEditor(value);
152
+ using editor = makeEditor(value);
153
placeCaret(editor, at);
154
expect(backspaceAcrossList(editor)).toBe(true);
155
expect(storedDraft(editor)).toBe(expected);
@@ -163,7 +159,7 @@ describe("Backspace at the start of a line", () => {
159
["- a\n```\nl1\nl2\n```", "- a\nl1\nl2"],
160
["p\n```ts\nl1\n```", "p\nl1"],
161
])("removes the fence of %j rather than joining its code up", (value, expected) => {
166
- const editor = makeEditor(value);
162
+ using editor = makeEditor(value);
163
placeCaret(editor, "l1");
164
editor.commands.keyboardShortcut("Backspace");
165
expect(storedDraft(editor)).toBe(expected);
@@ -176,14 +172,14 @@ describe("Delete at the end of a line", () => {
172
["- a\n - x\n- c", "- ax\n- c"],
173
["- a\n\nb", "- a\nb"],
174
])("in %j writes %j", (value, expected) => {
179
- const editor = makeEditor(value);
175
+ using editor = makeEditor(value);
176
placeCaret(editor, "a", 1);
177
expect(deleteAcrossList(editor)).toBe(true);
178
expect(storedDraft(editor)).toBe(expected);
179
});
180
181
it.each(["- a\n```\nl1\n```", "a\n```\nl1\n```"])("leaves the fence in %j alone", (value) => {
186
- const editor = makeEditor(value);
182
+ using editor = makeEditor(value);
183
placeCaret(editor, "a", 1);
184
editor.commands.keyboardShortcut("Delete");
185
expect(storedDraft(editor)).toBe(value);
@@ -192,7 +188,7 @@ describe("Delete at the end of a line", () => {
188
189
describe("blocks that a list item or quote cannot hold", () => {
190
it("puts lines pasted at the end of an item after the list", () => {
195
- const editor = makeEditor("- a");
191
+ using editor = makeEditor("- a");
192
editor.view.dispatch(editor.state.tr.setSelection(TextSelection.atEnd(editor.state.doc)));
193
const lines = buildTiptapContent("one\ntwo", (name) => ({ label: name, description: null }));
194
editor.commands.insertContent(lines);
@@ -200,7 +196,7 @@ describe("blocks that a list item or quote cannot hold", () => {
196
});
197
198
it("will not make a task list inside a quote", () => {
203
- const editor = makeEditor("> q");
199
+ using editor = makeEditor("> q");
200
placeCaret(editor, "q");
201
expect(editor.commands.wrapInList("taskList")).toBe(false);
202
expect(storedDraft(editor)).toBe("> q");
@@ -216,7 +212,7 @@ describe("[ ] typed at the start of a bullet item", () => {
212
["- [ ]x\n - y", "- [ ] x\n - y"],
213
["- [ ]x", "- [ ] x"],
214
])("makes the item in %j a task where it stands", (value, expected) => {
219
- const editor = makeEditor(value);
215
+ using editor = makeEditor(value);
216
placeCaret(editor, "[ ]x");
217
const from = editor.state.selection.from;
218
editor.view.dispatch(
@@ -233,7 +229,7 @@ describe("[ ] typed at the start of a bullet item", () => {
229
230
describe("a rule at the end of the draft", () => {
231
it("keeps an empty line after it to type on", () => {
236
- const editor = makeEditor("a\n---");
232
+ using editor = makeEditor("a\n---");
233
editor.view.dispatch(
234
editor.state.tr.delete(editor.state.doc.content.size - 2, editor.state.doc.content.size),
235
);
apps/web/src/lib/editableFocus.browser.test.ts
+2
-5
@@ -1,11 +1,7 @@
1
-import { afterEach, describe, expect, it } from "vite-plus/test";
1
+import { describe, expect, it } from "vite-plus/test";
2
3
import { isEditableFocused } from "./editableFocus";
4
5
-afterEach(() => {
6
- document.body.replaceChildren();
7
-});
8
-
5
describe("isEditableFocused", () => {
6
it("sees a text field focused inside an open shadow root", () => {
7
// A key event from a shadow input is retargeted to its host, so the host is
@@ -14,6 +10,7 @@ describe("isEditableFocused", () => {
10
const input = document.createElement("input");
11
host.attachShadow({ mode: "open" }).append(input);
12
document.body.append(host);
13
+ using _host = { [Symbol.dispose]: () => host.remove() };
14
15
expect(isEditableFocused(host)).toBe(false);
16
input.focus();
apps/web/src/shortcutModifierState.browser.test.ts
+13
-29
@@ -1,6 +1,7 @@
1
-import { act, createElement } from "react";
2
-import { createRoot, type Root } from "react-dom/client";
3
-import { afterEach, beforeEach, describe, expect, it, vi } from "vite-plus/test";
1
+import { createElement } from "react";
2
+import { describe, expect, it, vi } from "vite-plus/test";
3
+
4
+import { act, render } from "../test/render";
5
6
import {
7
areShortcutModifierStatesEqual,
@@ -17,33 +18,16 @@ const emptyState = (): ShortcutModifierState => ({
18
});
19
20
describe("useShortcutModifierState", () => {
20
- let root: Root;
21
- let container: HTMLDivElement;
22
-
23
- beforeEach(() => {
24
- vi.stubGlobal("IS_REACT_ACT_ENVIRONMENT", true);
25
- container = document.createElement("div");
26
- document.body.append(container);
27
- root = createRoot(container);
28
- });
29
-
30
- afterEach(async () => {
31
- await act(async () => root.unmount());
32
- container.remove();
33
- vi.unstubAllGlobals();
34
- });
35
-
21
it.each(["keyup", "paste", "blur"] as const)(
22
"does not render for unchanged modifiers after %s resets the state",
23
async (reset) => {
39
- const render = vi.fn();
24
+ const onRender = vi.fn();
25
function Consumer() {
41
- render(useShortcutModifierState());
26
+ onRender(useShortcutModifierState());
27
return null;
28
}
44
- await act(async () => {
45
- root.render(createElement(Consumer));
46
- });
29
+ // The test counts the hook's renders, and the hook never reads a route.
30
+ await using _screen = await render(createElement(Consumer), { router: false });
31
const press = async (type: "keydown" | "keyup", key: string, shiftKey = false) => {
32
await act(async () => {
33
window.dispatchEvent(new KeyboardEvent(type, { key, shiftKey }));
@@ -51,7 +35,7 @@ describe("useShortcutModifierState", () => {
35
};
36
37
await press("keydown", "Shift", true);
54
- expect(render).toHaveBeenLastCalledWith({ ...emptyState(), shiftKey: true });
38
+ expect(onRender).toHaveBeenLastCalledWith({ ...emptyState(), shiftKey: true });
39
if (reset === "keyup") {
40
await press("keyup", "Shift");
41
} else {
@@ -59,8 +43,8 @@ describe("useShortcutModifierState", () => {
43
window.dispatchEvent(new Event(reset));
44
});
45
}
62
- expect(render).toHaveBeenLastCalledWith(emptyState());
63
- render.mockClear();
46
+ expect(onRender).toHaveBeenLastCalledWith(emptyState());
47
+ onRender.mockClear();
48
49
for (const key of "typing") {
50
await press("keydown", key);
@@ -70,9 +54,9 @@ describe("useShortcutModifierState", () => {
54
window.dispatchEvent(new Event("paste"));
55
window.dispatchEvent(new Event("blur"));
56
});
73
- expect(render).not.toHaveBeenCalled();
57
+ expect(onRender).not.toHaveBeenCalled();
58
await press("keydown", "Shift", true);
75
- expect(render).toHaveBeenCalledExactlyOnceWith({ ...emptyState(), shiftKey: true });
59
+ expect(onRender).toHaveBeenCalledExactlyOnceWith({ ...emptyState(), shiftKey: true });
60
},
61
);
62
});
oxlint-plugin-t3code/rules/require-disposable-render.test.ts
+91
-1
@@ -9,6 +9,9 @@ const unitTest = createOxlintRuleHarness("t3code/require-disposable-render", {
9
filename: "widget.test.tsx",
10
});
11
12
+const reportsInputInAct = (output: string) =>
13
+ assert.match(output, /Do not wrap real input \(userEvent or a locator's click\/fill\) in act/);
14
+
15
describe("t3code/require-disposable-render", () => {
16
browserTest.valid(
17
"allows the disposable helper",
@@ -19,6 +22,7 @@ describe("t3code/require-disposable-render", () => {
22
" await using screen = await render(null);",
23
" await act(() => screen.rerender(null));",
24
' await userEvent.click(screen.getByRole("button"));',
25
+ " await act(() => store.setState({ open: true }));",
26
"});",
27
].join("\n"),
28
);
@@ -44,13 +48,99 @@ describe("t3code/require-disposable-render", () => {
48
"rejects userEvent wrapped in act from react",
49
[
50
'import { act } from "react";',
51
+ 'import { userEvent } from "vite-plus/test/browser";',
52
'it("clicks", async () => {',
53
" await act(async () => {",
54
" await userEvent.click(document.body);",
55
" });",
56
"});",
57
].join("\n"),
53
- (output) => assert.match(output, /Do not wrap userEvent in React's act/),
58
+ reportsInputInAct,
59
+ );
60
+ browserTest.invalid(
61
+ "rejects userEvent wrapped in the render helper's act",
62
+ [
63
+ 'import { act } from "../../test/render";',
64
+ 'import { userEvent } from "vite-plus/test/browser";',
65
+ 'it("types", async () => {',
66
+ ' await act(() => userEvent.type(document.body, "a"));',
67
+ "});",
68
+ ].join("\n"),
69
+ reportsInputInAct,
70
+ );
71
+ browserTest.invalid(
72
+ "rejects userEvent wrapped in a renamed render helper act",
73
+ [
74
+ 'import { act as flush } from "../test/render.tsx";',
75
+ 'import { userEvent } from "vite-plus/test/browser";',
76
+ 'it("clicks", async () => {',
77
+ " await flush(async () => {",
78
+ " await userEvent.click(document.body);",
79
+ " });",
80
+ "});",
81
+ ].join("\n"),
82
+ reportsInputInAct,
83
+ );
84
+ browserTest.invalid(
85
+ "rejects a renamed userEvent wrapped in act",
86
+ [
87
+ 'import { act } from "../test/render";',
88
+ 'import { userEvent as ue } from "vite-plus/test/browser";',
89
+ 'it("clicks", async () => {',
90
+ " await act(() => ue.click(document.body));",
91
+ "});",
92
+ ].join("\n"),
93
+ reportsInputInAct,
94
+ );
95
+ browserTest.invalid(
96
+ "rejects a locator click wrapped in act",
97
+ [
98
+ 'import { act } from "../test/render";',
99
+ 'import { page } from "vite-plus/test/browser";',
100
+ 'it("clicks", async () => {',
101
+ ' await act(async () => page.getByRole("button", { name: "Save" }).nth(0).click());',
102
+ "});",
103
+ ].join("\n"),
104
+ reportsInputInAct,
105
+ );
106
+ browserTest.invalid(
107
+ "rejects React.act from a namespace import",
108
+ [
109
+ 'import * as React from "react";',
110
+ 'it("renders", async () => {',
111
+ " await React.act(async () => {});",
112
+ "});",
113
+ ].join("\n"),
114
+ (output) => assert.match(output, /import `act` from there/),
115
+ );
116
+ browserTest.invalid(
117
+ "rejects userEvent wrapped in React.act",
118
+ [
119
+ 'import * as React from "react";',
120
+ 'import { userEvent } from "vite-plus/test/browser";',
121
+ 'it("clicks", async () => {',
122
+ " await React.act(() => userEvent.click(document.body));",
123
+ "});",
124
+ ].join("\n"),
125
+ reportsInputInAct,
126
+ );
127
+ browserTest.valid(
128
+ "allows act around a DOM click and userEvent in a function act only defines",
129
+ [
130
+ 'import { act } from "../test/render";',
131
+ 'import { page, userEvent } from "vite-plus/test/browser";',
132
+ 'it("clicks", async () => {',
133
+ ' await act(async () => page.getByRole("button").element().click());',
134
+ " await act(async () => {",
135
+ " const later = () => userEvent.click(document.body);",
136
+ " store.setState({ later });",
137
+ " });",
138
+ "});",
139
+ ].join("\n"),
140
+ );
141
+ browserTest.invalid(
142
+ "rejects lifecycle hooks through a test runner namespace",
143
+ ['import * as vt from "vitest";', "vt.beforeEach(() => {});"].join("\n"),
144
);
145
browserTest.invalid(
146
"rejects importing lifecycle hooks from the test runner",
oxlint-plugin-t3code/rules/require-disposable-render.ts
+121
-26
@@ -8,14 +8,31 @@ const LIFECYCLE_HOOKS = new Set(["afterAll", "afterEach", "beforeAll", "beforeEa
8
const TEST_RUNNERS = new Set(["@effect/vitest", "vite-plus/test", "vitest"]);
9
const REACT_ACT_EXPORTS = new Set(["act", "unstable_act"]);
10
const ACT_ENVIRONMENT = "IS_REACT_ACT_ENVIRONMENT";
11
+const RENDER_HELPER = /(?:^|\/)test\/render(?:\.tsx)?$/u;
12
+const LOCATOR_QUERY = /^getBy/u;
13
+// Locator methods that dispatch real input through the browser provider.
14
+const LOCATOR_INPUT = new Set([
15
+ "clear",
16
+ "click",
17
+ "dblClick",
18
+ "dropTo",
19
+ "fill",
20
+ "hover",
21
+ "selectOptions",
22
+ "tripleClick",
23
+ "unhover",
24
+ "upload",
25
+]);
26
+// These leave the locator for a DOM element, whose click() is synthetic and fine inside act.
27
+const LOCATOR_EXITS = new Set(["element", "elements", "query"]);
28
const HELPER = "Render with `await using screen = await render(...)` from apps/web/test/render.tsx";
29
30
const MESSAGES = {
31
reactDomClient: `${HELPER}; it owns the React root and unmounts it on dispose.`,
32
reactAct: `${HELPER} and import \`act\` from there; it enables React's act environment only while act runs.`,
33
actEnvironment: `${HELPER}; its act() sets ${ACT_ENVIRONMENT} for exactly as long as it runs.`,
17
- actAroundUserEvent:
18
- "Do not wrap userEvent in React's act; real input is not an act scope. Await the userEvent call directly.",
34
+ actAroundInput:
35
+ "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.",
36
lifecycleHook:
37
"Browser tests acquire what they need with `using`/`await using` instead of lifecycle hooks, so nothing outlives the test that created it.",
38
};
@@ -23,6 +40,32 @@ const MESSAGES = {
40
const stringValue = (node: ESTree.Node | null | undefined) =>
41
node?.type === "Literal" && typeof node.value === "string" ? node.value : undefined;
42
43
+const importedName = (specifier: ESTree.ImportSpecifier) =>
44
+ specifier.imported.type === "Identifier" ? specifier.imported.name : specifier.imported.value;
45
+
46
+const isFunction = (node: ESTree.Node) =>
47
+ node.type === "ArrowFunctionExpression" ||
48
+ node.type === "FunctionExpression" ||
49
+ node.type === "FunctionDeclaration";
50
+
51
+// Walks a.b().c().d back to its root, reporting whether a getBy* query built a locator on the way
52
+// without leaving it through element()/query().
53
+const isLocatorChain = (node: ESTree.Node): boolean => {
54
+ let sawQuery = false;
55
+ for (let current: ESTree.Node | undefined = node; current;) {
56
+ if (current.type === "CallExpression") {
57
+ current = current.callee;
58
+ continue;
59
+ }
60
+ if (current.type !== "MemberExpression") break;
61
+ const name = Option.getOrUndefined(getPropertyName(current.property));
62
+ if (name !== undefined && LOCATOR_EXITS.has(name)) return false;
63
+ if (name !== undefined && LOCATOR_QUERY.test(name)) sawQuery = true;
64
+ current = current.object;
65
+ }
66
+ return sawQuery;
67
+};
68
+
69
const namesActEnvironment = (node: unknown) => {
70
const target = unwrapExpression(node);
71
if (Option.isNone(target)) return false;
@@ -44,49 +87,94 @@ export default defineRule({
87
},
88
create(context) {
89
const isBrowserTest = BROWSER_TEST_FILE.test(context.filename);
47
- const reactActNames = new Set<string>();
90
+ // Local names bound to React's act or the render helper's act.
91
+ const actNames = new Set<string>();
92
+ const reactNamespaces = new Set<string>();
93
+ const runnerNamespaces = new Set<string>();
94
+ const userEventNames = new Set<string>();
95
+
96
+ const namespaceMember = (node: ESTree.Node, namespaces: ReadonlySet<string>) =>
97
+ node.type === "MemberExpression" &&
98
+ node.object.type === "Identifier" &&
99
+ namespaces.has(node.object.name)
100
+ ? Option.getOrUndefined(getPropertyName(node.property))
101
+ : undefined;
102
+
103
+ const isReactNamespaceAct = (callee: ESTree.Node) => {
104
+ const member = namespaceMember(callee, reactNamespaces);
105
+ return member !== undefined && REACT_ACT_EXPORTS.has(member);
106
+ };
107
49
- const isInsideReactAct = (node: ESTree.Node) => {
108
+ const isActCall = (node: ESTree.Node) =>
109
+ node.type === "CallExpression" &&
110
+ ((node.callee.type === "Identifier" && actNames.has(node.callee.name)) ||
111
+ isReactNamespaceAct(node.callee));
112
+
113
+ // A function defined inside act but not passed straight to a call may run after act settles.
114
+ const isInsideAct = (node: ESTree.Node) => {
115
for (let current = node.parent; current; current = current.parent) {
116
+ if (isActCall(current)) return true;
117
if (
52
- current.type === "CallExpression" &&
53
- current.callee.type === "Identifier" &&
54
- reactActNames.has(current.callee.name)
118
+ isFunction(current) &&
119
+ !(
120
+ current.parent?.type === "CallExpression" &&
121
+ (current.parent.arguments as ReadonlyArray<ESTree.Node>).includes(current)
122
+ )
123
) {
56
- return true;
124
+ return false;
125
}
126
}
127
return false;
128
};
129
130
+ const isRealInput = (callee: ESTree.MemberExpression) => {
131
+ if (callee.object.type === "Identifier" && userEventNames.has(callee.object.name)) {
132
+ return true;
133
+ }
134
+ const method = Option.getOrUndefined(getPropertyName(callee.property));
135
+ return method !== undefined && LOCATOR_INPUT.has(method) && isLocatorChain(callee.object);
136
+ };
137
+
138
return {
139
ImportDeclaration(node) {
140
+ for (const specifier of node.specifiers) {
141
+ if (specifier.type === "ImportSpecifier" && importedName(specifier) === "userEvent") {
142
+ userEventNames.add(specifier.local.name);
143
+ }
144
+ }
145
if (isBrowserTest && TEST_RUNNERS.has(node.source.value)) {
146
for (const specifier of node.specifiers) {
147
+ if (specifier.type === "ImportNamespaceSpecifier") {
148
+ runnerNamespaces.add(specifier.local.name);
149
+ continue;
150
+ }
151
if (specifier.type !== "ImportSpecifier") continue;
67
- const imported =
68
- specifier.imported.type === "Identifier"
69
- ? specifier.imported.name
70
- : specifier.imported.value;
71
- if (LIFECYCLE_HOOKS.has(imported)) {
152
+ if (LIFECYCLE_HOOKS.has(importedName(specifier))) {
153
context.report({ node: specifier, message: MESSAGES.lifecycleHook });
154
}
155
}
156
return;
157
}
158
+ if (RENDER_HELPER.test(node.source.value)) {
159
+ for (const specifier of node.specifiers) {
160
+ if (specifier.type === "ImportSpecifier" && importedName(specifier) === "act") {
161
+ actNames.add(specifier.local.name);
162
+ }
163
+ }
164
+ return;
165
+ }
166
if (node.source.value === "react-dom/client") {
167
context.report({ node: node.source, message: MESSAGES.reactDomClient });
168
return;
169
}
170
if (node.source.value !== "react") return;
171
for (const specifier of node.specifiers) {
83
- if (specifier.type !== "ImportSpecifier") continue;
84
- const imported =
85
- specifier.imported.type === "Identifier"
86
- ? specifier.imported.name
87
- : specifier.imported.value;
88
- if (REACT_ACT_EXPORTS.has(imported)) {
89
- reactActNames.add(specifier.local.name);
172
+ if (specifier.type !== "ImportSpecifier") {
173
+ reactNamespaces.add(specifier.local.name);
174
+ continue;
175
+ }
176
+ if (REACT_ACT_EXPORTS.has(importedName(specifier))) {
177
+ actNames.add(specifier.local.name);
178
context.report({ node: specifier, message: MESSAGES.reactAct });
179
}
180
}
@@ -102,12 +190,19 @@ export default defineRule({
190
if (callee.value.type === "MemberExpression") {
191
// vi.stubGlobal("IS_REACT_ACT_ENVIRONMENT", true) leaves the flag on for the whole test.
192
const method = getPropertyName(callee.value.property);
105
- if (
106
- callee.value.object.type === "Identifier" &&
107
- callee.value.object.name === "userEvent" &&
108
- isInsideReactAct(node)
109
- ) {
110
- context.report({ node, message: MESSAGES.actAroundUserEvent });
193
+ if (isReactNamespaceAct(callee.value)) {
194
+ context.report({ node: node.callee, message: MESSAGES.reactAct });
195
+ return;
196
+ }
197
+ if (isBrowserTest) {
198
+ const hook = namespaceMember(callee.value, runnerNamespaces);
199
+ if (hook !== undefined && LIFECYCLE_HOOKS.has(hook)) {
200
+ context.report({ node: node.callee, message: MESSAGES.lifecycleHook });
201
+ return;
202
+ }
203
+ }
204
+ if (isRealInput(callee.value) && isInsideAct(node)) {
205
+ context.report({ node, message: MESSAGES.actAroundInput });
206
return;
207
}
208
if (
vite.config.ts
+1
-1
@@ -188,7 +188,7 @@ export default defineConfig({
188
rules: { "t3code/prefer-effect-fn": "off" },
189
},
190
{
191
- files: ["apps/web/**/*.test.tsx"],
191
+ files: ["apps/web/**/*.test.{ts,tsx}"],
192
rules: { "t3code/require-disposable-render": "error" },
193
},
194
{