Skip to content

Commit fcc44a0

Browse files
committed
refactor(testing): renderRoute hydrate models the root marker; shared e2e body (#992)
renderRoute({ hydrate: true }) now sets data-hydrated on <html> after hydration, as production's root does from its effect (browser/rsc-router.tsx), and removes it on unmount. A <Suspense> boundary hydrates in a later pass than the tree above it, so a reader inside one is late by structure and no test sets the attribute. The #992 regression test through the primitive is that structural case, StrictMode on and off; on main's hook it reports "Hydration failed because the server rendered text didn't match the client". The hydrate plumbing is plain locals with one return per mode, and the RTL capability check and getConfig read live in the hydrate branch. withoutBrowserGlobals is written for its two globals. The option's JSDoc states the fidelity limit: a hook that reads a global that stays defined in the server pass (history, localStorage, navigator) outside a server snapshot renders the same in both passes and can still mismatch in real SSR. E2E: the late-Suspense body moves to @shared/e2e (expectLateSuspenseReaderHydratesClean) and uses guardHydrationErrors. Both apps' fixtures hold the boundary's server content under a :gate until the test releases it (GET <page>/:gate/release), after it has seen the root hydrate with the fallback still on screen, so "the boundary hydrates after the root" is asserted instead of left to a 500 ms timer. The held render polls a release count with a 15 s safety timeout. Also carries the CHANGELOG entries for #1017 and the comment update in location-state-hydration.test.tsx.
1 parent ffe3e00 commit fcc44a0

19 files changed

Lines changed: 394 additions & 318 deletions

‎packages/rangojs-router/CHANGELOG.md‎

Lines changed: 58 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,64 @@
22

33
## Unreleased
44

5+
### Fixed: `useLocationState` no longer causes a hydration mismatch when its reader hydrates inside `<Suspense>` ([#1017](https://github.com/rangojs/rango/pull/1017))
6+
7+
After a reload or a back/forward navigation, `history.state` still holds the
8+
location state. The server cannot see it and renders the reader with
9+
`undefined`. A reader at the top of the tree hydrated with `undefined` too and
10+
picked the stored value up afterwards. A reader inside a `<Suspense>` boundary
11+
that hydrated after the root did not: its hydrating render returned the stored
12+
value, React reported a mismatch (`Minified React error #418` in production)
13+
and re-rendered the boundary on the client (#992).
14+
15+
Every hydrating render of `useLocationState` now returns `undefined`, wherever
16+
the reader sits, and the stored value appears on the next render.
17+
18+
| Reader | Hydrating render before | Hydrating render now |
19+
| -------------------------------------------------- | ----------------------- | -------------------- |
20+
| Hydrates with the root | `undefined` | unchanged |
21+
| Inside a `<Suspense>` that hydrates after the root | the stored value | `undefined` |
22+
| Mounted on the client (a navigation, not a reload) | the stored value | unchanged |
23+
24+
Nothing to change in app code. A late-hydrating reader takes one extra render,
25+
as readers that hydrate with the root always did. Flash state behaves the same
26+
way and is still cleared after it is read once.
27+
28+
### Added: `renderRoute({ hydrate: true })` hydrates the tree instead of mounting it ([#1017](https://github.com/rangojs/rango/pull/1017))
29+
30+
`renderRoute` from `@rangojs/router/testing/dom` mounted with `createRoot`, so
31+
a test could not see what a hook renders on the server or while hydrating. With
32+
`hydrate: true` it renders the same element to HTML first, puts that HTML in
33+
the container, and hydrates it. The result gains `serverHtml` and
34+
`recoverableErrors`, the hydration errors React reported:
35+
36+
```tsx
37+
const { serverHtml, recoverableErrors, getByTestId } = await renderRoute(
38+
[{ path: "/grid", Component: Grid }],
39+
{ hydrate: true, locationState: [[GridState, { count: 3 }]] },
40+
);
41+
expect(serverHtml).toContain(">0<"); // the server never sees history.state
42+
expect(recoverableErrors).toEqual([]); // no hydration mismatch
43+
expect(getByTestId("count").textContent).toBe("3");
44+
```
45+
46+
- The server pass runs with `window` and `document` removed, so a
47+
`typeof window` branch takes its server side.
48+
- Hydrate mode sets `data-hydrated` on `<html>` in an effect, as the production
49+
root does, and removes it on unmount. A `<Suspense>` boundary that hydrates
50+
in a later pass is therefore "late" the way it is in a real document.
51+
- A global that stays defined in the server pass (`history`, `localStorage`,
52+
`navigator`) reads the same in both passes. A hook that reads one outside a
53+
server snapshot can pass here and still mismatch in real SSR.
54+
- Content that suspends in the server pass is emitted as its `<Suspense>`
55+
fallback and client-rendered; React reports that in `recoverableErrors`.
56+
- An attribute-only mismatch is not a recoverable error. React keeps the
57+
server attribute and only logs it.
58+
- It needs `@testing-library/react` 16.2.0 or later and throws on older
59+
versions, which do not report hydration errors.
60+
61+
Without `hydrate` nothing changes.
62+
563
### Fixed: a partial request ignores a `Referer` from another origin as its navigation context ([#1019](https://github.com/rangojs/rango/pull/1019))
664

765
A partial (navigation) request tells the server which page it is leaving. The

‎packages/rangojs-router/docs/internal/feature-map.md‎

Lines changed: 12 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -59,12 +59,18 @@ reachable through the public DOM primitive (#992: `useLocationState` inside a
5959
late-hydrating Suspense boundary). It renders the same element to HTML with
6060
`react-dom/server`'s `renderToString`, with `window` and `document` deleted for
6161
that synchronous pass so `typeof window` branches take their server side, then
62-
hydrates the container through RTL's `render({ hydrate: true })`. The result is
63-
a `RenderRouteHydrateResult`: `serverHtml`, plus `recoverableErrors`, the
64-
messages React passed to `onRecoverableError` (where a hydration mismatch
65-
arrives). Content that suspends in the server pass is client-rendered and
66-
reported there, not hydrated. Needs `@testing-library/react` 16.2.0 or newer;
67-
`renderRoute` throws on older versions, which drop `onRecoverableError`.
62+
hydrates the container through RTL's `render({ hydrate: true })`. It also sets
63+
`data-hydrated` on `<html>` after hydration, as the production root does
64+
(`browser/rsc-router.tsx`), so a `<Suspense>` boundary hydrates late by
65+
structure. The result is a `RenderRouteHydrateResult`: `serverHtml`, plus
66+
`recoverableErrors`, the messages React passed to `onRecoverableError` (where a
67+
hydration mismatch arrives). Content that suspends in the server pass is
68+
client-rendered and reported there, not hydrated. The fidelity limit: only
69+
`window` and `document` are removed, so a hook that reads `history`,
70+
`localStorage` or `navigator` outside a server snapshot renders the same in both
71+
passes and can still mismatch in real SSR. Needs `@testing-library/react` 16.2.0
72+
or newer; `renderRoute` throws on older versions, which drop
73+
`onRecoverableError`.
6874

6975
`renderRoute`'s `router.navigate(url, { loaders })` seeds loader data for that
7076
one navigation (merged over the render-time seeds), and `RenderRouteSpec`

‎packages/rangojs-router/docs/testing.md‎

Lines changed: 25 additions & 18 deletions
Original file line numberDiff line numberDiff line change
@@ -692,36 +692,43 @@ message of every error React recovered from. A hydration mismatch is exactly
692692
such an error, so an empty array is your "it hydrated as rendered" assertion.
693693

694694
```tsx
695-
afterEach(() => {
696-
cleanup();
697-
document.documentElement.removeAttribute("data-hydrated");
698-
});
695+
// A <Suspense> boundary hydrates after the root has marked the page hydrated,
696+
// as a streamed boundary does in production.
697+
function GridPage() {
698+
return (
699+
<Suspense fallback={null}>
700+
<Grid />
701+
</Suspense>
702+
);
703+
}
699704

700705
it("hydrates as the server rendered it, then shows the stored count", async () => {
701-
// Rango's root sets data-hydrated from its first effect, and a streamed
702-
// <Suspense> boundary hydrates after that. Set up front, it makes this
703-
// hydration render the late one.
704-
document.documentElement.setAttribute("data-hydrated", "");
705706
const { serverHtml, recoverableErrors, getByTestId } = await renderRoute(
706-
[{ path: "/grid", Component: Grid }],
707+
[{ path: "/grid", Component: GridPage }],
707708
{ hydrate: true, locationState: [[GridState, { count: 3 }]] },
708709
);
709-
expect(serverHtml).toBe('<p data-testid="count">0</p>'); // no history.state on the server
710+
expect(serverHtml).toContain('<p data-testid="count">0</p>'); // no history.state on the server
710711
expect(recoverableErrors).toEqual([]); // the first client render matched it
711712
expect(getByTestId("count").textContent).toBe("3"); // then the stored value
712713
});
713714
```
714715

716+
That test needs no setup for "late". In production the root sets `data-hydrated`
717+
on `<html>` from its effect once it has hydrated, and a streamed boundary
718+
hydrates after that. `renderRoute` does the same in hydrate mode (and removes
719+
the attribute on unmount), and React hydrates a `<Suspense>` boundary in a later
720+
pass than the tree above it. Put the reader in a boundary and its hydration
721+
render is the late one by structure.
722+
715723
You might wonder how a happy-dom test can have a "server" pass when `window` is
716724
right there. It cannot, unless the harness takes it away, so it does:
717725
`renderRoute` deletes `window` and `document` from the global scope for the
718726
synchronous server render and restores them before hydrating. Without that, a
719727
`typeof window !== "undefined"` branch would take its client side on the
720728
"server", produce the client HTML, and hydrate clean, hiding the first cause
721-
React lists for a mismatch. (We measured it on the pre-#992 hook: with the
722-
globals left in place it rendered the stored value into the server HTML and
723-
reported nothing.) The flip side is faithful too: an unguarded `document.title`
724-
in render throws `ReferenceError` in the server pass, as it does in SSR.
729+
React lists for a mismatch. The flip side is faithful too: an unguarded
730+
`document.title` in render throws `ReferenceError` in the server pass, as it
731+
does in SSR.
725732

726733
What to know before you rely on it:
727734

@@ -738,13 +745,13 @@ What to know before you rely on it:
738745
- **Attribute-only mismatches are not recoverable errors.** For a differing
739746
`className` or `href` React keeps the server attribute and logs
740747
`console.error` in development. Assert that with `vi.spyOn(console, "error")`.
741-
- **Only `window` and `document` are removed.** A bare `localStorage` or
742-
`navigator` read still succeeds in the server pass.
748+
- **Only `window` and `document` are removed.** This is the fidelity limit. A
749+
hook that reads a global that stays defined in the server pass (`history`,
750+
`localStorage`, `navigator`) outside a server snapshot renders the same in
751+
both passes here and can still mismatch in real SSR.
743752
- **One realm, two passes.** Every component renders once in the server pass
744753
before its hydration render, and module state written while rendering is
745754
still there at hydration. Count renders accordingly.
746-
- **`data-hydrated` is not set for you.** Production's root sets it from an
747-
effect; set and remove it in the test if your code reads it.
748755
- **`@testing-library/react` 16.2.0 or newer.** 16.0 and 16.1 never pass
749756
`onRecoverableError` to `hydrateRoot`, so a mismatch would be invisible.
750757
`renderRoute` throws there instead of returning an empty array.

‎packages/rangojs-router/e2e/location-state.test.ts‎

Lines changed: 8 additions & 23 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,8 @@
11
import { expect, test, type Page } from "@playwright/test";
2-
import { returnToEvictedEntry } from "@shared/e2e";
2+
import {
3+
expectLateSuspenseReaderHydratesClean,
4+
returnToEvictedEntry,
5+
} from "@shared/e2e";
36
import { useFixture, type Fixture } from "./fixture";
47
import {
58
waitForHydration,
@@ -1444,32 +1447,14 @@ test.describe("location-state.action-ls (production)", () => {
14441447
actionLocationStateSuite(f);
14451448
});
14461449

1447-
const HYDRATION_ERROR =
1448-
/hydrat|did not match|server rendered|Minified React error #(418|419|422|423|425)/i;
1449-
1450-
function lateSuspenseSuite(f: ReturnType<typeof useFixture>) {
1450+
function lateSuspenseSuite(f: Fixture) {
14511451
test("reader inside a late-hydrating Suspense boundary hydrates without a mismatch", async ({
14521452
page,
14531453
}) => {
1454-
const errors: string[] = [];
1455-
page.on("console", (msg) => {
1456-
if (msg.type() === "error") errors.push(msg.text());
1457-
});
1458-
page.on("pageerror", (err) => errors.push(err.message));
1459-
1460-
await page.goto(f.url("/location-state/late-suspense"));
1461-
await waitForHydration(page);
1462-
await page.locator('[data-testid="late-ls-write"]').click();
1463-
1464-
await page.reload();
1465-
await waitForHydration(page);
1466-
1467-
// The boundary resolves ~500ms after the root hydrated.
1468-
await expect(page.locator('[data-testid="late-ls-value"]')).toHaveText(
1469-
"stored-value",
1470-
{ timeout: 10000 },
1454+
await expectLateSuspenseReaderHydratesClean(
1455+
page,
1456+
f.url("/location-state/late-suspense"),
14711457
);
1472-
expect(errors.filter((e) => HYDRATION_ERROR.test(e))).toEqual([]);
14731458
});
14741459
}
14751460

‎packages/rangojs-router/e2e/test-app/src/components/LateSuspenseReader.tsx‎

Lines changed: 2 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -16,19 +16,11 @@ export function LateSuspenseWriter() {
1616
}
1717

1818
/**
19-
* Rendered inside a <Suspense> whose server content resolves after the root
19+
* Rendered inside a <Suspense> whose server content arrives after the root
2020
* has hydrated. The hydrating render must be `undefined` (what SSR produced);
2121
* the stored value appears on the next render.
2222
*/
2323
export function LateSuspenseReader() {
2424
const state = useLocationState(LateSuspenseState);
25-
return (
26-
<div data-testid="late-ls-reader">
27-
{state ? (
28-
<span data-testid="late-ls-value">{state.label}</span>
29-
) : (
30-
<span data-testid="late-ls-empty">empty</span>
31-
)}
32-
</div>
33-
);
25+
return <span data-testid="late-ls-value">{state?.label ?? "empty"}</span>;
3426
}

‎packages/rangojs-router/e2e/test-app/src/location-states.ts‎

Lines changed: 1 addition & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -82,10 +82,6 @@ export interface TxWhenStateShape {
8282

8383
export const TxWhenState = createLocationState<TxWhenStateShape>();
8484

85-
export interface LateSuspenseStateShape {
86-
label: string;
87-
}
88-
8985
// Persistent slot read by a useLocationState reader inside a Suspense boundary
9086
// that hydrates after the root (#992).
91-
export const LateSuspenseState = createLocationState<LateSuspenseStateShape>();
87+
export const LateSuspenseState = createLocationState<{ label: string }>();

‎packages/rangojs-router/e2e/test-app/src/router.named-routes.gen.ts‎

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -259,7 +259,8 @@ export const NamedRoutes = {
259259
"locale.list": "/:locale/blog",
260260
"locationState.actionLs": "/location-state/action-ls",
261261
"locationState.index": "/location-state",
262-
"locationState.lateSuspense": "/location-state/late-suspense",
262+
"locationState.lateSuspense": "/location-state/late-suspense/:gate",
263+
"locationState.lateSuspenseRelease": "/location-state/late-suspense/:gate/release",
263264
"locationState.linkState": "/location-state/link-state",
264265
"locationState.linkStatePlainTarget": "/location-state/link-state/plain-target",
265266
"locationState.linkStateTarget": "/location-state/link-state/target",

‎packages/rangojs-router/e2e/test-app/src/urls/location-state.tsx‎

Lines changed: 36 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -35,15 +35,31 @@ import {
3535
ActionLocationStateControls,
3636
} from "../components/ActionLocationState.js";
3737

38+
// #992 fixture. The boundary's server content is held until the e2e releases
39+
// its :gate (GET <page>/release), which it does after seeing the root hydrate.
40+
// The held render polls instead of awaiting a promise the release request
41+
// resolves, so only this Map crosses requests. It counts releases, and a
42+
// render waits for one made after it started: the test loads the page twice
43+
// under one gate.
44+
const lateSuspenseReleases = new Map<string, number>();
45+
46+
async function LateSuspenseContent({ gate }: { gate: string }) {
47+
const releasesAtStart = lateSuspenseReleases.get(gate) ?? 0;
48+
// Safety timeout: a failed test must not hold the render.
49+
const deadline = Date.now() + 15_000;
50+
while (
51+
(lateSuspenseReleases.get(gate) ?? 0) === releasesAtStart &&
52+
Date.now() < deadline
53+
) {
54+
await new Promise((resolve) => setTimeout(resolve, 25));
55+
}
56+
return <LateSuspenseReader />;
57+
}
58+
3859
/**
3960
* Location state test routes - tests for redirect() with state,
4061
* ctx.setLocationState(), useLocationState(), and useLocationState()
4162
*/
42-
async function LateSuspenseContent() {
43-
await new Promise((resolve) => setTimeout(resolve, 500));
44-
return <LateSuspenseReader />;
45-
}
46-
4763
export const locationStatePatterns = urls(({ path, middleware }) => [
4864
// Index page with links to trigger different scenarios
4965
path(
@@ -268,21 +284,29 @@ export const locationStatePatterns = urls(({ path, middleware }) => [
268284
{ name: "linkStatePlainTarget" },
269285
),
270286

271-
// #992: a persistent useLocationState reader inside a Suspense boundary that
272-
// resolves after the root hydrates.
287+
// #992: a persistent useLocationState reader inside a Suspense boundary
288+
// that the e2e holds until the root has hydrated, then releases.
273289
path(
274-
"/late-suspense",
275-
() => (
276-
<div data-testid="ls-late-suspense">
277-
<h1>Late Suspense</h1>
290+
"/late-suspense/:gate",
291+
(ctx) => (
292+
<div>
278293
<LateSuspenseWriter />
279294
<Suspense fallback={<div data-testid="late-ls-fallback">loading</div>}>
280-
<LateSuspenseContent />
295+
<LateSuspenseContent gate={ctx.params.gate} />
281296
</Suspense>
282297
</div>
283298
),
284299
{ name: "lateSuspense" },
285300
),
301+
path.json(
302+
"/late-suspense/:gate/release",
303+
(ctx) => {
304+
const releases = (lateSuspenseReleases.get(ctx.params.gate) ?? 0) + 1;
305+
lateSuspenseReleases.set(ctx.params.gate, releases);
306+
return { releases };
307+
},
308+
{ name: "lateSuspenseRelease" },
309+
),
286310

287311
// Static write/delete demo: drives LocationState.write() and .delete()
288312
// from the client and exposes both .read() and useLocationState() readers.

‎packages/rangojs-router/skills/testing/client-components.md‎

Lines changed: 16 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -168,27 +168,31 @@ A plain `renderRoute` mounts with `createRoot`, so a component never runs its hy
168168

169169
```tsx
170170
// @vitest-environment happy-dom
171+
import { Suspense } from "react";
171172
import { afterEach, expect, it } from "vitest";
172173
import { cleanup } from "@testing-library/react";
173174
import { renderRoute } from "@rangojs/router/testing/dom";
174175
import { Grid } from "../src/components/Grid"; // <p data-testid="count">{useLocationState(GridState)?.count ?? 0}</p>
175176
import { GridState } from "../src/location-states";
176177

177-
afterEach(() => {
178-
cleanup();
179-
document.documentElement.removeAttribute("data-hydrated");
180-
});
178+
afterEach(cleanup);
179+
180+
// A <Suspense> boundary hydrates after the root has marked the page hydrated,
181+
// as a streamed boundary does in production.
182+
function GridPage() {
183+
return (
184+
<Suspense fallback={null}>
185+
<Grid />
186+
</Suspense>
187+
);
188+
}
181189

182190
it("hydrates as the server rendered it, then shows the stored count", async () => {
183-
// Rango's root sets data-hydrated from its first effect, and a streamed
184-
// <Suspense> boundary hydrates after that. Set up front, it makes this
185-
// hydration render the late one.
186-
document.documentElement.setAttribute("data-hydrated", "");
187191
const { serverHtml, recoverableErrors, getByTestId } = await renderRoute(
188-
[{ path: "/grid", Component: Grid }],
192+
[{ path: "/grid", Component: GridPage }],
189193
{ hydrate: true, locationState: [[GridState, { count: 3 }]] },
190194
);
191-
expect(serverHtml).toBe('<p data-testid="count">0</p>'); // no history.state on the server
195+
expect(serverHtml).toContain('<p data-testid="count">0</p>'); // no history.state on the server
192196
expect(recoverableErrors).toEqual([]); // the first client render matched it
193197
expect(getByTestId("count").textContent).toBe("3"); // then the stored value
194198
});
@@ -204,8 +208,8 @@ it("hydrates as the server rendered it, then shows the stored count", async () =
204208
| `<Suspense>` whose content renders synchronously | In `serverHtml`. It hydrates in a later pass than the tree above it, after that tree's effects, before `renderRoute` resolves. |
205209
| Content that suspends in the server pass (`lazy`, a pending or plain `use()` promise) | NOT hydrated: `serverHtml` has the fallback, the client renders the content, and `recoverableErrors` reports the boundary. With no `<Suspense>` above it `renderRoute` rejects. A settled promise (Caveats, below) stays in the server HTML. |
206210
| Render counts and module state | Every component renders once in the server pass before its hydration render. Both passes share one module realm, so module state written while rendering is still there at hydration. |
207-
| `localStorage`, `navigator`, `history` as bare globals | Still defined in the server pass. Only `window` and `document` are removed. |
208-
| `data-hydrated` on `<html>` | Not set by `renderRoute` (production's root sets it from an effect). Set and remove it in the test, as above. |
211+
| `history`, `localStorage`, `navigator` read outside a server snapshot | FIDELITY LIMIT: still defined in the server pass (only `window` and `document` are removed), so the read renders the same in both passes here and can still mismatch in real SSR. |
212+
| `data-hydrated` on `<html>` | Set after hydration, as the production root sets it from its effect, and removed on unmount. A `<Suspense>` boundary therefore hydrates with it already set. |
209213

210214
- Needs `@testing-library/react` 16.2.0 or newer. 16.0 and 16.1 never pass `onRecoverableError` to `hydrateRoot`, so a mismatch would be invisible; `renderRoute` throws there instead.
211215
- `recoverableErrors` is live: React appends to it for as long as the root is mounted.

0 commit comments

Comments
 (0)