Adds browser tests and fixes hydration of the 404 page

The prerendered 404 page is served for other URLs, so its dehydrated match id
differs and the router renders the catch-all's pending component first. Without
one that render was empty, which gave React error 418 and duplicate head tags.
The tests run the built output in a real browser under the production CSP.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
2026-10-31 19:03:07 +01:00
co-authored by Claude Opus 5.5
parent 0c5d8b8f40
commit 8bf0000531
15 changed files with 1216 additions and 48 deletions
+70
View File
@@ -0,0 +1,70 @@
// @vitest-environment node
import { ChakraProvider } from '@chakra-ui/react';
import {
createMemoryHistory,
createRouter,
HeadContent,
RouterProvider,
rootRouteId,
} from '@tanstack/react-router';
import type { ReactNode } from 'react';
import { prerender } from 'react-dom/static';
import { describe, expect, it } from 'vitest';
import siteContent from './content/siteContent';
import { emailAddress } from './lib/emailAddress';
import { routerOptions } from './router';
import sitePages from './sitePages';
import system from './theme';
// Fast guard against `window` or `document` in a render path (BR-TST-07):
// every page is rendered in Node, where either one throws, before a full
// build is needed to find out. The build's own prerender stays authoritative.
// The document shell is left out as in renderApp: it renders <html>, and what
// is guarded here is the page inside it.
const TestShell = ({ children }: { children: ReactNode }) => (
<>
<HeadContent />
{children}
</>
);
// Waits for lazy chunks like the real prerender (the form on /contact)
async function prerenderPath(path: string) {
const router = createRouter({
...routerOptions(),
history: createMemoryHistory({ initialEntries: [path] }),
});
const rootOptions = router.routesById[rootRouteId].options as {
shellComponent?: typeof TestShell;
};
rootOptions.shellComponent = TestShell;
await router.load();
const { prelude } = await prerender(
<ChakraProvider value={system}>
<RouterProvider router={router} />
</ChakraProvider>,
);
return new Response(prelude).text();
}
describe('prerender in Node', () => {
it.each([...Object.keys(sitePages), '/onbekend'])(
'renders %s without window or document',
async (path) => {
const html = await prerenderPath(path);
expect(html).not.toBe('');
expect(html).toMatch(/<h1[\s>]/);
},
30_000,
);
it('keeps the assembled address out of the HTML of /contact', async () => {
const address = emailAddress(siteContent.email);
expect(address).toBeTruthy();
const html = await prerenderPath('/contact');
// The form is in the HTML, so the check covers the part that renders
// the address after a failed send (BR-MAIL-06)
expect(html).toContain('data-testid="contact-form"');
expect(html.toLowerCase()).not.toContain(address!.toLowerCase());
});
});
+16 -1
View File
@@ -1,9 +1,24 @@
import { createFileRoute } from '@tanstack/react-router';
import NotFound from '../components/StatusPage/NotFound';
// Eén component voor component en pendingComponent: de code splitter laat de
// import van NotFound vallen als die in een gesplitste (component) en in een
// niet-gesplitste eigenschap (pendingComponent) staat.
const CatchAll = () => <NotFound />;
// Vangt elke onbekende URL op en wordt als 404.html voorgerenderd (BR-404-01).
// Geen head() en geen notFound(): Start laat de build falen bij een niet-OK
// antwoord, en NotFound zet zelf titel en noindex.
//
// pendingComponent is hier geen laadscherm maar de eerste browserrender. De
// HTML is gemaakt voor /404 en de match-id bevat het pad (#$#404), dus voor
// /onbekend of /404.html herkent Start de match niet en laat die in de browser
// renderen tot het laden klaar is, met pendingComponent als inhoud. Zonder
// pendingComponent is dat niets, terwijl de HTML de pagina toont. React
// hydrateert die grens los van de rest en geeft fout #418 als het laden dan
// nog niet klaar is (trage verbinding of processor). Met dezelfde pagina als
// pendingComponent is de eerste render gelijk aan de HTML.
export const Route = createFileRoute('/$')({
component: NotFound,
component: CatchAll,
pendingComponent: CatchAll,
});
+31 -1
View File
@@ -1,7 +1,7 @@
import { screen, waitFor, within } from '@testing-library/react';
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
import { FakeIntersectionObserver } from '@/test/fakeIntersectionObserver';
import { hydrateApp } from '@/test/hydrate';
import { hydrateApp, hydrateAppAsStart } from '@/test/hydrate';
// A direct load of a page with a search: the HTML was prerendered without it,
// so the first browser render must ignore it and the page applies it right
@@ -71,3 +71,33 @@ describe('homepage ?pakket= on a direct load', () => {
expect(errors).toEqual([]);
});
});
// The prerendered 404 page is made for /404 and served for any unknown URL.
// Start does not recognise the catch-all match of another path (its id holds
// the path), so the browser renders that match itself. Its first render must
// be the page the HTML shows, or React reports a mismatch (BR-404-05, V12).
describe('404 page served for another URL', () => {
it.each(['/onbekend', '/404.html', '/over-mij/x'])(
'hydrates %s without a mismatch',
async (url) => {
const { errors } = await hydrateAppAsStart('/404', url);
expect(
await screen.findByRole('heading', {
name: 'Pagina niet gevonden',
}),
).toBeInTheDocument();
expect(errors).toEqual([]);
},
);
it('shows the section buttons after hydrating under /soorten-fotoshoots/', async () => {
const { errors } = await hydrateAppAsStart(
'/404',
'/soorten-fotoshoots/onbekend',
);
expect(
await screen.findByTestId('status-page-section-link'),
).toBeInTheDocument();
expect(errors).toEqual([]);
});
});
+64 -7
View File
@@ -11,6 +11,7 @@ import {
rootRouteId,
} from '@tanstack/react-router';
import { act } from '@testing-library/react';
import { hydrate as hydrateRouter } from '@tanstack/react-router/ssr/client';
import { hydrateRoot } from 'react-dom/client';
import { renderToString } from 'react-dom/server';
import { afterEach } from 'vitest';
@@ -61,7 +62,7 @@ const TestShell = ({ children }: { children: ReactNode }) => (
</>
);
async function appRouterAt(path: string) {
function createAppRouter(path: string, shell = TestShell) {
const router = createRouter({
...routerOptions(),
history: createMemoryHistory({ initialEntries: [path] }),
@@ -69,13 +70,24 @@ async function appRouterAt(path: string) {
const rootOptions = router.routesById[rootRouteId].options as {
shellComponent?: typeof TestShell;
};
rootOptions.shellComponent = TestShell;
rootOptions.shellComponent = shell;
return router;
}
const appFor = (router: ReturnType<typeof createAppRouter>) => (
<ChakraProvider value={system}>
<RouterProvider router={router} />
</ChakraProvider>
);
// Without HeadContent: it needs the real document, and the head is not what
// this hydration compares
const BareShell = ({ children }: { children: ReactNode }) => <>{children}</>;
async function appRouterAt(path: string) {
const router = createAppRouter(path);
await router.load();
return (
<ChakraProvider value={system}>
<RouterProvider router={router} />
</ChakraProvider>
);
return appFor(router);
}
// renderToString cannot wait for a lazy component: it emits the fallback and a
@@ -128,3 +140,48 @@ export async function serverHtml(ui: ReactElement, path = '/') {
export async function hydratePage(ui: ReactElement, path = '/') {
return hydrate(await withProviders(ui, path), await serverHtml(ui, path));
}
// Like hydrateApp, but the way Start hands over in the browser: the client
// router is not loaded first. It takes the matches the server dehydrated
// (window.$_TSR) and only adopts those whose id equals its own. Then a match
// the server made for another path, such as the catch-all at `/404` seen at
// `/onbekend`, is rendered by the browser alone, which hydrateApp cannot show
// because its client router has already loaded every match.
export async function hydrateAppAsStart(
serverPath: string,
clientPath: string,
) {
const serverRouter = createAppRouter(serverPath, BareShell);
// Router leaves out its root Suspense boundary on the server and in a
// hydrated browser router (router.ssr); jsdom is neither, so say it here
serverRouter.ssr = { manifest: undefined };
await serverRouter.load();
// renderToString puts the document tags (preloads, title, meta) in front of
// the markup; in the browser they live in <head>, outside the body that is
// hydrated, and e2e checks them (V11)
const markup = (await serverMarkup(appFor(serverRouter))).replace(
/^(?:<(?:link|meta)\b[^>]*>|<title>[^<]*<\/title>)*/,
'',
);
window.$_TSR = {
buffer: [],
initialized: false,
h: () => {},
e: () => {},
c: () => {},
p: (script) => script(),
router: {
manifest: undefined,
// Start inlines ids with '#' for '/' (dehydrateSsrMatchId)
matches: serverRouter.state.matches.map((match) => ({
i: match.id.replaceAll('/', '#'),
s: match.status,
ssr: true,
u: match.updatedAt,
})),
},
};
const clientRouter = createAppRouter(clientPath, BareShell);
await hydrateRouter(clientRouter);
return hydrate(appFor(clientRouter), markup);
}
+32 -28
View File
@@ -15,32 +15,36 @@ afterEach(() => {
vi.restoreAllMocks();
});
// jsdom kent geen matchMedia (Chakra-breakpoints, reduced motion) en geen
// scrollTo. Tests die het gedrag nodig hebben, overschrijven deze stubs.
Object.defineProperty(window, 'matchMedia', {
writable: true,
configurable: true,
value: (query: string) => ({
matches: false,
media: query,
onchange: null,
addEventListener: () => {},
removeEventListener: () => {},
addListener: () => {},
removeListener: () => {},
dispatchEvent: () => false,
}),
});
window.scrollTo = () => {};
// The router scrolls to a #hash with scrollIntoView, which jsdom lacks too
Element.prototype.scrollIntoView = () => {};
// Alleen in jsdom: een test met `@vitest-environment node` (prerender.test.tsx)
// heeft geen window, en juist daar moet een render die er toch bij komt falen
if (typeof window !== 'undefined') {
// jsdom kent geen matchMedia (Chakra-breakpoints, reduced motion) en geen
// scrollTo. Tests die het gedrag nodig hebben, overschrijven deze stubs.
Object.defineProperty(window, 'matchMedia', {
writable: true,
configurable: true,
value: (query: string) => ({
matches: false,
media: query,
onchange: null,
addEventListener: () => {},
removeEventListener: () => {},
addListener: () => {},
removeListener: () => {},
dispatchEvent: () => false,
}),
});
window.scrollTo = () => {};
// The router scrolls to a #hash with scrollIntoView, which jsdom lacks too
Element.prototype.scrollIntoView = () => {};
// jsdom has no ResizeObserver either; the carousel (Zag) needs one. Nothing
// is measured in jsdom, so a no-op is enough. IntersectionObserver is left
// out on purpose: useInView and DeferredImage are tested without it, and
// tests that render the carousel stub it themselves.
globalThis.ResizeObserver ??= class {
observe() {}
unobserve() {}
disconnect() {}
};
// jsdom has no ResizeObserver either; the carousel (Zag) needs one. Nothing
// is measured in jsdom, so a no-op is enough. IntersectionObserver is left
// out on purpose: useInView and DeferredImage are tested without it, and
// tests that render the carousel stub it themselves.
globalThis.ResizeObserver ??= class {
observe() {}
unobserve() {}
disconnect() {}
};
}