Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 2 additions & 2 deletions apps/app/src/components/dialogs/ProjectPathDialog.test.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -92,7 +92,7 @@ describe("ProjectPathDialog machine selection", () => {
);
});

it("preserves the direct single-machine folder flow", () => {
it("preserves the direct single-machine folder flow", async () => {
const onSubmit = vi.fn();
render(
<ProjectPathDialog
Expand All @@ -108,7 +108,7 @@ describe("ProjectPathDialog machine selection", () => {

expect(screen.queryByRole("button", { name: "Machine" })).toBeNull();
fireEvent.click(
screen.getByRole("button", { name: "Choose folder on host_atum" }),
await screen.findByRole("button", { name: "Choose folder on host_atum" }),
);
fireEvent.click(screen.getByRole("button", { name: "Add project" }));

Expand Down
3 changes: 2 additions & 1 deletion apps/app/src/components/secondary-panel/FilePreview.test.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -1074,7 +1074,7 @@ describe("FilePreview", () => {
expect(screen.getByRole("alert").textContent).toBe("Failed to load file");
});

it("renders .htm files with the existing Preview and Raw controls", () => {
it("renders .htm files with the existing Preview and Raw controls", async () => {
const path = "reports/report.HTM";
const url = "/preview/reports/report.HTM";
const view = render(
Expand Down Expand Up @@ -1104,6 +1104,7 @@ describe("FilePreview", () => {
expect(
screen.getByRole("button", { name: "Raw" }).getAttribute("aria-pressed"),
).toBe("true");
await settleLazyModules();
expect(
view.container.querySelector("diffs-container")?.shadowRoot?.textContent,
).toBe("<!doctype html><h1>Report</h1>");
Expand Down
3 changes: 3 additions & 0 deletions apps/app/src/lib/define-split.test.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,9 @@ import { afterEach, expect, it, vi } from "vitest";
import { downloadSplit } from "./split-prefetch";
import { defineSplit } from "./define-split";

vi.unmock("react");
vi.unmock("./define-split");

afterEach(() => {
cleanup();
vi.restoreAllMocks();
Expand Down
63 changes: 62 additions & 1 deletion apps/app/src/test/lazy-modules.test.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,8 @@

import { cleanup, render, screen } from "@testing-library/react";
import { lazy, Suspense, type ComponentType } from "react";
import { afterEach, expect, it, vi } from "vitest";
import { afterEach, describe, expect, it, vi } from "vitest";
import { defineSplit } from "@/lib/define-split";
import { settleLazyModules } from "./lazy-modules";

afterEach(cleanup);
Expand Down Expand Up @@ -80,3 +81,63 @@ it("lets findBy wait for an import that starts a microtask after render and outl

expect(await screen.findByText("Slow")).toBeTruthy();
});

const CachedSplit = defineSplit<{ label: string }>({
id: "lazy-modules-test-cached",
load: () =>
trackedImport(({ label }: { label: string }) => <p>{label}</p>, "./Cached"),
loading: () => <p>Loading cached</p>,
tier: "intent",
});

const PreparedSplit = defineSplit<{ label: string }>({
id: "lazy-modules-test-prepared",
load: () =>
trackedImport(
({ label }: { label: string }) => <p>{label}</p>,
"./Prepared",
),
loading: () => <p>Loading prepared</p>,
tier: "intent",
});

const CachedLazy = lazy(() =>
trackedImport({ default: () => <p>Lazy ready</p> }, "./CachedLazy"),
);

await PreparedSplit.preload();

describe("modules loaded before the current test", { shuffle: false }, () => {
it("loads a split and a lazy component in one test", async () => {
render(<CachedSplit label="First" />);
render(
<Suspense fallback={<p>Loading lazy</p>}>
<CachedLazy />
</Suspense>,
);
expect(await screen.findByText("First")).toBeTruthy();
expect(await screen.findByText("Lazy ready")).toBeTruthy();
render(<CachedSplit label="Same test" />);
expect(screen.getByText("Same test")).toBeTruthy();
});

it("holds an already-loaded split and lazy component until this test settles", async () => {
render(<CachedSplit label="Second" />);
render(
<Suspense fallback={<p>Loading lazy</p>}>
<CachedLazy />
</Suspense>,
);
expect(screen.getByText("Loading cached")).toBeTruthy();
expect(screen.getByText("Loading lazy")).toBeTruthy();

await settleLazyModules();
expect(screen.getByText("Second")).toBeTruthy();
expect(screen.getByText("Lazy ready")).toBeTruthy();
});

it("renders a split the file preloaded during collection immediately", () => {
render(<PreparedSplit label="Prepared" />);
expect(screen.getByText("Prepared")).toBeTruthy();
});
});
147 changes: 141 additions & 6 deletions apps/app/src/test/lazy-modules.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,7 @@
import { setImmediate as realSetImmediate } from "node:timers";
import type * as React from "react";
import type { ComponentType } from "react";
import { afterEach, beforeEach } from "vitest";

interface HeldImport {
specifier: string;
Expand All @@ -10,6 +13,11 @@ interface LazyImportState {
held: HeldImport[];
inFlight: Map<Promise<void>, string>;
unsettled: string[];
started: number;
generation: number;
collecting: boolean;
prepared: Set<unknown>;
renderGates: Map<unknown, React.ElementType>;
}

const SETTLING_WRAPPER = Symbol.for("bb.settleLazyModulesBeforeWaiting");
Expand All @@ -28,12 +36,18 @@ function lazyImportState(): LazyImportState {
held: [],
inFlight: new Map(),
unsettled: [],
started: 0,
generation: 0,
collecting: true,
prepared: new Set(),
renderGates: new Map(),
};
return globalThis.__bbLazyImportState;
}

function trackLazyImport<T>(load: Promise<T>, specifier: string): Promise<T> {
const state = lazyImportState();
state.started += 1;
let loaded = load;
if (state.holding) {
let release = () => {};
Expand All @@ -52,6 +66,44 @@ function trackLazyImport<T>(load: Promise<T>, specifier: string): Promise<T> {
return loaded;
}

function lazyModuleGeneration(): number {
return lazyImportState().generation;
}

function gatedLazyComponent<P extends object>(
key: unknown,
specifier: string,
loadedGeneration: number,
View: ComponentType<P>,
lazy: typeof React.lazy,
): React.ElementType<P> {
const state = lazyImportState();
const existing = state.renderGates.get(key);
if (existing !== undefined) return existing as React.ElementType<P>;
const chosen: React.ElementType<P> =
state.holding &&
loadedGeneration < state.generation &&
!state.prepared.has(key)
? (() => {
const gate = trackLazyImport(Promise.resolve(), specifier);
return lazy(() => gate.then(() => ({ default: View })));
})()
: View;
state.renderGates.set(key, chosen as React.ElementType);
return chosen;
}

function beginLazyModuleTestFile(): void {
const state = lazyImportState();
state.collecting = true;
state.prepared.clear();
}

export function prepareLazyModuleForFile(key: string): void {
const state = lazyImportState();
if (state.collecting) state.prepared.add(key);
}

function releaseHeldImports(state: LazyImportState): void {
for (const held of state.held.splice(0)) held.release();
}
Expand All @@ -66,12 +118,15 @@ async function reactAct(run: () => Promise<void>): Promise<void> {
}

async function settleTrackedImports(state: LazyImportState): Promise<void> {
let started: number;
do {
started = state.started;
await reactAct(async () => {
await Promise.all([...state.inFlight.keys()]);
await nextMacrotask();
});
} while (state.inFlight.size > 0);
await nextMacrotask();
} while (state.inFlight.size > 0 || state.started !== started);
}

async function whileImportsFlow<T>(run: () => Promise<T>): Promise<T> {
Expand Down Expand Up @@ -103,11 +158,11 @@ export async function settleLazyModules<T>(
});
}

export function installLazyImportTracking(): void {
function installLazyImportTracking(): void {
globalThis.__bbTrackLazyImport = trackLazyImport;
}

export async function settleLazyModulesBeforeWaiting(): Promise<void> {
async function settleLazyModulesBeforeWaiting(): Promise<void> {
const { configure, getConfig } = await import("@testing-library/react");
const { asyncWrapper } = getConfig();
if (Reflect.get(asyncWrapper, SETTLING_WRAPPER) === true) return;
Expand All @@ -121,10 +176,13 @@ export async function settleLazyModulesBeforeWaiting(): Promise<void> {
configure({ asyncWrapper: settlingWrapper });
}

export function holdLazyImports(): void {
function holdLazyImports(): void {
const state = lazyImportState();
state.unsettled = [];
state.inFlight.clear();
state.renderGates.clear();
state.generation += 1;
state.collecting = false;
state.holding = true;
}

Expand All @@ -138,14 +196,91 @@ function describeUnsettled(state: LazyImportState): string[] {
];
}

export function releaseLazyImports(): void {
function releaseLazyImports(): void {
const state = lazyImportState();
state.holding = false;
state.unsettled = describeUnsettled(state);
releaseHeldImports(state);
}

export function unsettledLazyImports(): readonly string[] {
function unsettledLazyImports(): readonly string[] {
const state = lazyImportState();
return state.holding ? describeUnsettled(state) : state.unsettled;
}

let reactModule: typeof React | undefined;

function loadedReact(): typeof React {
if (reactModule === undefined) {
throw new Error(
"gateLoadedComponent rendered before installLazyModuleHold() loaded React",
);
}
return reactModule;
}

const UNSETTLED_HINT =
"A lazy import resolves when the test awaits settleLazyModules() from @/test/lazy-modules or a Testing Library findBy/waitFor; synchronous assertions after the render or interaction that starts it see the loading state.";

export function installLazyModuleHold(): void {
installLazyImportTracking();
beginLazyModuleTestFile();
beforeEach(async (context) => {
reactModule ??= await import("react");
await settleLazyModulesBeforeWaiting();
holdLazyImports();
context.onTestFailed(({ task }) => {
const unsettled = unsettledLazyImports();
const [error] = task.result?.errors ?? [];
if (unsettled.length === 0 || error === undefined) return;
error.message += `\n\nLazy imports had not settled when this test failed: ${unsettled.join(", ")}. ${UNSETTLED_HINT}`;
});
});
afterEach(() => {
releaseLazyImports();
});
}

export function gateLoadedComponent<P extends object>(
key: string,
View: ComponentType<P>,
): ComponentType<P> {
const loadedIn = lazyModuleGeneration();
function GatedLoadedComponent(props: P) {
const react = loadedReact();
const Gated = gatedLazyComponent(key, key, loadedIn, View, react.lazy);
return react.createElement(Gated, props);
}
return GatedLoadedComponent;
}

export function gateReactLazy<R extends typeof React>(react: R): R {
reactModule = react;
const lazy: typeof react.lazy = (load) => {
let resolvedIn: number | null = null;
const Inner: React.ElementType = react.lazy(() =>
load().then((module) => {
resolvedIn ??= lazyModuleGeneration();
return module;
}),
);
function LazyContent(props: object) {
return react.createElement(Inner, props);
}
function GatedLazy(props: object) {
const View =
resolvedIn === null
? LazyContent
: gatedLazyComponent(
load,
"React.lazy",
resolvedIn,
LazyContent,
react.lazy,
);
return react.createElement(View, props);
}
return GatedLazy as never;
};
return { ...react, lazy, default: { ...react, lazy } };
}
Loading
Loading