diff --git a/tests/setup.ts b/tests/setup.ts index 1272638d..87feb00f 100644 --- a/tests/setup.ts +++ b/tests/setup.ts @@ -1,19 +1,28 @@ -import "@testing-library/jest-dom/vitest"; -import { cleanup, configure } from "@testing-library/react"; import { afterEach, vi } from "vitest"; -// findBy*/waitFor settle on the DOM change itself; their deadline only reports -// a hang. Routes render through React.lazy, and React 19 holds every Suspense -// reveal on a real 300ms timer (FALLBACK_THROTTLE_MS). A route entered through -// a context table and then a lazy page spends 600ms of the 1s default before -// any rendering work, so on a loaded host the default turns into a speed -// requirement. Fake timers cannot shorten it: Testing Library advances only -// Jest's fake timers, and MSW and user-event run on the real clock. Half the -// 10s test timeout still reports a real hang with the DOM dump. -configure({ asyncUtilTimeout: 5_000 }); +// Testing Library and its matchers need a DOM. Most test files run in Node +// (tests/unit has over 200, three of them with jsdom), and importing React DOM +// and Testing Library into every one of them was the largest part of the +// suite's setup time. They load only where the file's environment has a DOM. +async function loadDomTesting(): Promise<() => void> { + await import("@testing-library/jest-dom/vitest"); + const { cleanup, configure } = await import("@testing-library/react"); + // findBy*/waitFor settle on the DOM change itself; their deadline only reports + // a hang. Routes render through React.lazy, and React 19 holds every Suspense + // reveal on a real 300ms timer (FALLBACK_THROTTLE_MS). A route entered through + // a context table and then a lazy page spends 600ms of the 1s default before + // any rendering work, so on a loaded host the default turns into a speed + // requirement. Fake timers cannot shorten it: Testing Library advances only + // Jest's fake timers, and MSW and user-event run on the real clock. Half the + // 10s test timeout still reports a real hang with the DOM dump. + configure({ asyncUtilTimeout: 5_000 }); + return cleanup; +} + +const cleanup = typeof document === "undefined" ? undefined : await loadDomTesting(); afterEach(() => { - cleanup(); + cleanup?.(); // A test that fails before its own vi.useRealTimers() must not leave fake // timers to the next test in the file. vi.useRealTimers();