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
@@ -402,7 +402,7 @@ Disjoint from B2 and B4. Runs only targeted `vitest run` commands. The editing o
- Done when: **CP3**: `pnpm build` succeeds, the runner prints its success line (this requires Steps 17 and 21 done, otherwise EMAIL_IN_OUTPUT fails the build, which is the check working). Port 4173 and CPU rules of Step 2 apply to item 5.
- Record: verification log notes under V5, V7, and the lighthouse finding.
### Step 25: Prerender-safety test (BR-TST-07) [ ]
### Step 25: Prerender-safety test (BR-TST-07) [x]
- Executor: Sonnet.
- Implements: BR-TST-07; FR-PR-05; NFR-PR-Q-03 (fast feedback).
@@ -410,7 +410,7 @@ Disjoint from B2 and B4. Runs only targeted `vitest run` commands. The editing o
- Do: for every key of `sitePages` plus an unknown path, create a router with memory history from `routerOptions()`, await `router.load()`, render with `react-dom/server` inside `ChakraProvider`, and expect no throw and a non-empty string containing the page's `<h1>`. This catches `window`/`document` use in render paths. If it cannot be made to work with the shell, drop the shell from the test as in Step 5. Feasibility is the open point: if the Chakra provider or the router cannot render in a Node environment at all, record "not feasible, the build's own prerender is the guard" in the verification log and replace the test by a documented skip-free alternative (a test that scans nothing is not acceptable): in that case STOP and report instead of deleting the step. Add the assertion that the server HTML of `/contact` has no assembled address.
- Done when: `pnpm exec vitest run src/prerender.test.tsx` passes.
### Step 26: e2e harness and smoke test [ ]
### Step 26: e2e harness and smoke test [x]
- Executor: Sonnet.
- Implements: BR-TST-05 (harness); D11; NFR-PR-Q-03; V1 (browser side), V8 early.
@@ -422,7 +422,7 @@ Disjoint from B2 and B4. Runs only targeted `vitest run` commands. The editing o
- `smoke.e2e.ts`: `/` and `/contact` and `/onbekend`: page loads under the production CSP, the heading is visible, zero console errors/warnings and zero CSP violations. This is the first real-browser proof; if it fails with hydration or CSP errors, analyse; failures that need a design change: STOP.
- Done when: `pnpm build && pnpm e2e` passes locally (Chrome must be installed or `CHROME_PATH` set; if no browser is available on this machine, STOP and ask the main session instead of skipping).
### Step 27: Full e2e tests (BR-TST-05, BR-TST-06; V8, V9, V10, V11, V12, V14, V15, V16, V17) [ ]
### Step 27: Full e2e tests (BR-TST-05, BR-TST-06; V8, V9, V10, V11, V12, V14, V15, V16, V17) [x]
- Executor: Sonnet.
- Implements: BR-TST-05, 06; BR-HYD-17, 20, 21; BR-LZY-01, 05; BR-404-03, 04, 05, 07; BR-ENT-06; BR-MAIL-10; FR-PR-05 to 08, 14, 15, 22; NFR-PR-S-02, SEC-01, Q-03, Q-04; PBT: "No PBT properties identified" (browser flows).
@@ -32,18 +32,42 @@ Notes:
| V5 | `index.html` written, crawling off | 4 | `/` is written as `index.html` with `autoSubfolderIndex: false`; `/x` as `x.html`, `/soorten-fotoshoots/x` as `soorten-fotoshoots/x.html`. Option names (from the `start-plugin-core` schema): `prerender.crawlLinks: false` and `prerender.autoStaticPathsDiscovery: false` (the latter stops Start adding static routes by itself), page list from `Object.keys(sitePages)` plus `{ path: '/404', prerender: { outputPath: '/404.html' } }`. | Prerender log: "Prerendered 12 pages". `find dist/client -name '*.html'` gives exactly 404, index, over-mij, portfolio, privacyverklaring, contact, soorten-fotoshoots and five `soorten-fotoshoots/<shoot>.html` (12 files, no others). Step 24: `pnpm build` (tsc, vite build, runner) exits 0 with the same 12 pages; `vite.config.ts` now takes `NOT_FOUND_PATH` and `NOT_FOUND_FILE` from `config/pageFiles.ts`. | OK |
| V6 | Code splitting; router plugin unused | 4 (30 later) | Start's plugin includes `tanstackRouterGenerator` and `tanStackRouterCodeSplitter` itself (client and server environments), so route code splitting is on without an option and `@tanstack/router-plugin` is not needed as a direct dependency. Removed with `pnpm remove @tanstack/router-plugin`; only Start's own copy (1.168.48) remains. | Client build has one chunk per route (`over-mij-*.js`, `contact-*.js`, `portfolio-*.js`, `newborn-*.js`, ..., `_-*.js` for the catch-all), plus `ContactForm`, `Lightbox`, `TestimonialCarousel` chunks. Step 30 re-checks. | OK |
| V7 | Sitemap in the client environment only | 4 | `this.environment.name === 'client'` identifies the client build in `generateBundle` (Vite 8.3.1, Start environments `client` and `ssr`). | `dist/client/sitemap.xml` exists once (10 `<loc>`, no `/privacyverklaring`, no `/404`); `find dist -name sitemap.xml` gives only that file; `public/` has no `sitemap.xml`. Step 24: the same build gives the runner line `Inline scripts verplaatst: 12 pagina's gecontroleerd, 16 scripts verplaatst, 28 bestanden geschreven` (no violations), and `dist` keeps the sitemap in the client build only. | OK |
| V8 | Lazy `ContactForm` in HTML and hydration | 27 | open (first look: `contact.html` contains `data-testid="contact-form"` and its fields; `/contact` hydrates in Chrome without console output) | | open |
| V9 | Testimonials in HTML, hidden slides | 21, 27 | Code part (step 18, 21): `renderToString` of `Testimonials` holds the quote of every visible review; the copies besides the longest sit in a `VisuallyHidden` wrapper with `aria-hidden` and `inert`; axe has no violations in jsdom with the placeholder showing. Layout and reading order in a browser: step 27. | `Testimonials.test.tsx` (4 new tests) | open |
| V8 | Lazy `ContactForm` in HTML and hydration | 27 | What is true (differs from the plan text and BR-LZY-01 "the form fields are in the HTML inside the gate"): the prerender waits for the lazy chunk, so the form and its fields (`data-testid="contact-form"`, `contact-form-shoot`, ...) are in the bytes of `contact.html`, but as a streamed Suspense segment, not in place. In `<main>` the gate holds `<!--$?--><template id="B:0"></template>` plus the empty `FORM_PLACEHOLDER_HEIGHT` box; the form sits in `<div hidden id="S:0">` at the end of the body, and React's completion runtime (`$RC("B:0","S:0")`, moved to an external script by the runner) moves it into place. Without JavaScript the form is therefore in the HTML but not visible (`isVisible` false); FR-PR-13 allows that. With JavaScript, under the production CSP and the moved scripts, the form appears inside `main`, there is no `securitypolicyviolation` and no console message or hydration error. A late chunk is safe too (BR-LZY-05): with the `ContactForm-*.js` request held back 1500 ms, the page hydrates without any message and the form appears. | `e2e/hydration.e2e.ts` "contactformulier op /contact (V8)", 3 tests, pass; also the 390 and 1280 px page tests of `/contact`. | OK (BR-LZY-01 text to be corrected: fields are in the HTML only as the hidden streamed segment) |
| V9 | Testimonials in HTML, hidden slides | 21, 27 | Code part (step 18, 21): `renderToString` of `Testimonials` holds the quote of every visible review; the copies besides the longest sit in a `VisuallyHidden` wrapper with `aria-hidden` and `inert`; axe has no violations in jsdom with the placeholder showing. Browser part (step 27): the raw HTML of `/` contains the quote and author of every visible review. Measured at 390 px with and without JavaScript: the longest review is 350 x 533 px in the flow, the other copy is 1 x 1 px, `aria-hidden` and `inert`; the testimonials section is 840 px high in both cases (no layout change at hydration while the carousel has not loaded). Reading order: the hidden copies are out of the accessibility tree, so each review is read once. | `Testimonials.test.tsx` (4 new tests); `e2e/rawHtml.e2e.ts` "reviews op de homepage"; `e2e/interaction.e2e.ts` "reviews voor het laden van de carrousel (V9)" | OK |
| V10 | Placeholder sizes, CLS below 0.01 | 17, 34 | First estimates (step 17), not measured: footer item `minH` 44px below `lg`, `1lh` from `lg` (one line of the list item); contact card item `minH` 44px; gate notice inline block `38ch` (lead " Mail me voor nu op " 20 + address 18 characters, from the parts without assembling) plus a hidden button with the recipe and label. To be measured in 27 and 34. | `Footer.tsx`, `ContactDetails.tsx`, `ContactFormGate.tsx` | open |
| V11 | One title, one noindex meta | 4 (normal pages), 27 (`404.html`) | Normal pages in the prerendered HTML: one `<title>`, one `description`, one `canonical`, no `data-fallback`, a robots meta only on `/privacyverklaring`. `404.html`: one `<title>` ("Pagina niet gevonden \| Andrea Slop Fotografie") and one `<meta name="robots" content="noindex">`, no description or canonical. React writes `<meta charSet="utf-8">` with a capital S (valid, attribute names are case-insensitive). | `scripts.mjs` counts per file. After hydration in Chrome: `/`, `/over-mij`, `/contact` still 1 title. Caution for Step 27: `/soorten-fotoshoots/onbekend` showed 2 titles and 2 robots metas after React error #418 (the two extra 404 buttons render before hydration; Step 16 fixes that); `/onbekend` is clean. | OK (normal pages); `404.html` source OK, final check in 27 |
| V12 | 404 hydration with real shell | 27 | open (first look, before Step 16: `/onbekend` hydrates clean; `/soorten-fotoshoots/onbekend` gives #418, which Step 16 `hydrated && isShootSectionPath` should remove) | | open |
| V11 | One title, one noindex meta | 4 (normal pages), 27 (`404.html`) | Normal pages in the prerendered HTML: one `<title>`, one `description`, one `canonical`, no `data-fallback`, a robots meta only on `/privacyverklaring`. `404.html`: one `<title>` ("Pagina niet gevonden \| Andrea Slop Fotografie") and one `<meta name="robots" content="noindex">`, no description or canonical. React writes `<meta charSet="utf-8">` with a capital S (valid, attribute names are case-insensitive). | `scripts.mjs` counts per file. After hydration in Chrome: `/`, `/over-mij`, `/contact` still 1 title. Caution for Step 27: `/soorten-fotoshoots/onbekend` showed 2 titles and 2 robots metas after React error #418 (the two extra 404 buttons render before hydration; Step 16 fixes that); `/onbekend` is clean. | OK (final check in Step 27, see the V11 paragraph below the table) |
| V12 | 404 hydration with real shell | 27 | Found and fixed. With the real shell (navigation, footer, e-mail placeholders) the 404 HTML for `/404` hydrated at another URL gave React #418 in a race, reproducible below 1024 px width and under CPU or network delay (Lighthouse). Root cause and fix: "404 hydration error #418" below the table (`pendingComponent` of the catch-all route equals its component). After the fix `/404.html`, `/404`, `/onbekend`, `/soorten-fotoshoots/onbekend` give no console message, no CSP violation, one title and one robots meta at 390 and 1280 px, and also with the route chunk delayed by 800 ms; `/soorten-fotoshoots/onbekend` shows one button without JavaScript and two extra after hydration. | `e2e/hydration.e2e.ts` (48 tests); `src/routes/hydration.test.tsx` (4 new tests with `hydrateAppAsStart`). Without the fix 5 e2e tests and 4 unit tests fail. | OK |
| V13 | Timestamps and build paths | 4, 13 | Repeated on the final output of the runner (HTML plus the 16 moved script files plus all JS/CSS/XML/TXT/JSON): no build timestamp (`YYYY-MM-DDTHH:MM`) in any text file, no `.map` file, no repository root path (forward slashes, backslashes or doubled backslashes) in any text file. File names are content hashes, so they cannot carry a timestamp. | Scan in the scratch run (`repoPathFiles: 0`, `timestampFiles: 0`, `maps: 0`); the runner's own BUILD_PATH_LEAK check reported nothing. | OK |
| V14 | Focus on first load, tidy navigation | 27 | open | | open |
| V15 | Emotion/Chakra flicker | 4 (styles in HTML), 27 (screenshots) | Styles are in the HTML: `<style data-emotion` x69 in `/over-mij`, x120 on `/`, plus the bundled stylesheet `<link rel="stylesheet" href="/assets/index-*.css">` (fonts and Chakra base). After hydration in Chrome `/over-mij` has 70 emotion style tags (one added by the client); no console warning. Visual check in Step 27. | `scripts.mjs`; Chrome probe. | OK (styles present); screenshots in 27 |
| V16 | `Intl` price text | 27 | open | | open |
| V17 | No `on*=` or `javascript:` | 13, 27 | Step 13 on the runner output: 0 HTML files with an `on*=` attribute and 0 HTML files with `javascript:`. The only `javascript:` in `dist/client` is two strings in `assets/index-*.js`: React's own guard text (`javascript:throw new Error('React has blocked a javascript: URL...`), which is not markup and not a URL in a page. Step 27 repeats it under the CSP. | Scratch run counts (`onAttrFiles: 0`); `grep -l javascript:` over the HTML and the bundle. | OK (Step 13); CSP check in 27 |
| V14 | Focus on first load, tidy navigation | 27 | Focus: on a first load of `/` (after hydration plus 500 ms) `document.activeElement` is not `main`; after a client navigation to `/over-mij` it is `main`; on `/contact?pakket=gezin` the tidy navigation (search removed) does not move focus either. Tidy navigation: `/contact?pakket=gezin` ends on `/contact` with the same `history.length` as before (replace, no extra entry) and `scrollY` 0, one render later than before as BR-HYD-11 expects. `/?pakket=gezin#contact` scrolls the contact section into view after hydration. | `e2e/interaction.e2e.ts` ("zet de focus op main...", "verandert de focus niet...", "tidy navigatie op de contactpagina", "/?pakket=...#contact"), pass. | OK |
| V15 | Emotion/Chakra flicker | 4 (styles in HTML), 27 (screenshots) | Styles are in the HTML: `<style data-emotion` x69 in `/over-mij`, x120 on `/`, plus the bundled stylesheet `<link rel="stylesheet" href="/assets/index-*.css">` (fonts and Chakra base). After hydration in Chrome `/over-mij` has 70 emotion style tags (one added by the client); no console warning. Step 27 screenshots (`/over-mij`, JavaScript off versus on, 390 and 1280 px; reviewed by eye): without JavaScript the header, navigation (desktop links or hamburger), eyebrow "Andrea Slop Fotografie" and the heading "Over mij" are fully styled, with the Jost and Marcellus fonts, in the same positions as with JavaScript; below the heading the page is empty (the `Reveal` content is hidden in the HTML, by design until unit 2) and with JavaScript the photo and text appear in that space (390 px: photo 237 to 499, then text; 1280 px: photo and two-column text). No unstyled flash, no moved header or heading; measured: position and width of `h1` and the top of `main` are equal within 0.5 px with and without JavaScript at both widths. No console warning about styles. | `scripts.mjs`; Chrome probe; `e2e/interaction.e2e.ts` "stijlen zonder en met JavaScript (V15)"; screenshots in the scratch folder (`shots/over-mij-{390,1280}-{zonder,met}-js.png`). | OK |
| V16 | `Intl` price text | 27 | The text nodes containing a euro sign are identical in the server HTML (JavaScript off) and after hydration in Chrome (production build) for `/` and the five shoot pages, and non-empty; no hydration error. Node and Chrome ICU give the same `nl-NL` text including the non-breaking space. | `e2e/hydration.e2e.ts` "prijstekst (V16)", 6 tests, pass. | OK |
| V17 | No `on*=` or `javascript:` | 13, 27 | Step 13 on the runner output: 0 HTML files with an `on*=` attribute and 0 HTML files with `javascript:`. The only `javascript:` in `dist/client` is two strings in `assets/index-*.js`: React's own guard text (`javascript:throw new Error('React has blocked a javascript: URL...`), which is not markup and not a URL in a page. Step 27: no attribute starting with `on` and no `javascript:` attribute value in any of the 11 pages or `404.html` (parsed with `DOMParser`), and no `securitypolicyviolation` on any of the 48 hydration page loads, the interaction flows and `/contact` with the reveal script, under `securityHeaders('production')`. | Scratch run counts (`onAttrFiles: 0`); `grep -l javascript:` over the HTML and the bundle; `e2e/rawHtml.e2e.ts` and `e2e/hydration.e2e.ts`. | OK |
| V18 | CI artifact layout | 28 | open | | open |
V11 step 27: in `e2e/rawHtml.e2e.ts` all 11 pages have exactly one `<title>` equal to `pageHead`, one `description`, one canonical; `404.html` has one `<title>` ("Pagina niet gevonden \| Andrea Slop Fotografie") and one `<meta name="robots" content="noindex">`, no `data-fallback`. In `e2e/hydration.e2e.ts` the same counts hold after hydration, at 390 and 1280 px, for the 11 pages and `/404`, `/404.html`, `/onbekend`, `/soorten-fotoshoots/onbekend` (one title; robots 1 on the 404 pages and `/privacyverklaring`, 0 elsewhere). The two titles and two robots metas seen on `/soorten-fotoshoots/onbekend` before Step 16 are gone. Status: OK. (Not covered: a URL the router matches but the server does not, see BR-404-07 below, ends with two titles.)
### 404 hydration error #418 on `404.html` (root cause, Step 27)
Symptom: Lighthouse (Step 24) reported React error #418 on `/404.html`. In Chrome it reproduced deterministically below 1024 px viewport width (`/404.html`, `/404`, `/onbekend`, `/soorten-fotoshoots/onbekend`; two titles and two robots metas afterwards) and was clean at 1280 px.
Evidence for the mechanism:
1. A build with development React and no minification (temporary config, deleted) gave the full message: the client rendered `<Suspense fallback={null}>` inside `MatchImpl routeId="/$"` where the server HTML has the `<section>` of the 404 page.
2. The HTML is made for `/404`. Start dehydrates match ids with `#` for `/`: the bootstrap script has `__root__#` and `#$#404`. The browser at `/404.html` or `/onbekend` computes `#$#404.html` or `#$#onbekend`, so `hydrate()` in `@tanstack/router-core` (`load-client.ts`: `dehydrated.i !== dehydrateSsrMatchId(candidate.id)`) stops at index 1, sets `pendingBoundary = 1` and presents that match as `{ status: 'pending', ssr: false }`. A match with `ssr: false` renders `<ClientOnly fallback={pendingElement}>`; `pendingElement` comes from the route's `pendingComponent` (none) or `defaultPendingComponent` (none), so the first browser render of the page body was empty, against server HTML that shows the page.
3. React hydrates that Suspense boundary on its own, later than the root. If the router has not yet finished loading the match (a status update replaces the pending match with the loaded one, which then renders the same page as the HTML), the boundary is hydrated with the empty client render: mismatch, #418, client re-render, and the hoisted `<title>` and robots meta of the server HTML stay next to the new ones. If the match loads first, nothing is reported. So it is a race, which is why the outcome depends on viewport width and on CPU and network speed (Lighthouse throttles both). Why width matters is only a timing effect (below 1024 px the page reproduced every time on this machine, from 1024 px not); it was not traced further. With the route chunk `_-*.js` held back 400 ms, 1280 px fails too; with it held back 0 ms, 1280 px passes.
4. A plain pending component is also not an option left to chance: `pendingComponent` is not in the default split groups, so it stays in the route file, and the code splitter drops the `NotFound` import there when `NotFound` is also used by the split `component` (build error `NotFound is not defined`).
Why `hydration.test.tsx` missed it: `hydrateApp` creates the client router and awaits `router.load()` before hydrating, so every match is already loaded and the dehydrated-id comparison and the `ssr: false` pending presentation never occur. The browser has the router in the state Start's `hydrate()` leaves it in. The new `hydrateAppAsStart` (in `src/test/hydrate.tsx`) sets up `window.$_TSR.router.matches` with the server's ids, lets the router's own `hydrate()` run against a client router that has not loaded, and then hydrates. Four new tests in `src/routes/hydration.test.tsx` (`/onbekend`, `/404.html`, `/over-mij/x`, `/soorten-fotoshoots/onbekend`) fail without the fix with the same mismatch and pass with it. The e2e tests also fail without the fix (5 of 48 hydration tests: `/404.html`, `/onbekend`, `/soorten-fotoshoots/onbekend` at 390 px, plus the two delayed-chunk tests at both widths).
Fix (inside BR-HYD, no design change; BR-404-01 still holds): `src/routes/$.tsx` sets `pendingComponent` to the same page as `component`, through one shared `CatchAll = () => <NotFound />` (needed because of the splitter issue in point 4). The first browser render of the unknown-URL match is then identical to the prerendered page, whether React hydrates the boundary before or after the match has loaded. After the fix, `/404.html`, `/404`, `/onbekend`, `/soorten-fotoshoots/onbekend` are clean in the production build at 412 and 1280 px, also with the route chunk held back 0, 400, 600 and (development build) 2500 ms. Side effect to know: when the chunk takes longer than `pendingMs` (1 s), Router shows the pending component next to the hydrated HTML (the server copy is hidden by React with `display: none`), so the page briefly holds two copies of the 404 content until the chunk arrives; invisible to the visitor, but a test that counts headings in that window would see two.
`/over-mij/x`-style URLs: the same mechanism applies to any match whose id differs from the dehydrated one. For the catch-all it is fixed. For a real page served as `404.html` (BR-404-07) it is not, see below.
### BR-404-07 observation (for unit 3)
`/Over-Mij`: the preview server on this machine (Windows, case-insensitive file system) maps it to `over-mij.html` with status 200 and the page hydrates cleanly, URL stays `/Over-Mij`. On a case-sensitive host the server would send `404.html` with 404; replayed through a route handler in Chrome (production build, 1280 px): the router matches `/over-mij`, the page shows "Over mij", the document ends with two titles ("Over mij ..." and "Pagina niet gevonden ...") and no #418 in this run (the match loaded before React hydrated the boundary, so the outcome is the race of point 3), only the console line for the 404 status. `/over-mij/`: `resolveRequest` gives `404.html` with 404 (BR-SRV-07 interim); in Chrome the router renders the real "Over mij" page at `/over-mij/` (no redirect), again with two titles and the 404 console line, no #418 in this run. Both are observations, not assertions (`e2e/hydration.e2e.ts` "URL die de server niet kent en de router wel"); unit 3 must decide the URL rules so that server and router agree, and the stale 404 title and `noindex` meta in the head are the SEO consequence to weigh.
## Other findings in Steps 3 to 5
- Email address: `info@andreaslop.nl` is in all 12 HTML files (footer link, contact details, gate notice) and nowhere in `dist/client/assets/*.js`, `robots.txt` or `sitemap.xml`. Expected until Step 17.
+328
View File
@@ -0,0 +1,328 @@
import { afterAll, beforeAll, describe, expect, it } from 'vitest';
import sitePages from '../src/sitePages.ts';
import { eventually, openPage, waitForHydration } from './support/browser.ts';
import type { Page } from 'playwright-core';
import { startServer } from './support/server.ts';
// BR-TST-05, BR-HYD-20: elke pagina hydrateert onder de productie-CSP zonder
// één console-melding. De build is de productiebuild, dus React meldt een
// mismatch als minified fout (#418); `messages` laat hem door.
let server: Awaited<ReturnType<typeof startServer>>;
beforeAll(async () => {
server = await startServer();
});
afterAll(() => server.close());
const pages = Object.keys(sitePages);
// Smal is het telefoonscherm waar Lighthouse op meet; breed is desktop. De
// hydratatie verloopt niet gelijk: onder lg staat het mobiele menu in de HTML.
const widths = [390, 1280];
const notFoundPaths = [
'/404',
'/404.html',
'/onbekend',
'/soorten-fotoshoots/onbekend',
];
// Alleen een document dat de server bewust met 404 beantwoordt (BR-SRV-05)
const expectedStatus = (path: string) =>
path === '/404.html' || pages.includes(path) ? 200 : 404;
describe.each(widths)('hydratatie op %i px', (width) => {
it.each([...pages, ...notFoundPaths])(
'%s hydrateert zonder meldingen of CSP-overtredingen',
async (path) => {
const status = expectedStatus(path);
const { page, ...opened } = await openPage(server.origin + path, {
width,
expectNotFound: status === 404,
});
expect(opened.status).toBe(status);
await waitForHydration(page);
expect(opened.messages).toEqual([]);
expect(opened.violations).toEqual([]);
// Na de hydratatie nog steeds één titel en hoogstens één robots (V11)
const counts = await page.evaluate(() => ({
titles: document.querySelectorAll('title').length,
robots: document.querySelectorAll('meta[name="robots"]').length,
h1: document.querySelectorAll('h1').length,
}));
const noindex =
notFoundPaths.includes(path) || path === '/privacyverklaring';
expect(counts).toEqual({
titles: 1,
robots: noindex ? 1 : 0,
h1: 1,
});
},
);
});
describe('de 404-pagina, gemaakt voor /404 en getoond op een andere URL', () => {
// De bron van fout #418 op 404.html (Step 27): Start herkent de match van
// de catch-all voor een ander pad dan /404 niet en laat die in de browser
// renderen. React hydrateert die grens los van de rest; komt het laden
// van de route-chunk later dan die hydratatie, dan was de eerste render
// leeg tegenover de HTML. Op een snelle pc is het een race, dus hier wordt
// de chunk vertraagd tot de race altijd verloren wordt.
it.each(widths)(
'hydrateert ook als de routechunk laat komt (%i px)',
async (width) => {
const { page, ...opened } = await openPage(
server.origin + '/404.html',
{
width,
prepare: async (page) => {
await page.route(
/\/assets\/_-[^/]+\.js$/,
async (route) => {
await new Promise((done) =>
setTimeout(done, 800),
);
await route.continue();
},
);
},
},
);
await waitForHydration(page);
// Wacht tot de vertraagde chunk binnen is en de route zich herstelt
await page.waitForTimeout(1500);
expect(opened.messages).toEqual([]);
expect(opened.violations).toEqual([]);
await eventually(() =>
page
.getByRole('heading', { name: 'Pagina niet gevonden' })
.count(),
).toBe(1);
},
);
it('toont de twee extra knoppen onder /soorten-fotoshoots/ pas na de hydratatie', async () => {
const url = server.origin + '/soorten-fotoshoots/onbekend';
// Zonder JavaScript: precies de HTML van /404, met één knop
const plain = await openPage(url, {
javaScript: false,
expectNotFound: true,
});
await eventually(() =>
plain.page.getByTestId('status-page-home-link').count(),
).toBe(1);
await eventually(() =>
plain.page.getByTestId('status-page-section-link').count(),
).toBe(0);
const { page, ...opened } = await openPage(url, {
expectNotFound: true,
});
await waitForHydration(page);
await eventually(() =>
page.getByTestId('status-page-section-link').count(),
).toBe(1);
await eventually(() =>
page.getByTestId('status-page-home-link').count(),
).toBe(1);
expect(opened.messages).toEqual([]);
});
it('toont op een gewone onbekende URL alleen de knop naar home', async () => {
const { page, ...opened } = await openPage(
server.origin + '/onbekend',
{
expectNotFound: true,
},
);
await waitForHydration(page);
await eventually(() =>
page.getByTestId('status-page-home-link').count(),
).toBe(1);
await eventually(() =>
page.getByTestId('status-page-section-link').count(),
).toBe(0);
expect(opened.messages).toEqual([]);
});
});
// De zoekwaarde (?pakket=, ?shoot=) staat niet in de voorgerenderde HTML en
// wordt pas na de hydratatie toegepast (BR-HYD-10 tot 12)
describe('zoekwaarden na de hydratatie', () => {
const shootField = (page: Page) => page.getByTestId('contact-form-shoot');
it('/?pakket=gezin#contact kiest het pakket en ruimt het adres op', async () => {
const { page, ...opened } = await openPage(
server.origin + '/?pakket=gezin#contact',
);
await waitForHydration(page);
await eventually(() => shootField(page).inputValue()).toBe('gezin');
// De tidy-navigatie haalt de zoekwaarde weg, de hash blijft
await page.waitForFunction(() => location.search === '');
expect(new URL(page.url()).hash).toBe('#contact');
expect(opened.messages).toEqual([]);
expect(opened.violations).toEqual([]);
});
it('/contact?pakket=gezin kiest het pakket en eindigt op /contact', async () => {
const { page, ...opened } = await openPage(
server.origin + '/contact?pakket=gezin',
);
await waitForHydration(page);
await eventually(() => shootField(page).inputValue()).toBe('gezin');
await page.waitForFunction(() => location.search === '');
expect(new URL(page.url()).pathname).toBe('/contact');
expect(opened.messages).toEqual([]);
expect(opened.violations).toEqual([]);
});
it('/portfolio?shoot=gezin past het filter toe en houdt het adres', async () => {
const { page, ...opened } = await openPage(
server.origin + '/portfolio?shoot=gezin',
);
await waitForHydration(page);
await eventually(() =>
page.getByTestId('filter-gezin').getAttribute('aria-pressed'),
).toBe('true');
expect(new URL(page.url()).search).toBe('?shoot=gezin');
expect(opened.messages).toEqual([]);
expect(opened.violations).toEqual([]);
});
});
// V16: de prijzen komen uit Intl.NumberFormat('nl-NL'). Node maakt de HTML,
// Chrome hydrateert; verschillen in ICU geven andere tekst (BR-HYD-17).
describe('prijstekst (V16)', () => {
const pricePaths = [
'/',
...pages.filter((p) => p.startsWith('/soorten-fotoshoots/')),
];
async function priceTexts(page: Page) {
return page.evaluate(() => {
const texts: string[] = [];
const walker = document.createTreeWalker(
document.body,
NodeFilter.SHOW_TEXT,
);
for (let node = walker.nextNode(); node; node = walker.nextNode()) {
if (node.textContent?.includes('€')) {
texts.push(node.textContent);
}
}
return texts;
});
}
it.each(pricePaths)(
'%s toont voor en na de hydratatie dezelfde prijzen',
async (path) => {
const url = server.origin + path;
const server_ = await openPage(url, { javaScript: false });
const before = await priceTexts(server_.page);
const { page, ...opened } = await openPage(url);
await waitForHydration(page);
const after = await priceTexts(page);
expect(before.length).toBeGreaterThan(0);
expect(after).toEqual(before);
expect(opened.messages).toEqual([]);
},
);
});
// V8, BR-LZY-01 en 05: het contactformulier is een luie chunk
describe('contactformulier op /contact (V8)', () => {
it('staat in de HTML, maar verborgen tot het script het op zijn plek zet', async () => {
const html = await (await fetch(server.origin + '/contact')).text();
// Het formulier met zijn velden zit in de bytes van de pagina...
expect(html).toContain('data-testid="contact-form"');
expect(html).toContain('data-testid="contact-form-shoot"');
// ...maar als gestreamd segment: een lege plek in main, het formulier
// in een verborgen div aan het eind van de body
expect(html).toMatch(/<template id="B:0"><\/template>/);
expect(html).toMatch(/<div hidden id="S:0">/);
// Zonder JavaScript is het formulier niet zichtbaar (FR-PR-13)
const plain = await openPage(server.origin + '/contact', {
javaScript: false,
});
expect(await plain.page.getByTestId('contact-form').isVisible()).toBe(
false,
);
});
it('verschijnt in main onder de CSP en geeft geen hydratatiefout', async () => {
const { page, ...opened } = await openPage(server.origin + '/contact');
await waitForHydration(page);
await eventually(() =>
page.locator('main').getByTestId('contact-form').isVisible(),
).toBe(true);
expect(opened.messages).toEqual([]);
// Het verplaatste completion-script mag niet geblokkeerd worden
expect(opened.violations).toEqual([]);
});
it('hydrateert zonder fout als de chunk van het formulier laat komt (BR-LZY-05)', async () => {
const { page, ...opened } = await openPage(server.origin + '/contact', {
prepare: async (page) => {
await page.route(
/\/assets\/ContactForm-[^/]+\.js$/,
async (route) => {
await new Promise((done) => setTimeout(done, 1500));
await route.continue();
},
);
},
});
await waitForHydration(page);
await eventually(() =>
page.locator('main').getByTestId('contact-form').isVisible(),
).toBe(true);
expect(opened.messages).toEqual([]);
expect(opened.violations).toEqual([]);
});
});
// BR-404-07: een URL die de server niet kent maar de router wel. Dit is een
// waarneming voor unit 3, geen controle die de suite laat falen. De
// preview-server draait op Windows en Linux anders (hoofdletters in
// bestandsnamen), dus de Linux-situatie wordt nagespeeld: 404.html met 404.
describe('URL die de server niet kent en de router wel (BR-404-07)', () => {
it.each(['/Over-Mij', '/over-mij/'])('observeert %s', async (path) => {
const real = await fetch(server.origin + path, { redirect: 'manual' });
const observe = async (
served: string,
prepare?: (page: Page) => Promise<void>,
) => {
const { page, ...opened } = await openPage(server.origin + path, {
prepare,
});
await page.waitForTimeout(1500);
const state = await page.evaluate(() => ({
url: location.pathname,
h1: document.querySelector('h1')?.textContent,
titles: [...document.querySelectorAll('title')].map(
(t) => t.textContent,
),
}));
console.info(
`BR-404-07 ${path} (${served}): ${JSON.stringify({ ...state, status: opened.status, messages: opened.messages })}`,
);
};
console.info(
`BR-404-07 ${path}: preview-server geeft ${real.status} ${real.headers.get('content-type')}`,
);
await observe('preview-server van deze machine');
await observe(
'404.html met 404, zoals een hoofdlettergevoelige host',
async (page) => {
await page.route(server.origin + path, async (route) => {
const notFound = await route.fetch({
url: server.origin + '/404.html',
});
await route.fulfill({ response: notFound, status: 404 });
});
},
);
expect(real.status).toBeGreaterThan(0);
});
});
+262
View File
@@ -0,0 +1,262 @@
import { mkdirSync } from 'node:fs';
import { join } from 'node:path';
import { afterAll, beforeAll, describe, expect, it } from 'vitest';
import { eventually, openPage, waitForHydration } from './support/browser.ts';
import { startServer } from './support/server.ts';
// BR-TST-05 (interactie), BR-ENT-06, BR-MAIL-10: wat een bezoeker na de
// hydratatie kan doen, en wat daarvoor en daarna anders is.
let server: Awaited<ReturnType<typeof startServer>>;
beforeAll(async () => {
server = await startServer();
});
afterAll(() => server.close());
describe('mobiel menu', () => {
it('opent en sluit met de knop en met Escape', async () => {
const { page, ...opened } = await openPage(server.origin + '/', {
width: 390,
});
await waitForHydration(page);
const toggle = page.getByTestId('nav-menu-toggle');
const menu = page.locator('#mobile-nav');
expect(await menu.isVisible()).toBe(false);
await toggle.click();
await eventually(() => toggle.getAttribute('aria-expanded')).toBe(
'true',
);
await eventually(() => menu.isVisible()).toBe(true);
await toggle.click();
await eventually(() => toggle.getAttribute('aria-expanded')).toBe(
'false',
);
await eventually(() => menu.isVisible()).toBe(false);
await toggle.click();
await eventually(() => menu.isVisible()).toBe(true);
await page.keyboard.press('Escape');
await eventually(() => menu.isVisible()).toBe(false);
expect(opened.messages).toEqual([]);
expect(opened.violations).toEqual([]);
});
});
describe('navigatie in de browser', () => {
it('gaat naar een andere pagina zonder de pagina te herladen', async () => {
const { page, ...opened } = await openPage(server.origin + '/');
await waitForHydration(page);
// Blijft alleen bestaan als de pagina niet opnieuw geladen wordt
await page.evaluate(() => {
(window as unknown as { staysAlive: boolean }).staysAlive = true;
});
await page
.getByRole('navigation', { name: 'Hoofdmenu' })
.getByRole('link', { name: 'Over mij' })
.click();
await page.waitForURL('**/over-mij');
await eventually(() =>
page.locator('h1').first().textContent(),
).toMatch(/\S/);
expect(
await page.evaluate(
() =>
(window as unknown as { staysAlive?: boolean }).staysAlive,
),
).toBe(true);
expect(await page.title()).toContain('Over mij');
expect(opened.messages).toEqual([]);
expect(opened.violations).toEqual([]);
});
it('zet de focus op main na een navigatie, niet bij het eerste laden (V14)', async () => {
const { page } = await openPage(server.origin + '/');
await waitForHydration(page);
// Even wachten: de focus zou na het hydrateren kunnen schuiven
await page.waitForTimeout(500);
const focused = () =>
page.evaluate(() => document.activeElement?.id ?? '');
expect(await focused()).not.toBe('main');
await page
.getByRole('navigation', { name: 'Hoofdmenu' })
.getByRole('link', { name: 'Over mij' })
.click();
await page.waitForURL('**/over-mij');
await eventually(focused).toBe('main');
});
it('verandert de focus niet als alleen de zoekwaarde of hash wisselt (V14)', async () => {
const { page } = await openPage(
server.origin + '/contact?pakket=gezin',
);
await waitForHydration(page);
// De tidy-navigatie haalt ?pakket= weg; dat telt niet als paginawissel
await page.waitForFunction(() => location.search === '');
await page.waitForTimeout(500);
expect(
await page.evaluate(() => document.activeElement?.id ?? ''),
).not.toBe('main');
});
});
describe('het e-mailadres', () => {
it('staat niet in de HTML en komt er na de hydratatie als link', async () => {
const plain = await openPage(server.origin + '/', {
javaScript: false,
});
expect(await plain.page.getByTestId('footer-email-link').count()).toBe(
0,
);
expect(await plain.page.locator('a[href^="mailto:"]').count()).toBe(0);
const { page, ...opened } = await openPage(server.origin + '/');
await waitForHydration(page);
const link = page.getByTestId('footer-email-link');
await eventually(() => link.count()).toBe(1);
expect(await link.getAttribute('href')).toMatch(/^mailto:.+@.+/);
expect(opened.messages).toEqual([]);
});
});
describe('tidy navigatie op de contactpagina (V14)', () => {
it('eindigt op /contact zonder extra geschiedenisregel en bovenaan', async () => {
const { page } = await openPage(
server.origin + '/contact?pakket=gezin',
);
const before = await page.evaluate(() => history.length);
await waitForHydration(page);
await page.waitForFunction(() => location.search === '');
expect(new URL(page.url()).pathname).toBe('/contact');
expect(await page.evaluate(() => history.length)).toBe(before);
expect(await page.evaluate(() => window.scrollY)).toBe(0);
});
});
describe('/?pakket=...#contact', () => {
it('scrolt naar het contactgedeelte', async () => {
const { page, ...opened } = await openPage(
server.origin + '/?pakket=gezin#contact',
{ height: 800 },
);
await waitForHydration(page);
const top = () =>
page
.getByTestId('contact-section')
.evaluate((section) => section.getBoundingClientRect().top);
// De scroll is vloeiend en begint na de hydratatie
await eventually(async () => (await top()) < 400).toBe(true);
expect(await page.evaluate(() => window.scrollY)).toBeGreaterThan(0);
expect(opened.messages).toEqual([]);
expect(opened.violations).toEqual([]);
});
});
describe('structured data en CSP (BR-SCR-22)', () => {
it('JSON-LD blijft inline staan zonder dat de CSP het blokkeert', async () => {
const { page, ...opened } = await openPage(server.origin + '/over-mij');
await waitForHydration(page);
expect(
await page.locator('script[type="application/ld+json"]').count(),
).toBeGreaterThan(0);
expect(opened.violations).toEqual([]);
expect(opened.messages).toEqual([]);
});
});
// V15: de stijlen staan in de HTML, de pagina springt niet bij de hydratatie.
// Een screenshotvergelijking met en zonder JavaScript gaat naar
// E2E_SCREENSHOT_DIR (alleen als die gezet is); er wordt naar gekeken, niet
// op pixels vergeleken, want Reveal en de afbeeldingen veranderen na de
// hydratatie bewust van uiterlijk (eenheid 2).
describe('stijlen zonder en met JavaScript (V15)', () => {
it('heeft de stijlen in de HTML', async () => {
const html = await (await fetch(server.origin + '/over-mij')).text();
expect(html).toMatch(/<style data-emotion=/);
expect(html).toMatch(/<link rel="stylesheet" href="\/assets\/index-/);
});
it.each([390, 1280])(
'houdt de kop en de pagina op hun plek bij %i px',
async (width) => {
const url = server.origin + '/over-mij';
const dir = process.env.E2E_SCREENSHOT_DIR;
if (dir) mkdirSync(dir, { recursive: true });
const box = (page: import('playwright-core').Page) =>
page.evaluate(() => {
const rect = (selector: string) => {
const { x, y, width, height } = document
.querySelector(selector)!
.getBoundingClientRect();
return { x, y, width, height };
};
return {
h1: rect('h1'),
main: rect('main'),
footerTop: rect('footer').y + window.scrollY,
};
});
const plain = await openPage(url, { javaScript: false, width });
await plain.page.waitForLoadState('networkidle');
const withoutScript = await box(plain.page);
if (dir) {
await plain.page.screenshot({
path: join(dir, `over-mij-${width}-zonder-js.png`),
});
}
const { page, ...opened } = await openPage(url, { width });
await waitForHydration(page);
await page.waitForLoadState('networkidle');
await page.waitForTimeout(1500);
const withScript = await box(page);
if (dir) {
await page.screenshot({
path: join(dir, `over-mij-${width}-met-js.png`),
});
}
// De kop staat op dezelfde plek; tot ruim een regel verschil in de
// hoogte van de pagina is toegestaan (afbeeldingen, e-mailregel)
expect(withScript.h1.x).toBeCloseTo(withoutScript.h1.x, 0);
expect(withScript.h1.y).toBeCloseTo(withoutScript.h1.y, 0);
expect(withScript.h1.width).toBeCloseTo(withoutScript.h1.width, 0);
expect(withScript.main.y).toBeCloseTo(withoutScript.main.y, 0);
expect(opened.messages).toEqual([]);
},
);
});
// V9: de reviews staan in de HTML; de kopieën naast de langste zijn alleen
// voor zoekmachines en schermlezers verborgen en verstoren de lay-out niet
describe('reviews voor het laden van de carrousel (V9)', () => {
it('toont één review, de rest is 1 px, aria-hidden en inert', async () => {
const { page } = await openPage(server.origin + '/', {
javaScript: false,
width: 390,
});
const slides = await page
.getByTestId('testimonials')
.locator('[data-testid^="testimonial-"]')
.evaluateAll((elements) =>
elements.map((element) => {
const { width, height } = element.getBoundingClientRect();
return {
size: [Math.round(width), Math.round(height)],
hidden: !!element.closest(
'[aria-hidden="true"][inert]',
),
};
}),
);
expect(slides.length).toBeGreaterThan(1);
const [shown, ...copies] = slides;
expect(shown.hidden).toBe(false);
expect(shown.size[1]).toBeGreaterThan(50);
for (const copy of copies) {
expect(copy).toEqual({ size: [1, 1], hidden: true });
}
});
});
+157
View File
@@ -0,0 +1,157 @@
// @vitest-environment jsdom
import { afterAll, beforeAll, describe, expect, it } from 'vitest';
import siteContent from '../src/content/siteContent.ts';
import testimonials from '../src/content/testimonials.ts';
import { emailAddress } from '../src/lib/emailAddress.ts';
import { visibleTestimonials } from '../src/lib/visibleTestimonials.ts';
import { footerNav, mainNav, type NavItem } from '../src/navigation.ts';
import { canonicalUrl, pageHead, siteName } from '../src/seo.ts';
import sitePages from '../src/sitePages.ts';
import type { RoutePath } from '../src/navigation.ts';
import { startServer } from './support/server.ts';
// BR-TST-06: wat een bezoeker of zoekmachine zonder JavaScript krijgt. Alleen
// `fetch` van de preview-server en een parser die geen script uitvoert (de
// jsdom-omgeving is hier alleen voor DOMParser; er is geen browser).
let server: Awaited<ReturnType<typeof startServer>>;
beforeAll(async () => {
server = await startServer();
});
afterAll(() => server.close());
async function fetchDocument(path: string, status = 200) {
const response = await fetch(server.origin + path);
expect(response.status).toBe(status);
const html = await response.text();
// DOMParser voert geen script uit: er wordt alleen gelezen
return {
html,
document: new DOMParser().parseFromString(html, 'text/html'),
};
}
const targets = (items: readonly NavItem[]): string[] =>
items.flatMap((item) => [item.to, ...targets(item.children ?? [])]);
const navTargets = [...new Set([...targets(mainNav), ...targets(footerNav)])];
// Zichtbare tekst van main buiten de h1: geen scripts, stijlen of templates
function bodyText(document: Document) {
const main = document.querySelector('main')!.cloneNode(true) as Element;
for (const node of main.querySelectorAll(
'h1, script, style, template, noscript, [hidden]',
)) {
node.remove();
}
return (main.textContent ?? '').replace(/\s+/g, ' ').trim();
}
// V17: inline event-handler-attributen en javascript:-URL's zijn geen script
// voor de runner maar de CSP blokkeert ze; ze mogen er niet in staan
function inlineScriptVectors(document: Document) {
return [...document.querySelectorAll('*')].flatMap((element) =>
[...element.attributes]
.filter(
({ name, value }) =>
name.startsWith('on') ||
value.trim().toLowerCase().startsWith('javascript:'),
)
.map(({ name }) => `${element.tagName.toLowerCase()}[${name}]`),
);
}
// De samengestelde mailadres-vormen die nergens in de HTML mogen staan; de
// runner (BR-MAIL-10) controleert ze ook in de scripts en stijlen
function addressForms(address: string) {
const [user, domain] = address.split('@');
return [address, `${user}%40${domain}`, `${user}&#64;${domain}`].map(
(form) => form.toLowerCase(),
);
}
const paths = Object.keys(sitePages) as RoutePath[];
describe.each(paths)('rauwe HTML van %s', (path) => {
it('heeft titel, kop, tekst, links, canonical en gegevens', async () => {
const { html, document } = await fetchDocument(path);
const head = pageHead(path);
// Precies één titel en één beschrijving (V11), de titel uit het register
const titles = document.querySelectorAll('title');
expect(titles).toHaveLength(1);
expect(titles[0].textContent).toBe(head.meta[0].title);
expect(
document.querySelectorAll('meta[name="description"]'),
).toHaveLength(1);
// Eén h1, en genoeg tekst eromheen om te lezen zonder JavaScript
expect(document.querySelectorAll('h1')).toHaveLength(1);
expect(bodyText(document).length).toBeGreaterThanOrEqual(40);
// Een link naar elk doel van het hoofdmenu en de footer
const hrefs = new Set(
[...document.querySelectorAll('a[href]')].map((a) =>
a.getAttribute('href'),
),
);
for (const target of navTargets) expect(hrefs).toContain(target);
const canonical = document.querySelectorAll('link[rel="canonical"]');
expect(canonical).toHaveLength(1);
expect(canonical[0].getAttribute('href')).toBe(canonicalUrl(path));
// JSON-LD: aanwezig en leesbaar
const blocks = [
...document.querySelectorAll('script[type="application/ld+json"]'),
];
expect(blocks.length).toBeGreaterThan(0);
for (const block of blocks) {
expect(() => JSON.parse(block.textContent ?? '')).not.toThrow();
}
expect(html).not.toContain('data-fallback');
expect(inlineScriptVectors(document)).toEqual([]);
const address = emailAddress(siteContent.email);
expect(address).toBeTruthy();
for (const form of addressForms(address!)) {
expect(html.toLowerCase()).not.toContain(form);
}
});
});
describe('rauwe HTML van 404.html', () => {
it('heeft één titel, één noindex en geen beschrijving of canonical', async () => {
// 404.html als bestand: status 200 (BR-SRV-04)
const { html, document } = await fetchDocument('/404.html');
const titles = document.querySelectorAll('title');
expect(titles).toHaveLength(1);
expect(titles[0].textContent).toBe(
`Pagina niet gevonden | ${siteName}`,
);
const robots = document.querySelectorAll('meta[name="robots"]');
expect(robots).toHaveLength(1);
expect(robots[0].getAttribute('content')).toBe('noindex');
expect(document.querySelectorAll('h1')).toHaveLength(1);
expect(bodyText(document).length).toBeGreaterThanOrEqual(40);
expect(html).not.toContain('data-fallback');
expect(inlineScriptVectors(document)).toEqual([]);
});
it('is wat de server voor een onbekende URL stuurt, met status 404', async () => {
const { html } = await fetchDocument('/onbekend', 404);
const file = await (await fetch(server.origin + '/404.html')).text();
expect(html).toBe(file);
});
});
describe('reviews op de homepage (V9)', () => {
it('heeft de tekst van elke zichtbare review in de HTML', async () => {
const { document } = await fetchDocument('/');
const text = (document.body.textContent ?? '').replace(/\s+/g, ' ');
const shown = visibleTestimonials(testimonials);
expect(shown.length).toBeGreaterThan(0);
for (const { quote, author } of shown) {
expect(text).toContain(quote);
expect(text).toContain(author);
}
});
});
+30
View File
@@ -0,0 +1,30 @@
import { afterAll, beforeAll, describe, expect, it } from 'vitest';
import { openPage, waitForHydration } from './support/browser.ts';
import { startServer } from './support/server.ts';
// Eerste echte-browserproef: de pagina laadt onder de productie-CSP, hydrateert
// en meldt niets. Valt dit om, dan is de oorzaak eerst hier te vinden.
let server: Awaited<ReturnType<typeof startServer>>;
beforeAll(async () => {
server = await startServer();
});
afterAll(() => server.close());
describe.each([
['/', 200],
['/contact', 200],
['/onbekend', 404],
])('%s', (path, status) => {
it('laadt en hydrateert zonder meldingen of CSP-overtredingen', async () => {
const opened = await openPage(server.origin + path, {
expectNotFound: status === 404,
});
expect(opened.status).toBe(status);
await expect(
opened.page.getByRole('heading', { level: 1 }).first().isVisible(),
).resolves.toBe(true);
await waitForHydration(opened.page);
expect(opened.messages).toEqual([]);
expect(opened.violations).toEqual([]);
});
});
+136
View File
@@ -0,0 +1,136 @@
import {
chromium,
type Browser,
type BrowserContext,
type Page,
} from 'playwright-core';
import { afterAll, afterEach, expect } from 'vitest';
// Eén Chrome per testbestand, een eigen context (cookies, JavaScript aan of
// uit) per pagina. Zonder CHROME_PATH zoekt Playwright het geïnstalleerde Chrome.
let browser: Promise<Browser> | undefined;
const contexts = new Set<BrowserContext>();
// --no-sandbox en --disable-dev-shm-usage zijn nodig in CI. De Lighthouse-flags
// bevatten ook --headless=new; Playwright zet headless zelf.
const extraArgs = (process.env.LIGHTHOUSE_CHROME_FLAGS ?? '')
.split(/\s+/)
.filter((flag) => flag && !flag.startsWith('--headless'));
function launch() {
browser ??= chromium.launch({
...(process.env.CHROME_PATH
? { executablePath: process.env.CHROME_PATH }
: { channel: 'chrome' as const }),
args: extraArgs,
});
return browser;
}
afterEach(async () => {
await Promise.all([...contexts].map((context) => context.close()));
contexts.clear();
});
afterAll(async () => {
await (await browser)?.close();
browser = undefined;
});
export interface OpenedPage {
page: Page;
status: number;
// Console-fouten en -waarschuwingen en niet-afgevangen fouten van de pagina
messages: string[];
// securitypolicyviolation-events: wat de CSP blokkeert
violations: string[];
}
export interface OpenOptions {
javaScript?: boolean;
width?: number;
height?: number;
// Een onbekende URL krijgt van de server bewust status 404 (BR-SRV-05).
// Chrome meldt dat voor het document zelf als console-fout. Alleen die ene
// melding wordt genegeerd; elke andere fout, ook een 404 voor een bestand
// of een hydratatiefout, blijft staan.
expectNotFound?: boolean;
// Voor de navigatie: bijvoorbeeld een request vertragen of vervangen
prepare?: (page: Page) => Promise<void>;
}
const NAVIGATION_404 =
'Failed to load resource: the server responded with a status of 404 (Not Found)';
// Opent de pagina en verzamelt alles wat de tests moeten kunnen aanwijzen. De
// luisteraars staan er al voor de navigatie, anders mist een test de fouten
// van de eerste render.
export async function openPage(
url: string,
{
javaScript = true,
width = 1280,
height = 800,
expectNotFound = false,
prepare,
}: OpenOptions = {},
): Promise<OpenedPage> {
const context = await (
await launch()
).newContext({
javaScriptEnabled: javaScript,
viewport: { width, height },
});
contexts.add(context);
const page = await context.newPage();
const messages: string[] = [];
const violations: string[] = [];
page.on('console', (message) => {
if (message.type() !== 'error' && message.type() !== 'warning') return;
if (
expectNotFound &&
message.text() === NAVIGATION_404 &&
message.location().url === url
) {
return;
}
messages.push(`${message.type()}: ${message.text()}`);
});
page.on('pageerror', (error) =>
messages.push(`pageerror: ${error.message}`),
);
await page.exposeFunction('reportViolation', (violation: string) =>
violations.push(violation),
);
await page.addInitScript(() => {
document.addEventListener('securitypolicyviolation', (event) => {
(
window as unknown as {
reportViolation: (violation: string) => void;
}
).reportViolation(
`${event.violatedDirective} blokkeerde ${event.blockedURI}`,
);
});
});
await prepare?.(page);
const response = await page.goto(url, { waitUntil: 'load' });
return { page, status: response?.status() ?? 0, messages, violations };
}
// De pagina is gehydrateerd als de e-mailplaceholders zijn ingevuld
// (BR-MAIL-02: er staat alleen een placeholder tot de hydratatie klaar is).
// Een hydratatiefout zou al eerder in `messages` staan.
export async function waitForHydration(page: Page) {
await page.waitForFunction(
() => !document.querySelector('[data-email-pending]'),
);
}
// Vitest kent de wachtende matchers van Playwright niet; expect.poll herhaalt
// de vraag aan de pagina tot het antwoord klopt of de tijd om is.
export const eventually = <T>(read: () => Promise<T>) =>
expect.poll(read, { timeout: 15_000, interval: 100 });
+12
View File
@@ -0,0 +1,12 @@
import { existsSync } from 'node:fs';
import { join } from 'node:path';
import { clientDir } from './server.ts';
// De browsertests bouwen niets: zonder build testen ze een oude of lege map
export default function setup() {
if (!existsSync(join(clientDir, 'index.html'))) {
throw new Error(
`dist/client ontbreekt (${clientDir}). Draai eerst: pnpm build`,
);
}
}
+24
View File
@@ -0,0 +1,24 @@
import type { AddressInfo } from 'node:net';
import { resolve } from 'node:path';
import { startPreviewServer } from '../../config/previewServer.ts';
// De gebouwde site: `pnpm build` schrijft hem, de tests bouwen niets. Relatief
// aan de werkmap (web/), zoals `pnpm preview`; import.meta.url is in een
// jsdom-testbestand geen bestands-URL.
export const clientDir = resolve('dist/client');
// Dezelfde server als `pnpm preview`, met de productie-CSP en echte 404's,
// op een poort die het systeem kiest zodat tests elkaar niet in de weg zitten
export async function startServer() {
const server = await startPreviewServer(clientDir, 0);
const { port } = server.address() as AddressInfo;
return {
origin: `http://127.0.0.1:${port}`,
close: () =>
new Promise<void>((resolve, reject) => {
server.close((error) => (error ? reject(error) : resolve()));
// Open keep-alive-verbindingen van Chrome houden close() op
server.closeAllConnections();
}),
};
}
+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() {}
};
}
+19
View File
@@ -0,0 +1,19 @@
import { defineConfig } from 'vitest/config';
// Browsertests (BR-TST-05, BR-TST-06) tegen de gebouwde site in dist/client.
// Los van vite.config.ts: de Start-plugin en de jsdom-opzet van de
// unittests horen hier niet bij. Geen dekking, de tests meten de build.
export default defineConfig({
// De tests lezen het register en de content uit src (zelfde bron als de site)
resolve: { tsconfigPaths: true },
test: {
environment: 'node',
include: ['e2e/**/*.e2e.ts'],
// De CI-runner (Raspberry Pi) is veel trager dan een pc: Chrome starten
// en een pagina hydrateren kost daar vele seconden
testTimeout: 60_000,
hookTimeout: 60_000,
// Bouwt niets; controleert alleen dat dist/client er is
globalSetup: ['./e2e/support/globalSetup.ts'],
},
});