Files
AndreaSlopFotografie/web/src/app.test.tsx
T
SluijsensandClaude Sonnet 5.5 e09459423f Connects the contact form to the CMS API through the cms-client package
Copies the headless cms-client package (SlpSoftware 93fa729) and builds the
form on useContactForm: availability check when the form is in view (no
request while switched off), the readable shoot label as subject, the Friendly
Captcha widget as its own lazy chunk, trackEvent for contact-sent and
contact-failed. Removes the old reducer, validation and submit stub.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-10 23:21:02 +01:00

648 lines
26 KiB
TypeScript
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
import { screen, waitFor, within } from '@testing-library/react';
import userEvent from '@testing-library/user-event';
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
import lighthouseConfig from '../lighthouserc.cjs';
import shootTypes from './content/shootTypes';
import { shootPagePath } from './lib/shootPages';
import { siteUrl } from './seo';
import { sitemapXml } from './sitemap';
import { FakeIntersectionObserver } from './test/fakeIntersectionObserver';
import sitePages from './sitePages';
import { axeResults } from './test/axe';
import { expectShell, renderApp } from './test/renderApp';
import type { SocialLink } from './content/types';
// Laat PageIntro op verzoek crashen, om de foutpagina binnen de shell te testen
const crash = vi.hoisted(() => ({ enabled: false }));
vi.mock('./components/PageIntro/PageIntro', async (importOriginal) => {
const original =
await importOriginal<
typeof import('./components/PageIntro/PageIntro')
>();
return {
default: (props: Parameters<typeof original.default>[0]) => {
if (crash.enabled) throw new Error('kapot');
return original.default(props);
},
};
});
// Lets a test replace the social links, e.g. without a valid Instagram link
const socials = vi.hoisted(() => ({
override: null as SocialLink[] | null,
}));
vi.mock('./content/siteContent', async (importOriginal) => {
const original = (
await importOriginal<typeof import('./content/siteContent')>()
).default;
return {
default: {
...original,
get socials() {
return socials.override ?? original.socials;
},
},
};
});
// The homepage's review carousel (Zag) needs an IntersectionObserver and
// Element.scrollTo, which jsdom lacks
beforeEach(() => {
vi.stubGlobal('IntersectionObserver', FakeIntersectionObserver);
Element.prototype.scrollTo = () => {};
});
afterEach(() => {
crash.enabled = false;
socials.override = null;
vi.unstubAllGlobals();
FakeIntersectionObserver.reset();
// @ts-expect-error -- jsdom has no Element.scrollTo of its own
delete Element.prototype.scrollTo;
});
describe('app', () => {
it.each(Object.keys(sitePages))(
'%s rendert binnen de shell met een h1 en zonder axe-fouten',
async (path) => {
const { container } = await renderApp(path);
expectShell();
expect(
await screen.findAllByRole('heading', { level: 1 }),
).toHaveLength(1);
expect(await axeResults(container)).toHaveNoViolations();
},
);
it('zet titel en noindex van een placeholder in de head', async () => {
await renderApp('/privacyverklaring');
await screen.findByRole('heading', {
level: 1,
name: 'Privacyverklaring',
});
expect(document.title).toBe(
'Privacyverklaring | Andrea Slop Fotografie',
);
expect(
document.head.querySelector('link[rel="canonical"]'),
).toHaveAttribute('href', 'https://andreaslop.nl/privacyverklaring');
expect(
document.head.querySelector('meta[name="robots"]'),
).toHaveAttribute('content', 'noindex');
});
// Een data-script blijft staan waar HeadContent rendert (in de body);
// React verplaatst alleen title, meta en link. Google leest JSON-LD overal.
it('zet precies een blok gestructureerde data in de pagina', async () => {
await renderApp('/');
const scripts = document.querySelectorAll(
'script[type="application/ld+json"]',
);
expect(scripts).toHaveLength(1);
expect(JSON.parse(scripts[0].textContent!)['@type']).toBe(
'ProfessionalService',
);
});
it('shows the about page with its outline, links and structured data', async () => {
const { container } = await renderApp('/over-mij');
await screen.findByRole('heading', { level: 1, name: 'Over mij' });
// The page's own outline; the footer adds its own column headings
expect(
within(screen.getByRole('main'))
.getAllByRole('heading')
.map((h) => `${h.tagName} ${h.textContent}`),
).toEqual([
'H1 Over mij',
'H2 Hoi! Ik ben Andrea',
'H3 Hoe het begon',
'H3 Buiten de camera om',
]);
expect(
screen.getByRole('link', { name: 'mijn portfolio' }),
).toHaveAttribute('href', '/portfolio');
expect(
screen.getByRole('link', { name: 'neem contact op' }),
).toHaveAttribute('href', '/contact');
expect(
screen.getByRole('link', { name: 'Boek je shoot' }),
).toHaveAttribute('href', '/contact');
expect(
screen.getByRole('list', { name: "Foto's" }),
).toBeInTheDocument();
expect(document.title).toBe(
'Over mij – fotograaf in Huizen | Andrea Slop Fotografie',
);
expect(document.head.querySelector('meta[name="robots"]')).toBeNull();
const types = [
...document.querySelectorAll('script[type="application/ld+json"]'),
].map((script) => JSON.parse(script.textContent!)['@type']);
expect(types.sort()).toEqual(['AboutPage', 'ProfessionalService']);
expect(await axeResults(container)).toHaveNoViolations();
});
it('shows the contact page with its outline, cards and structured data', async () => {
const { container } = await renderApp('/contact');
await screen.findByRole('heading', { level: 1, name: 'Contact' });
const main = within(screen.getByRole('main'));
// Both cards are in the page; jsdom has no screen width, so the
// headings are listed regardless of which layout is visible
expect(
main
.getAllByRole('heading', { hidden: true })
.map((h) => `${h.tagName} ${h.textContent}`),
).toEqual([
'H1 Contact',
'H2 Direct contact',
'H2 Stuur me een bericht',
'H2 Direct contact',
]);
expect(
screen.getByText(/ik reageer binnen 1-2 werkdagen\./),
).toBeInTheDocument();
expect(
screen.getByRole('region', { name: 'Stuur me een bericht' }),
).toBeInTheDocument();
expect(
screen.getByTestId('contact-details-narrow'),
).toBeInTheDocument();
expect(screen.getByTestId('contact-details-wide')).toBeInTheDocument();
expect(
await screen.findByTestId('contact-form-shoot', undefined, {
timeout: 10_000,
}),
).toBeInTheDocument();
expect(document.title).toBe(
'Contact – fotoshoot boeken in Huizen | Andrea Slop Fotografie',
);
expect(document.head.querySelector('meta[name="robots"]')).toBeNull();
const types = [
...document.querySelectorAll('script[type="application/ld+json"]'),
].map((script) => JSON.parse(script.textContent!)['@type']);
expect(types.sort()).toEqual(['ContactPage', 'ProfessionalService']);
expect(await axeResults(container)).toHaveNoViolations();
});
it('takes over ?pakket= on the contact page and tidies the URL without moving focus', async () => {
const { router } = await renderApp('/contact?pakket=newborn');
expect(
await screen.findByTestId('contact-form-shoot', undefined, {
timeout: 10_000,
}),
).toHaveValue('Newborn');
await waitFor(() => expect(router.state.location.searchStr).toBe(''));
expect(router.state.location.pathname).toBe('/contact');
expect(document.activeElement).toBe(document.body);
});
it('drops an unknown ?pakket= on the contact page', async () => {
const { router } = await renderApp('/contact?pakket=bruiloft');
expect(
await screen.findByTestId('contact-form-shoot', undefined, {
timeout: 10_000,
}),
).toHaveValue('');
await waitFor(() => expect(router.state.location.searchStr).toBe(''));
});
it('shows the shoot types page with its outline, links and structured data', async () => {
const { container } = await renderApp('/soorten-fotoshoots');
await screen.findByRole('heading', {
level: 1,
name: 'Soorten fotoshoots',
});
const main = screen.getByRole('main');
expect(
within(main)
.getAllByRole('heading')
.map((h) => `${h.tagName} ${h.textContent}`),
).toEqual([
'H1 Soorten fotoshoots',
'H2 Newborn',
'H2 Zwangerschap',
'H2 Gezin',
'H2 Loveshoot',
'H2 Portretten',
'H2 Benieuwd naar de prijzen?',
]);
expect(
within(main)
.getAllByRole('article')
.map((article) => article.id),
).toEqual(['newborn', 'zwangerschap', 'gezin', 'loveshoot', 'portret']);
expect(
within(main)
.getAllByRole('link', { name: /^Stuur een berichtje/ })
.map((link) => link.getAttribute('href')),
).toEqual([
'/contact?pakket=newborn',
'/contact?pakket=zwangerschap',
'/contact?pakket=gezin',
'/contact',
'/contact',
]);
// Links to the filtered portfolio only once that page is live
// (indexed), and only for shoot types with portfolio photos
expect(
within(main)
.queryAllByRole('link', { name: /^Bekijk meer/ })
.map((link) => link.getAttribute('href')),
).toEqual(
sitePages['/portfolio'].indexed
? [
'/portfolio?shoot=newborn',
'/portfolio?shoot=zwangerschap',
'/portfolio?shoot=gezin',
]
: [],
);
expect(
screen.getByRole('link', { name: 'de pakketten' }),
).toHaveAttribute('href', '/#prijzen');
expect(
screen.getByRole('link', { name: 'Boek je shoot' }),
).toHaveAttribute('href', '/contact');
expect(document.title).toBe(
'Soorten fotoshoots | Andrea Slop Fotografie',
);
expect(document.head.querySelector('meta[name="robots"]')).toBeNull();
const data = [
...document.querySelectorAll('script[type="application/ld+json"]'),
].map((script) => JSON.parse(script.textContent!));
expect(data.map((item) => item['@type']).sort()).toEqual([
'ProfessionalService',
'WebPage',
]);
const page = data.find((item) => item['@type'] === 'WebPage');
expect(page.mainEntity.itemListElement).toHaveLength(5);
expect(await axeResults(container)).toHaveNoViolations();
});
it('shows the portfolio with its outline, filters, photos and structured data', async () => {
const { container } = await renderApp('/portfolio');
await screen.findByRole('heading', { level: 1, name: 'Portfolio' });
expectShell();
const main = screen.getByRole('main');
expect(
within(main)
.getAllByRole('heading', { level: 2 })
.map((heading) => heading.textContent),
).toEqual(["Foto's", 'Instagram']);
expect(
within(main).getByRole('button', { name: 'Alles', pressed: true }),
).toBeInTheDocument();
expect(
within(screen.getByTestId('portfolio-grid')).getAllByRole('link'),
).toHaveLength(10);
expect(document.title).toBe('Portfolio | Andrea Slop Fotografie');
expect(document.head.querySelector('meta[name="robots"]')).toBeNull();
expect(
document.head.querySelector('link[rel="canonical"]'),
).toHaveAttribute('href', 'https://andreaslop.nl/portfolio');
expect(
document.head.querySelector('meta[property="og:image"]'),
).toHaveAttribute('content', 'https://andreaslop.nl/og-portfolio.jpg');
const data = [
...document.querySelectorAll('script[type="application/ld+json"]'),
].map((script) => JSON.parse(script.textContent!));
const gallery = data.find((item) => item['@type'] === 'ImageGallery');
expect(gallery.associatedMedia).toHaveLength(10);
expect(await axeResults(container)).toHaveNoViolations();
});
it('starts the portfolio filtered on ?shoot= and keeps the canonical URL plain', async () => {
await renderApp('/portfolio?shoot=gezin');
await screen.findByRole('heading', { level: 1, name: 'Portfolio' });
expect(
screen.getByRole('button', { name: 'Gezin', pressed: true }),
).toBeInTheDocument();
expect(
within(screen.getByTestId('portfolio-grid')).getAllByRole('link'),
).toHaveLength(2);
expect(
document.head.querySelector('link[rel="canonical"]'),
).toHaveAttribute('href', 'https://andreaslop.nl/portfolio');
});
it.each(['onzin', 'loveshoot', '%3Cscript%3E'])(
'shows the whole portfolio for ?shoot=%s',
async (value) => {
await renderApp(`/portfolio?shoot=${value}`);
await screen.findByRole('heading', { level: 1, name: 'Portfolio' });
expect(
screen.getByRole('button', { name: 'Alles', pressed: true }),
).toBeInTheDocument();
expect(
within(screen.getByTestId('portfolio-grid')).getAllByRole(
'link',
),
).toHaveLength(10);
},
);
it('puts the chosen filter in the URL without a history entry', async () => {
const { router } = await renderApp('/portfolio');
await screen.findByRole('heading', { level: 1, name: 'Portfolio' });
const user = userEvent.setup();
await user.click(screen.getByRole('button', { name: 'Newborn' }));
await waitFor(() =>
expect(router.state.location.search).toEqual({ shoot: 'newborn' }),
);
expect(router.history.length).toBe(1);
await user.click(screen.getByRole('button', { name: 'Alles' }));
await waitFor(() => expect(router.state.location.search).toEqual({}));
});
it('toont een onbekende URL als 404 binnen de shell', async () => {
const { container } = await renderApp('/bestaat-niet');
expect(
await screen.findByRole('heading', {
level: 1,
name: 'Pagina niet gevonden',
}),
).toBeInTheDocument();
expectShell();
expect(await axeResults(container)).toHaveNoViolations();
});
it('toont een fout in een pagina als foutpagina binnen de shell', async () => {
crash.enabled = true;
vi.spyOn(console, 'error').mockImplementation(() => {});
// De router meldt de bewust gegooide fout ook als waarschuwing
vi.spyOn(console, 'warn').mockImplementation(() => {});
await renderApp('/portfolio');
expect(
await screen.findByRole('heading', {
level: 1,
name: 'Er ging iets mis',
}),
).toBeInTheDocument();
expectShell();
expect(document.body).not.toHaveTextContent('kapot');
});
});
describe('homepage', () => {
it('shows the sections below the hero in page order', async () => {
const { container } = await renderApp('/');
const hero = await screen.findByRole('region', {
name: 'Uitgelicht werk',
});
const sections = [
screen.getByRole('region', { name: 'Lifestyle fotografie' }),
screen.getByRole('region', {
name: 'Lifestyle fotograaf met een passie voor storytelling',
}),
screen.getByRole('region', { name: 'Prijzen' }),
screen.getByRole('region', { name: 'Lieve woorden' }),
screen.getByRole('region', { name: 'Contact' }),
screen.getByRole('region', { name: 'Instagram' }),
];
let previous: Element = hero;
for (const section of sections) {
expect(
previous.compareDocumentPosition(section) &
Node.DOCUMENT_POSITION_FOLLOWING,
).toBeTruthy();
previous = section;
}
expect(screen.getAllByRole('heading', { level: 1 })).toHaveLength(1);
expect(await axeResults(container)).toHaveNoViolations();
});
it.each([
['missing', []],
[
'not https',
[
{
platform: 'instagram',
href: 'http://www.instagram.com/andreaslopfotografie/',
},
],
],
] satisfies [string, SocialLink[]][])(
'leaves out the Instagram section when its link is %s',
async (_, links) => {
socials.override = links;
await renderApp('/');
await screen.findByRole('region', { name: 'Contact' });
expect(
screen.queryByRole('region', { name: 'Instagram' }),
).toBeNull();
},
);
});
describe('homepage ?pakket=', () => {
it('a click on "Boek Newborn" scrolls to Contact and selects Newborn', async () => {
const scrolls = vi.spyOn(Element.prototype, 'scrollIntoView');
const user = userEvent.setup();
await renderApp('/');
await user.click(
await screen.findByRole('link', { name: 'Boek Newborn' }),
);
expect(
await screen.findByTestId('contact-form-shoot', undefined, {
timeout: 10_000,
}),
).toHaveValue('Newborn');
await waitFor(() =>
expect(
scrolls.mock.contexts.some(
(element) => (element as Element).id === 'contact',
),
).toBe(true),
);
});
it('a "Boek Newborn" link selects Newborn, tidies the URL and focuses Contact', async () => {
const { router } = await renderApp('/?pakket=newborn#contact');
// The form is lazy; arriving via "Boek" loads it straight away
expect(
await screen.findByTestId('contact-form-shoot', undefined, {
timeout: 10_000,
}),
).toHaveValue('Newborn');
await waitFor(() => expect(router.state.location.searchStr).toBe(''));
expect(router.state.location.hash).toBe('contact');
// The form stays once loaded, also now that ?pakket= is gone
expect(screen.getByTestId('contact-form-shoot')).toHaveValue('Newborn');
// within the section: the footer has a "Contact" heading too
expect(
within(screen.getByRole('region', { name: 'Contact' })).getByRole(
'heading',
{ level: 2 },
),
).toHaveFocus();
});
it.each(['/?pakket=newborn', '/?pakket=123', '/?pakket=%3Cscript%3E'])(
'%s renders the homepage without errors',
async (path) => {
await renderApp(path);
expect(
await screen.findByRole('region', { name: 'Prijzen' }),
).toBeInTheDocument();
expect(document.body).not.toHaveTextContent('<script>');
},
);
});
// The JSON-LD objects in the page, in document order
const structuredData = () =>
[...document.querySelectorAll('script[type="application/ld+json"]')].map(
(script) => JSON.parse(script.textContent!),
);
const shootIds = shootTypes.map((shoot) => shoot.id);
describe('shoot pages', () => {
it.each(shootIds)('%s has its own head and structured data', async (id) => {
const path = shootPagePath(id);
await renderApp(path);
await screen.findByRole('heading', { level: 1 });
expect(document.title).toBe(
`${sitePages[path].title} | Andrea Slop Fotografie`,
);
expect(
document.head.querySelector('meta[name="description"]'),
).toHaveAttribute('content', sitePages[path].description);
expect(
document.head.querySelector('link[rel="canonical"]'),
).toHaveAttribute('href', `${siteUrl}${path}`);
// Each shoot page has its own preview image from the registry
expect(
document.head.querySelector('meta[property="og:image"]'),
).toHaveAttribute(
'content',
`${siteUrl}${sitePages[path].ogImage!.path}`,
);
expect(document.head.querySelector('meta[name="robots"]')).toBeNull();
const data = structuredData();
expect(data.map((item) => item['@type']).sort()).toEqual([
'FAQPage',
'ProfessionalService',
'WebPage',
]);
const page = data.find((item) => item['@type'] === 'WebPage');
expect(page.mainEntity['@id']).toBe(`${siteUrl}${path}#service`);
expect('offers' in page.mainEntity).toBe(
['newborn', 'zwangerschap', 'gezin'].includes(id),
);
});
it('gives the overview the Service ids of the shoot pages and renders no shoot page', async () => {
await renderApp('/soorten-fotoshoots');
await screen.findByRole('heading', {
level: 1,
name: 'Soorten fotoshoots',
});
const page = structuredData().find(
(item) => item['@type'] === 'WebPage',
);
expect(
page.mainEntity.itemListElement.map(
(entry: { item: { '@id': string } }) => entry.item['@id'],
),
).toEqual(
shootIds.map((id) => `${siteUrl}${shootPagePath(id)}#service`),
);
// No layout route: nothing of a shoot page on the overview
expect(
document.querySelector('script[type="application/ld+json"]'),
).not.toBeNull();
expect(
structuredData().some((item) => item['@type'] === 'FAQPage'),
).toBe(false);
});
it.each(['/soorten-fotoshoots/onzin', '/soorten-fotoshoots/newborn/extra'])(
'shows the 404 within the shell for %s',
async (path) => {
await renderApp(path);
expect(
await screen.findByRole('heading', {
level: 1,
name: 'Pagina niet gevonden',
}),
).toBeInTheDocument();
expectShell();
},
);
// The router matches paths case-insensitively (default), so this is not
// a 404; the canonical URL stays the lowercase one
it('serves /soorten-fotoshoots/Newborn as the newborn page with the lowercase canonical', async () => {
await renderApp('/soorten-fotoshoots/Newborn');
await screen.findByRole('heading', { level: 1 });
expect(
document.head.querySelector('link[rel="canonical"]'),
).toHaveAttribute('href', `${siteUrl}/soorten-fotoshoots/newborn`);
});
});
describe('pagina-register', () => {
// Finite sets, so example-based: every shoot page is registered
// everywhere, and nothing else lives under /soorten-fotoshoots/
it('has every shoot page in the router, registry, sitemap and Lighthouse list', async () => {
const { router } = await renderApp('/');
const sitemap = sitemapXml(
Object.entries(sitePages).map(([path, page]) => ({
path,
indexed: page.indexed,
})) as Parameters<typeof sitemapXml>[0],
siteUrl,
);
const prefix = '/soorten-fotoshoots/';
const expected = shootIds.map(shootPagePath).sort();
const underPrefix = (paths: string[]) =>
paths.filter((path) => path.startsWith(prefix)).sort();
for (const path of expected) {
expect(router.routesByPath).toHaveProperty([path]);
expect(sitePages[path as keyof typeof sitePages].indexed).toBe(
true,
);
expect(sitemap).toContain(`<loc>${siteUrl}${path}</loc>`);
expect(lighthouseConfig.indexedPaths).toContain(path);
}
expect(underPrefix(Object.keys(router.routesByPath))).toEqual(expected);
expect(underPrefix(Object.keys(sitePages))).toEqual(expected);
expect(underPrefix(lighthouseConfig.indexedPaths)).toEqual(expected);
const sitemapPaths = [...sitemap.matchAll(/<loc>([^<]*)<\/loc>/g)].map(
(match) => match[1].replace(siteUrl, ''),
);
expect(underPrefix(sitemapPaths)).toEqual(expected);
});
it('bevat precies de routes van de route tree', async () => {
const { router } = await renderApp('/');
// De vangroute (404) is geen pagina en staat niet in het register
const routePaths = Object.keys(router.routesByPath)
.filter((path) => path !== '/$')
.sort();
expect(Object.keys(sitePages).sort()).toEqual(routePaths);
});
it('loopt gelijk met de URLs van Lighthouse CI', () => {
const indexed = Object.entries(sitePages)
.filter(([, page]) => page.indexed)
.map(([path]) => path);
const noindex = Object.entries(sitePages)
.filter(([, page]) => !page.indexed)
.map(([path]) => path);
expect(lighthouseConfig.indexedPaths).toEqual(indexed);
expect(lighthouseConfig.noindexPaths).toEqual(noindex);
// Lighthouse weigert een foutstatus; de preview-server geeft de 404-pagina
// alleen via de opt-in route met status 200. /404.html is een echte 404
expect(lighthouseConfig.notFoundPath).toBe('/__audit/404');
});
});