import { ChakraProvider } from '@chakra-ui/react'; import { createMemoryHistory, createRouter, RouterProvider, } from '@tanstack/react-router'; import { render, 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 ErrorPage from './components/StatusPage/ErrorPage'; import { FakeIntersectionObserver } from './test/fakeIntersectionObserver'; import { routeTree } from './routeTree.gen'; import sitePages from './sitePages'; import { axeResults } from './test/axe'; import type { SocialLink } from './content/types'; import system from './theme'; // 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[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() ).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; }); // De echte app: route tree, router-opties en thema zoals in main.tsx async function renderApp(path: string) { const router = createRouter({ routeTree, history: createMemoryHistory({ initialEntries: [path] }), scrollRestoration: true, defaultErrorComponent: ErrorPage, }); await router.load(); const result = render( , ); return { ...result, router }; } const expectShell = () => { expect(screen.getByRole('banner')).toBeInTheDocument(); expect(screen.getByRole('contentinfo')).toBeInTheDocument(); }; 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('/portfolio'); await screen.findByRole('heading', { level: 1, name: 'Portfolio' }); expect(document.title).toBe('Portfolio | Andrea Slop Fotografie'); expect( document.head.querySelector('link[rel="canonical"]'), ).toHaveAttribute('href', 'https://andreaslop.nl/portfolio'); 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 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([ '/?pakket=newborn#contact', '/?pakket=zwangerschap#contact', '/?pakket=gezin#contact', '/#contact', '/#contact', ]); // Links to the filtered portfolio only once that page is live // (indexed); they switch on by themselves when it is 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', '/portfolio?shoot=loveshoot', '/portfolio?shoot=portret', ] : [], ); 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('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('