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:
@@ -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);
|
||||
});
|
||||
});
|
||||
@@ -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 });
|
||||
}
|
||||
});
|
||||
});
|
||||
@@ -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}@${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);
|
||||
}
|
||||
});
|
||||
});
|
||||
@@ -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([]);
|
||||
});
|
||||
});
|
||||
@@ -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 });
|
||||
@@ -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`,
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -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();
|
||||
}),
|
||||
};
|
||||
}
|
||||
@@ -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
@@ -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,
|
||||
});
|
||||
|
||||
@@ -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([]);
|
||||
});
|
||||
});
|
||||
|
||||
@@ -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
@@ -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() {}
|
||||
};
|
||||
}
|
||||
|
||||
@@ -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'],
|
||||
},
|
||||
});
|
||||
Reference in New Issue
Block a user