Skip to content

Commit 3b0672c

Browse files
test(web): misc-a tests run in a real browser
Convert the misc-a group's React tests from react-test-renderer and static markup to Vitest browser mode, delete the ones that only asserted markup, and build every mock from the real module. Co-Authored-By: Claude Opus 5.5 <[email protected]>
1 parent 130f4a2 commit 3b0672c

26 files changed

Lines changed: 1514 additions & 1751 deletions

apps/web/src/browser/HostedBrowserWebview.test.tsx renamed to apps/web/src/browser/HostedBrowserWebview.browser.test.tsx

Lines changed: 49 additions & 46 deletions
Original file line numberDiff line numberDiff line change
@@ -7,7 +7,7 @@ import {
77
type DesktopPreviewBridge,
88
} from "@t3tools/contracts";
99
import { act } from "react";
10-
import { create, type ReactTestRenderer } from "react-test-renderer";
10+
import { createRoot, type Root } from "react-dom/client";
1111
import { afterEach, beforeEach, describe, expect, it, vi } from "vite-plus/test";
1212

1313
const mocks = vi.hoisted(() => ({
@@ -20,28 +20,32 @@ const mocks = vi.hoisted(() => ({
2020
activeRecordings: new Set<string>(),
2121
}));
2222

23-
vi.mock("~/localApi", () => ({
24-
ensureLocalApi: () => ({ persistence: mocks }),
25-
}));
23+
vi.mock(import("~/localApi"), async (original) => {
24+
const actual = await original();
25+
return {
26+
...actual,
27+
ensureLocalApi: () => ({ ...actual.ensureLocalApi(), persistence: mocks as never }),
28+
};
29+
});
30+
31+
vi.mock(import("./desktopTabLifetime"), { spy: true });
2632

27-
vi.mock("~/components/preview/previewBridge", () => ({
33+
// The Electron desktop bridge; a browser has none.
34+
vi.mock(import("~/components/preview/previewBridge"), async (original) => ({
35+
...(await original()),
2836
previewBridge: {
2937
createTab: mocks.createTab,
3038
closeTab: mocks.closeTab,
3139
registerWebview: mocks.registerWebview,
3240
getPreviewConfig: mocks.getPreviewConfig,
33-
},
41+
} as unknown as DesktopPreviewBridge,
3442
}));
3543

36-
vi.mock("~/components/preview/usePreviewBridge", () => ({
44+
vi.mock(import("~/components/preview/usePreviewBridge"), async (original) => ({
45+
...(await original()),
3746
usePreviewBridge: () => undefined,
3847
}));
3948

40-
vi.mock("./browserRecording", () => ({
41-
useActiveBrowserRecordingTabIds: () => mocks.activeRecordings,
42-
stopBrowserRecording: async () => null,
43-
}));
44-
4549
import {
4650
__resetClientSettingsPersistenceForTests,
4751
ensureClientSettingsHydrated,
@@ -50,7 +54,8 @@ import { useBrowserSurfaceStore } from "./browserSurfaceStore";
5054
import * as desktopTabLifetime from "./desktopTabLifetime";
5155
import { HostedBrowserWebview } from "./HostedBrowserWebview";
5256

53-
let renderer: ReactTestRenderer | undefined;
57+
let root: Root | undefined;
58+
let container: HTMLDivElement;
5459

5560
function deferred<A>() {
5661
let resolve!: (value: A) => void;
@@ -76,20 +81,16 @@ beforeEach(() => {
7681
preloadUrl: null,
7782
});
7883
vi.stubGlobal("IS_REACT_ACT_ENVIRONMENT", true);
79-
vi.stubGlobal("window", globalThis);
80-
vi.stubGlobal("navigator", { platform: "Linux" });
81-
vi.stubGlobal(
82-
"requestAnimationFrame",
83-
vi.fn(() => 0),
84-
);
85-
vi.stubGlobal("cancelAnimationFrame", vi.fn());
8684
vi.spyOn(console, "error").mockImplementation(() => undefined);
85+
container = document.createElement("div");
86+
document.body.append(container);
8787
});
8888

8989
afterEach(async () => {
9090
vi.useFakeTimers();
91-
await act(() => renderer?.unmount());
92-
renderer = undefined;
91+
await act(async () => root?.unmount());
92+
root = undefined;
93+
container.remove();
9394
await vi.advanceTimersByTimeAsync(0);
9495
vi.useRealTimers();
9596
__resetClientSettingsPersistenceForTests();
@@ -107,19 +108,31 @@ describe("HostedBrowserWebview settings hydration", () => {
107108
.mockReturnValueOnce(firstRead.promise)
108109
.mockReturnValueOnce(retryRead.promise);
109110
mocks.createTab.mockReturnValueOnce(tabCreation.promise);
110-
const acquire = vi.spyOn(desktopTabLifetime, "acquireDesktopTab");
111-
const createGuest = vi.fn((_attributes: unknown) =>
112-
Object.assign(new EventTarget(), { getWebContentsId: () => 41 }),
113-
);
111+
const acquire = vi.mocked(desktopTabLifetime.acquireDesktopTab);
112+
// Chromium treats <webview> as an unknown element; give it the one Electron method the
113+
// host calls once the guest attaches.
114+
const createElement = document.createElement.bind(document);
115+
const createGuest = vi.spyOn(document, "createElement").mockImplementation(((
116+
tagName: string,
117+
options?: ElementCreationOptions,
118+
) => {
119+
const element = createElement(tagName, options);
120+
return tagName === "webview"
121+
? Object.assign(element, { getWebContentsId: () => 41 })
122+
: element;
123+
}) as typeof document.createElement);
124+
const guests = () => createGuest.mock.calls.filter(([tagName]) => tagName === "webview");
125+
const guest = () => container.querySelector("webview");
114126
const threadRef = {
115127
environmentId: EnvironmentId.make("host-settings-retry"),
116128
threadId: ThreadId.make("thread-settings-retry"),
117129
};
118130
const runtimeTabId = "retained-background-tab";
119131
useBrowserSurfaceStore.getState().acquireActivity(runtimeTabId);
120132

121-
await act(() => {
122-
renderer = create(
133+
root = createRoot(container);
134+
await act(async () =>
135+
root!.render(
123136
<HostedBrowserWebview
124137
threadRef={threadRef}
125138
tabId="server-tab"
@@ -130,18 +143,12 @@ describe("HostedBrowserWebview settings hydration", () => {
130143
profileId="work"
131144
zoomFactor={1.25}
132145
/>,
133-
{
134-
createNodeMock: (element) =>
135-
element.type === "webview"
136-
? createGuest(element.props)
137-
: { scrollLeft: 0, scrollTop: 0, scrollTo: () => undefined },
138-
},
139-
);
140-
});
146+
),
147+
);
141148

142149
expect(mocks.getClientSettings).toHaveBeenCalledOnce();
143150
expect(acquire).not.toHaveBeenCalled();
144-
expect(createGuest).not.toHaveBeenCalled();
151+
expect(guest()).toBeNull();
145152
expect(mocks.createTab).not.toHaveBeenCalled();
146153

147154
const failure = new Error("Saved settings are unavailable");
@@ -151,7 +158,7 @@ describe("HostedBrowserWebview settings hydration", () => {
151158
await expect(hydration).rejects.toBe(failure);
152159
});
153160
expect(acquire).not.toHaveBeenCalled();
154-
expect(createGuest).not.toHaveBeenCalled();
161+
expect(guest()).toBeNull();
155162
expect(mocks.createTab).not.toHaveBeenCalled();
156163

157164
let retry!: Promise<void>;
@@ -160,7 +167,7 @@ describe("HostedBrowserWebview settings hydration", () => {
160167
});
161168
expect(mocks.getClientSettings).toHaveBeenCalledTimes(2);
162169
expect(acquire).not.toHaveBeenCalled();
163-
expect(createGuest).not.toHaveBeenCalled();
170+
expect(guest()).toBeNull();
164171
expect(mocks.createTab).not.toHaveBeenCalled();
165172

166173
await act(async () => {
@@ -176,13 +183,9 @@ describe("HostedBrowserWebview settings hydration", () => {
176183

177184
expect(acquire).toHaveBeenCalledExactlyOnceWith(runtimeTabId, undefined);
178185
expect(mocks.getPreviewConfig).toHaveBeenCalledExactlyOnceWith(threadRef.environmentId, "work");
179-
expect(createGuest).toHaveBeenCalledOnce();
180-
expect(createGuest).toHaveBeenCalledWith(
181-
expect.objectContaining({
182-
partition: "persist:t3-preview-work",
183-
src: "https://example.com",
184-
}),
185-
);
186+
expect(guests()).toHaveLength(1);
187+
expect(guest()?.getAttribute("partition")).toBe("persist:t3-preview-work");
188+
expect(guest()?.getAttribute("src")).toBe("https://example.com");
186189
expect(mocks.createTab).toHaveBeenCalledExactlyOnceWith(runtimeTabId, {
187190
zoomFactor: 1.25,
188191
colorScheme: "dark",

apps/web/src/cloud/useCloudLinkController.test.tsx renamed to apps/web/src/cloud/useCloudLinkController.browser.test.tsx

Lines changed: 47 additions & 26 deletions
Original file line numberDiff line numberDiff line change
@@ -7,7 +7,7 @@ import {
77
import type { RelayManagedEndpointProviderKind } from "@t3tools/contracts/relay";
88
import { AsyncResult } from "effect/reactivity";
99
import { act, useLayoutEffect } from "react";
10-
import { create, type ReactTestRenderer } from "react-test-renderer";
10+
import { createRoot, type Root } from "react-dom/client";
1111
import { afterEach, beforeEach, describe, expect, it, vi } from "vite-plus/test";
1212

1313
const testState = vi.hoisted(() => ({
@@ -24,8 +24,9 @@ const testState = vi.hoisted(() => ({
2424
toast: vi.fn(),
2525
}));
2626

27-
vi.mock("@effect/atom-react", () => ({
28-
useAtomValue: () => ({
27+
vi.mock(import("@effect/atom-react"), async (original) => ({
28+
...(await original()),
29+
useAtomValue: (() => ({
2930
environments: new Map(
3031
testState.relayProviderKind === null
3132
? []
@@ -36,35 +37,56 @@ vi.mock("@effect/atom-react", () => ({
3637
],
3738
],
3839
),
39-
}),
40+
})) as never,
4041
}));
41-
vi.mock("@clerk/react", () => ({
42-
useAuth: () => ({ getToken: testState.getToken, isSignedIn: true }),
42+
vi.mock(import("@clerk/react"), async (original) => ({
43+
...(await original()),
44+
useAuth: (() => ({ getToken: testState.getToken, isSignedIn: true })) as never,
4345
}));
44-
vi.mock("../components/ui/toast", () => ({ toastManager: { add: testState.toast } }));
45-
vi.mock("../state/relay", () => ({
46-
relayEnvironmentDiscovery: { refresh: testState.refreshDiscovery, stateValueAtom: {} },
46+
vi.mock(import("../components/ui/toast"), async (original) => {
47+
const actual = await original();
48+
return { ...actual, toastManager: { ...actual.toastManager, add: testState.toast } as never };
49+
});
50+
vi.mock(import("../state/relay"), async (original) => {
51+
const actual = await original();
52+
return {
53+
...actual,
54+
relayEnvironmentDiscovery: {
55+
...actual.relayEnvironmentDiscovery,
56+
refresh: testState.refreshDiscovery,
57+
} as never,
58+
};
59+
});
60+
vi.mock(import("../state/session"), async (original) => ({
61+
...(await original()),
62+
readEnvironmentScope: (_environmentId, scope) => testState.scopes.has(scope),
4763
}));
48-
vi.mock("../state/session", () => ({
49-
readEnvironmentScope: (_environmentId: string, scope: string) => testState.scopes.has(scope),
64+
vi.mock(import("../state/use-atom-command"), async (original) => ({
65+
...(await original()),
66+
useAtomCommand: ((command: unknown) => command) as never,
5067
}));
51-
vi.mock("../state/use-atom-command", () => ({ useAtomCommand: (command: unknown) => command }));
52-
vi.mock("./linkEnvironmentAtoms", () => ({
53-
linkPrimaryEnvironment: testState.link,
54-
unlinkPrimaryEnvironment: testState.unlink,
55-
updatePrimaryEnvironmentPreferences: testState.preferences,
68+
vi.mock(import("./linkEnvironmentAtoms"), async (original) => ({
69+
...(await original()),
70+
linkPrimaryEnvironment: testState.link as never,
71+
unlinkPrimaryEnvironment: testState.unlink as never,
72+
updatePrimaryEnvironmentPreferences: testState.preferences as never,
5673
}));
57-
vi.mock("./primaryCloudLinkState", () => ({
74+
vi.mock(import("./primaryCloudLinkState"), async (original) => ({
75+
...(await original()),
5876
readCachedPrimaryCloudLinkState: () => testState.snapshot,
59-
usePrimaryCloudLinkState: () => ({
77+
usePrimaryCloudLinkState: (() => ({
6078
target,
6179
data: testState.renderedSnapshot,
6280
error: null,
6381
isPending: false,
6482
refresh: testState.refreshLink,
65-
}),
83+
})) as never,
84+
}));
85+
// The Clerk JWT template is build-time config the test environment does not set.
86+
vi.mock(import("./publicConfig"), async (original) => ({
87+
...(await original()),
88+
resolveRelayClerkTokenOptions: () => ({}) as never,
6689
}));
67-
vi.mock("./publicConfig", () => ({ resolveRelayClerkTokenOptions: () => ({}) }));
6890

6991
import { useCloudLinkController, type CloudLinkDesiredState } from "./useCloudLinkController";
7092

@@ -83,7 +105,7 @@ const linkedState: EnvironmentCloudLinkStateResult = {
83105
publishAgentActivity: false,
84106
};
85107

86-
let renderer: ReactTestRenderer | null = null;
108+
let root: Root | null = null;
87109
let controller: ReturnType<typeof useCloudLinkController> | null = null;
88110

89111
function ControllerProbe() {
@@ -95,9 +117,8 @@ function ControllerProbe() {
95117
}
96118

97119
async function mountController() {
98-
await act(() => {
99-
renderer = create(<ControllerProbe />);
100-
});
120+
root = createRoot(document.createElement("div"));
121+
await act(async () => root!.render(<ControllerProbe />));
101122
}
102123

103124
async function reconcile(desired: CloudLinkDesiredState) {
@@ -136,8 +157,8 @@ beforeEach(() => {
136157
});
137158

138159
afterEach(async () => {
139-
await act(() => renderer?.unmount());
140-
renderer = null;
160+
await act(async () => root?.unmount());
161+
root = null;
141162
controller = null;
142163
vi.restoreAllMocks();
143164
vi.unstubAllGlobals();

0 commit comments

Comments
 (0)