Open History to see the last commit
1import {
2 createMemoryHistory,
3 createRootRoute,
4 createRouter,
5 RouterProvider,
6 type AnyRouter,
7} from "@tanstack/react-router";
8import { getTranslationsSnapshot, GTProvider } from "gt-react";
9import { act as reactAct, createContext, use, type ReactNode } from "react";
10import { createRoot } from "react-dom/client";
11import { vi } from "vite-plus/test";
12import { page, utils, type Locator, type LocatorSelectors } from "vite-plus/test/browser";
13
14import { DEFAULT_LOCALE } from "../src/i18n/locales";
15
16declare global {
17 var IS_REACT_ACT_ENVIRONMENT: boolean | undefined;
18}
19
20// React warns about every update outside act() while this flag is on, and a real
21// browser drives updates from userEvent, timers and network that act() cannot wrap.
22// So it is on only while act() runs, and nested calls restore the outer value.
23export async function act<T>(callback: () => T | Promise<T>): Promise<T> {
24 const previous = globalThis.IS_REACT_ACT_ENVIRONMENT;
25 globalThis.IS_REACT_ACT_ENVIRONMENT = true;
26 try {
27 return await reactAct(async () => await callback());
28 } finally {
29 globalThis.IS_REACT_ACT_ENVIRONMENT = previous;
30 }
31}
32
33export interface RenderOptions {
34 /**
35 * Element to render into, for tests that size or style it before the first render.
36 * The screen owns it from then on and removes it on dispose.
37 */
38 readonly container?: HTMLElement;
39 /** Initial location of the test router, or `false` to render without one. */
40 readonly router?: string | false;
41 /**
42 * The language GT renders, from the app's catalogs. `false` for a test that mounts the app's
43 * own I18nProvider: GT's providers do not nest.
44 */
45 readonly locale?: string | false;
46}
47
48/** Queries are scoped to the container; use `page` for portals such as menus and dialogs. */
49export interface Screen extends LocatorSelectors, AsyncDisposable {
50 readonly container: HTMLElement;
51 readonly locator: Locator;
52 readonly router: AnyRouter | undefined;
53 readonly rerender: (ui: ReactNode) => Promise<void>;
54 /** Unmounts early, to test cleanup effects. Dispose still removes the container. */
55 readonly unmount: () => Promise<void>;
56}
57
58const RoutedUi = createContext<ReactNode>(null);
59
60function RoutedUiOutlet() {
61 return use(RoutedUi);
62}
63
64// Links and navigation hooks need a router even when the test is not about routing.
65function createTestRouter(path: string): AnyRouter {
66 return createRouter({
67 routeTree: createRootRoute({ component: RoutedUiOutlet }),
68 history: createMemoryHistory({ initialEntries: [path] }),
69 // The router's error UI would otherwise turn a crash into a passing negative assertion.
70 disableGlobalCatchBoundary: true,
71 });
72}
73
74/**
75 * Renders `ui` for one test. Acquire it with `await using` so the tree unmounts and the
76 * container and router go away when the test ends, pass or fail.
77 */
78export async function render(
79 ui: ReactNode,
80 {
81 container = document.createElement("div"),
82 router: path = "/",
83 locale = DEFAULT_LOCALE,
84 }: RenderOptions = {},
85): Promise<Screen> {
86 if (!container.isConnected) document.body.append(container);
87 const root = createRoot(container);
88 const router = path === false ? undefined : createTestRouter(path);
89 // The router element is created once so a rerender updates the tree instead of remounting it.
90 const routerElement = router && <RouterProvider router={router} />;
91 // Loaded first, so GT's provider renders the language at once instead of its fallback.
92 if (locale !== false) await getTranslationsSnapshot(locale);
93 const wrap = (node: ReactNode) => {
94 const routed = routerElement ? <RoutedUi value={node}>{routerElement}</RoutedUi> : node;
95 // GT's hooks need its provider, as in the app.
96 return locale === false ? routed : <GTProvider locale={locale}>{routed}</GTProvider>;
97 };
98
99 let mounted = true;
100 const unmount = async () => {
101 if (!mounted) return;
102 mounted = false;
103 await act(() => root.unmount());
104 };
105 const screen: Screen = {
106 ...utils.getElementLocatorSelectors(container),
107 container,
108 locator: page.elementLocator(container),
109 router,
110 rerender: (next) => act(() => root.render(wrap(next))),
111 unmount,
112 async [Symbol.asyncDispose]() {
113 try {
114 await unmount();
115 } finally {
116 container.remove();
117 }
118 },
119 };
120
121 try {
122 await screen.rerender(ui);
123 } catch (error) {
124 await screen[Symbol.asyncDispose]();
125 throw error;
126 }
127 return screen;
128}
129
130/** Fake timers for one test: `using _timers = fakeTimers()`. */
131export function fakeTimers(config?: Parameters<typeof vi.useFakeTimers>[0]): Disposable {
132 vi.useFakeTimers(config);
133 return { [Symbol.dispose]: () => void vi.useRealTimers() };
134}
135
136/** Replaces one global for one test and restores exactly that global on dispose. */
137export function stubGlobal(name: string, value: unknown): Disposable {
138 const original = Object.getOwnPropertyDescriptor(globalThis, name);
139 Object.defineProperty(globalThis, name, {
140 value,
141 configurable: true,
142 enumerable: true,
143 writable: true,
144 });
145 return {
146 [Symbol.dispose]() {
147 if (original) Object.defineProperty(globalThis, name, original);
148 else Reflect.deleteProperty(globalThis, name);
149 },
150 };
151}