Files
AndreaSlopFotografie/web/e2e/hostInjection.e2e.ts
T
SluijsensandClaude Sonnet 5.5 bf21b6f690 Builds the markers, data block and stand-in host for the CMS host injection
The pages carry the CMS markers (data block, list regions, JSON-LD price,
inline price); PackagesProvider reads the host's data block after hydration
and asks the API only when there is none; the site address comes from the
block. A stand-in for the host (config/hostInjector.ts, --cms-data in the
preview server) and browser tests check the behaviour with different data.

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

340 lines
13 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',
]) {
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([]);
});
});