Files
AndreaSlopFotografie/web/e2e/hostInjection.e2e.ts
SluijsensandClaude Sonnet 5.5 ad0b114828 Hero from the CMS: markers HERO-HTML and HERO-PRELOAD, hero key in the data block, picture per ratio, baked fallback
The prerendered hero is plain HTML between the markers (first photo, h1, buttons), the slider takes over after hydration with the hero of the host block, the API or the build. The head preload is added to the finished HTML. Hero texts move into nl.json. The stand-in host and the e2e tests cover the hero.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-16 16:48:00 +01:00

425 lines
16 KiB
TypeScript

import { afterAll, beforeAll, describe, expect, it } from 'vitest';
import type { LiveData } from '../config/hostInjector.ts';
import {
eventually,
openPage,
waitForHydration,
type OpenedPage,
} from './support/browser.ts';
import { startServer } from './support/server.ts';
// De CMS-host vult markers in de geprerenderde HTML (plan: aidlc-docs/features/
// asf-cms-host-injection). Hier doet de previewserver alsof hij die host is
// (config/hostInjector.ts), met data die van de gebakken data afwijkt. Wat
// getest wordt: de HTML die de host schrijft is leesbaar zonder JavaScript,
// de pagina hydrateert zonder fout, toont daarna de actuele data zonder zelf
// de API te vragen, en valt terug op wat gebakken is als de data niet bruikbaar
// is.
const AUTHORED = 'https://andreaslop.nl';
let live: { data: LiveData; publicBaseUrl?: string } | null = null;
let server: Awaited<ReturnType<typeof startServer>>;
beforeAll(async () => {
server = await startServer({
inject: () =>
live && {
data: live.data,
authoredBaseUrl: AUTHORED,
publicBaseUrl: live.publicBaseUrl,
},
});
});
afterAll(() => server.close());
const pakket = (
slug: string,
title: string,
price: string,
order: number,
extra: Record<string, unknown> = {},
) => ({
slug,
title,
price,
features: [`Kenmerk van ${title}`],
displayOrder: order,
...extra,
});
const FIVE = [
pakket('zwangerschap', 'Zwangerschap', '€ 200', 0),
pakket('newborn', 'Newborn', '€ 210', 1, { featured: true }),
pakket('gezin', 'Gezin', '€ 220', 2),
pakket('loveshoot', 'Loveshoot', '€ 230', 3),
pakket('portret', 'Portret', '€ 240', 4),
];
const NO_BANNERS = { top: null, bottom: null };
const html = async (path: string) => (await fetch(server.origin + path)).text();
const cards = (page: OpenedPage['page']) =>
page.locator('[data-testid^="price-card-"]:not([data-testid$="-book"])');
// Elke test begint zonder injectie en zet live zelf
const inject = (data: LiveData, publicBaseUrl?: string) => {
live = { data, publicBaseUrl };
};
describe('markers in de gebouwde pagina', () => {
it('heeft ze op de plekken van het contract, en niet op andere', async () => {
live = null;
const home = await html('/');
for (const marker of [
'OFFERINGS-HTML',
'BANNER-TOP-HTML',
'BANNER-BOTTOM-HTML',
'HERO-HTML',
'HERO-PRELOAD',
]) {
expect(home.split(`<!--CMS:${marker}-->`)).toHaveLength(2);
expect(home.split(`<!--/CMS:${marker}-->`)).toHaveLength(2);
}
for (const path of [
'/',
'/over-mij',
'/contact',
'/soorten-fotoshoots',
]) {
const page = await html(path);
expect(page.split('<!--CMS:DATA-->')).toHaveLength(2);
expect(page).toMatch(
/<!--CMS:DATA--><script type="application\/json" id="cms-data">\{/,
);
}
// Prijs-JSON-LD en inline prijs alleen op de pakketpagina's
for (const slug of ['newborn', 'zwangerschap', 'gezin']) {
const page = await html(`/soorten-fotoshoots/${slug}`);
expect(page).toContain(
`<!--CMS:OFFER-JSON-LD slug="${slug}"--><script type="application/ld+json">`,
);
expect(page).toContain(`data-cms-price="${slug}"`);
}
for (const slug of ['loveshoot', 'portret']) {
const page = await html(`/soorten-fotoshoots/${slug}`);
expect(page).not.toContain('CMS:OFFER-JSON-LD');
expect(page).not.toContain('data-cms-price');
}
});
});
describe('met data van de host die afwijkt van de build', () => {
it('schrijft leesbare HTML zonder JavaScript', async () => {
inject({
offerings: FIVE,
banners: {
top: {
title: 'Nieuw',
text: 'Nog twee plekken',
position: 'top',
},
bottom: { title: 'Onder', position: 'bottom' },
},
});
const home = await html('/');
// Eén pakket per kaart met de nieuwe prijs, de uitgelichte gemarkeerd
for (const price of ['200', '210', '220', '230', '240']) {
expect(home).toContain(`€&nbsp;${price}`);
}
expect(home).toContain('data-slug="newborn" data-featured="true"');
expect(home).toContain('<strong>Nieuw</strong>');
expect(home).toContain('<strong>Onder</strong>');
// De gebakken prijs (175) staat er niet meer in de lijst
const list = home.slice(
home.indexOf('<!--CMS:OFFERINGS-HTML-->'),
home.indexOf('<!--/CMS:OFFERINGS-HTML-->'),
);
expect(list).not.toContain('175');
});
it('hydrateert zonder fout en toont daarna de actuele data zonder API-verzoek', async () => {
inject({
offerings: FIVE,
banners: {
top: { title: '', text: 'Nog twee plekken', position: 'top' },
bottom: { title: 'Onder', text: 't', position: 'bottom' },
},
});
const requested: string[] = [];
const { page, messages } = await openPage(server.origin + '/', {
prepare: async (p) => {
p.on('request', (request) => {
if (request.url().includes('/api/v1/offerings')) {
requested.push(request.url());
}
});
},
});
await waitForHydration(page);
await eventually(() => cards(page).count()).toBe(5);
expect(await cards(page).first().textContent()).toContain('€\u00a0200');
expect(await page.locator('.cms-offerings').count()).toBe(0);
expect(await page.getByTestId('price-top-bar').textContent()).toContain(
'Nog twee plekken',
);
expect(await page.getByTestId('price-banner').textContent()).toContain(
'Onder',
);
// De uitgelichte kaart is gemarkeerd
expect(await page.locator('[data-featured="true"]').count()).toBe(1);
// Het datablok is er: de site vraagt de API niet zelf
expect(requested).toEqual([]);
expect(messages).toEqual([]);
});
it('verbergt de banners als de host geen actieve heeft (204)', async () => {
inject({ offerings: FIVE, banners: NO_BANNERS });
const { page, messages } = await openPage(server.origin + '/');
await waitForHydration(page);
await eventually(() => cards(page).count()).toBe(5);
expect(await page.getByTestId('price-top-bar').count()).toBe(0);
expect(await page.getByTestId('price-banner').count()).toBe(0);
expect(messages).toEqual([]);
});
it('verbergt de sectie als de host alle pakketten heeft uitgezet', async () => {
inject({ offerings: [], banners: NO_BANNERS });
const { page, messages } = await openPage(server.origin + '/');
await waitForHydration(page);
await eventually(() => page.getByTestId('pricing').count()).toBe(0);
expect(messages).toEqual([]);
});
it('past de formulierkeuze aan op de data van de host', async () => {
inject({ offerings: FIVE, banners: NO_BANNERS });
const { page, messages } = await openPage(
server.origin + '/contact?pakket=portret',
);
await waitForHydration(page);
await eventually(() =>
page.getByTestId('contact-form-shoot').locator('option').count(),
).toBe(7); // Kies een optie, vijf pakketten, Overig
expect(messages).toEqual([]);
});
it('zet de prijs op de pakketpagina in de HTML, in de JSON-LD en na hydratatie', async () => {
inject({
offerings: [pakket('newborn', 'Newborn', '€ 1.250', 0)],
banners: NO_BANNERS,
});
const raw = await html('/soorten-fotoshoots/newborn');
expect(raw).toMatch(/data-cms-price="newborn"[^>]*>€\u00a01\.250</);
expect(raw).toContain('"price":1250');
const { page, messages } = await openPage(
server.origin + '/soorten-fotoshoots/newborn',
);
await waitForHydration(page);
await eventually(() =>
page.locator('[data-cms-price="newborn"]').textContent(),
).toBe('€\u00a01.250');
const prices = await page.evaluate(() =>
[...document.querySelectorAll('script[type="application/ld+json"]')]
.map((script) => JSON.parse(script.textContent ?? ''))
.flatMap(
(data) => JSON.stringify(data).match(/"price":\d+/g) ?? [],
),
);
expect(prices).toEqual(['"price":1250']);
expect(messages).toEqual([]);
});
it('haalt de prijs uit de JSON-LD als het pakket niet meer bestaat', async () => {
inject({
offerings: [pakket('gezin', 'Gezin', '€ 220', 0)],
banners: NO_BANNERS,
});
const raw = await html('/soorten-fotoshoots/newborn');
expect(raw).not.toContain('"offers"');
// Het pakket dat er nog wel is houdt zijn prijs
expect(await html('/soorten-fotoshoots/gezin')).toContain(
'"price":220',
);
});
});
describe('adres van de site', () => {
it('zet canonical, og: en JSON-LD op het adres van de host, ook na navigatie', async () => {
inject(
{ offerings: FIVE, banners: NO_BANNERS },
'https://test.voorbeeld.nl',
);
const raw = await html('/');
expect(raw).not.toContain(AUTHORED);
expect(raw).toContain(
'rel="canonical" href="https://test.voorbeeld.nl/"',
);
const { page, messages } = await openPage(server.origin + '/');
await waitForHydration(page);
// Navigeren binnen de site: de head wordt opnieuw opgebouwd en moet het
// adres uit het datablok gebruiken, niet het gebakken productie-adres
await page.getByRole('link', { name: 'Over mij' }).first().click();
await eventually(() => page.title()).toContain('Over mij');
expect(
await page.locator('link[rel="canonical"]').getAttribute('href'),
).toBe('https://test.voorbeeld.nl/over-mij');
expect(
await page
.locator('meta[property="og:image"]')
.getAttribute('content'),
).toMatch(/^https:\/\/test\.voorbeeld\.nl\//);
expect(messages).toEqual([]);
});
});
describe('als de data niet bruikbaar is', () => {
it('toont wat gebakken is bij een datablok zonder bruikbare lijst', async () => {
// De host schreef een blok waar geen lijst in staat. De site gelooft
// dat niet en houdt de gebakken pakketten (zonder fout).
inject({ offerings: 'kapot', banners: NO_BANNERS });
const { page, messages } = await openPage(server.origin + '/');
await waitForHydration(page);
await eventually(() => cards(page).count()).toBe(3);
expect(messages).toEqual([]);
});
it('vangt vijandige tekst op: geen script, wel de tekst', async () => {
inject({
offerings: [
pakket(
'newborn',
'<img src=x onerror="window.pwned=1">',
'€ 200',
0,
{
features: ['<script>window.pwned=1</script>'],
},
),
],
banners: {
top: null,
bottom: { title: '<b onmouseover=1>x</b>', position: 'bottom' },
},
});
const raw = await html('/');
expect(raw).not.toContain('<img src=x');
expect(raw).not.toContain('<script>window.pwned');
const { page, messages } = await openPage(server.origin + '/');
await waitForHydration(page);
await eventually(() => cards(page).count()).toBe(1);
expect(await page.evaluate(() => 'pwned' in window)).toBe(false);
expect(await cards(page).first().textContent()).toContain(
'<img src=x onerror="window.pwned=1">',
);
expect(messages).toEqual([]);
});
});
describe('zonder host die injecteert', () => {
it('toont de gebakken pakketten en vraagt de API zelf, zoals voor de injectie', async () => {
live = null;
const requested: string[] = [];
const { page, messages } = await openPage(server.origin + '/', {
prepare: async (p) => {
p.on('request', (request) => {
if (request.url().includes('/api/v1/offerings')) {
requested.push(new URL(request.url()).pathname);
}
});
},
});
await waitForHydration(page);
await eventually(() => cards(page).count()).toBe(3);
await eventually(async () => requested.length).toBe(3);
// Het blok dat de build schreef telt niet als data van de host
expect(requested.sort()).toEqual([
'/api/v1/offerings',
'/api/v1/offerings/banner',
'/api/v1/offerings/banner',
]);
expect(messages).toEqual([]);
});
});
const hostHero = (extra: Record<string, unknown> = {}) => ({
display: 'slideshow',
title: 'Nieuwe titel',
tagline: 'Nieuw label',
buttons: [{ label: 'Boek nu', target: '#contact' }],
slides: ['een', 'twee'].map((name) => ({
id: name,
alt: `Alt ${name}`,
decorative: false,
image: {
width: 100,
height: 80,
focus: { x: 0.25, y: 0.75 },
src: '/favicon.png',
variants: [],
},
})),
...extra,
});
describe('de hero van de host', () => {
it('schrijft de eerste foto, de titel en de preload in de HTML', async () => {
inject({ offerings: FIVE, banners: NO_BANNERS, hero: hostHero() });
const home = await html('/');
const region = home.slice(
home.indexOf('<!--CMS:HERO-HTML-->'),
home.indexOf('<!--/CMS:HERO-HTML-->'),
);
expect(region).toContain('Nieuwe titel');
expect(region).toContain('alt="Alt een"');
expect(region).not.toContain('Alt twee');
expect(region).toContain('style="object-position:25% 75%"');
expect(region).toContain('href="#contact"');
expect(home).toContain(
'<!--CMS:HERO-PRELOAD--><link rel="preload" as="image" href="/favicon.png" fetchpriority="high"><!--/CMS:HERO-PRELOAD-->',
);
});
it('toont na hydratatie de slides van de host, zonder API-verzoek', async () => {
inject({ offerings: FIVE, banners: NO_BANNERS, hero: hostHero() });
const requested: string[] = [];
const { page, messages } = await openPage(server.origin + '/', {
prepare: async (p) => {
p.on('request', (request) => {
if (request.url().includes('/api/v1/hero')) {
requested.push(request.url());
}
});
},
});
await waitForHydration(page);
await eventually(() =>
page.locator('[aria-roledescription="carousel"] h1').textContent(),
).toContain('Nieuwe titel');
expect(
await page
.locator('[aria-roledescription="carousel"] img')
.first()
.getAttribute('alt'),
).toBe('Alt een');
expect(requested).toEqual([]);
expect(messages).toEqual([]);
});
it('laat de gebakken hero staan als de data niet bruikbaar is', async () => {
inject({
offerings: FIVE,
banners: NO_BANNERS,
hero: hostHero({ slides: [] }),
});
const home = await html('/');
// The data block still holds what the host sent; the region keeps the
// baked hero
const region = home.slice(
home.indexOf('<!--CMS:HERO-HTML-->'),
home.indexOf('<!--/CMS:HERO-HTML-->'),
);
expect(region).not.toContain('Nieuwe titel');
expect(region).toContain('Andrea Slop');
expect(home).toContain('<!--CMS:HERO-PRELOAD--><link');
});
});