import { act, fireEvent, screen, within } from '@testing-library/react'; import type { UseCarouselProps } from '@chakra-ui/react'; import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'; import homeContent from '@/content/homeContent'; import testimonials from '@/content/testimonials'; import { axeResults } from '@/test/axe'; import { FakeIntersectionObserver } from '@/test/fakeIntersectionObserver'; import { serverHtml } from '@/test/hydrate'; import { renderWithProviders } from '@/test/renderWithProviders'; import { visibleTestimonials } from '@/lib/visibleTestimonials'; import Testimonials from './Testimonials'; // jsdom has no layout, so the carousel (Zag) cannot compute pages and // cannot really move; paging, looping and swiping are Zag's own and are // checked in a real browser (see the unit's code summary). These tests check // our wiring: which API calls our controls make, and what is announced. const carousel = vi.hoisted(() => ({ props: undefined as UseCarouselProps | undefined, calls: [] as Array<[string, ...unknown[]]>, // Zag can not move in jsdom: a test sets the page the counter should show page: undefined as number | undefined, })); vi.mock('@chakra-ui/react', async (importOriginal) => { const chakra = await importOriginal(); return { ...chakra, useCarousel: (props: UseCarouselProps) => { const api = chakra.useCarousel(props); carousel.props = props; const record = (name: string, real: (...args: never[]) => void) => (...args: unknown[]) => { carousel.calls.push([name, ...args]); (real as (...args: unknown[]) => void)(...args); }; return { ...api, page: carousel.page ?? api.page, scrollNext: record('scrollNext', api.scrollNext), scrollPrev: record('scrollPrev', api.scrollPrev), scrollTo: record('scrollTo', api.scrollTo), }; }, }; }); beforeEach(() => { carousel.calls = []; carousel.page = undefined; vi.stubGlobal('IntersectionObserver', FakeIntersectionObserver); Element.prototype.scrollTo = () => {}; }); afterEach(() => { vi.unstubAllGlobals(); FakeIntersectionObserver.reset(); // @ts-expect-error -- jsdom has no Element.scrollTo of its own delete Element.prototype.scrollTo; }); const content = homeContent.testimonials; // The carousel is a lazy chunk. The first test that loads it pays for // transforming and instrumenting it, which under the full suite with // coverage can take well over the default 1s of findBy* const LAZY_LOAD = { timeout: 10_000 }; // Renders the section and brings it into view, so the lazily loaded // carousel appears async function renderTestimonials(items = testimonials) { const result = await renderWithProviders( , ); act(() => { FakeIntersectionObserver.instances.forEach((observer) => observer.trigger(true), ); }); if (visibleTestimonials(items).length > 1) { await screen.findByRole('region', { name: 'Reviews' }, LAZY_LOAD); } return result; } const status = () => screen.getByTestId('testimonials-status'); const counter = () => screen.getByTestId('testimonials-counter'); const button = (name: string) => screen.getByRole('button', { name }); const preferReducedMotion = () => vi.spyOn(window, 'matchMedia').mockImplementation( (query: string) => ({ matches: query.includes('reduce'), media: query, onchange: null, addEventListener: () => {}, removeEventListener: () => {}, addListener: () => {}, removeListener: () => {}, dispatchEvent: () => false, }) as MediaQueryList, ); describe('Testimonials', () => { it('shows the heading at once but loads the carousel only near the screen', async () => { await renderWithProviders( , ); expect( screen.getByRole('region', { name: 'Lieve woorden' }), ).toBeInTheDocument(); expect(screen.queryByRole('region', { name: 'Reviews' })).toBeNull(); act(() => { FakeIntersectionObserver.instances.forEach((observer) => observer.trigger(true), ); }); expect( await screen.findByRole('region', { name: 'Reviews' }, LAZY_LOAD), ).toBeInTheDocument(); }); it('shows a looping carousel of the reviews with Dutch labels', async () => { const { container } = await renderTestimonials(); const section = screen.getByRole('region', { name: 'Lieve woorden' }); const region = within(section).getByRole('region', { name: 'Reviews', }); expect(region).toHaveAttribute('aria-roledescription', 'carrousel'); expect(carousel.props).toMatchObject({ slideCount: 2, loop: true, allowMouseDrag: true, }); expect(button('Vorige review')).toBeInTheDocument(); expect(button('Volgende review')).toBeInTheDocument(); const slides = container.querySelectorAll( '[aria-roledescription="slide"]', ); expect(slides[0]).toHaveAttribute('aria-label', 'Review 1 van 2'); expect(slides[1]).toHaveAttribute('aria-label', 'Review 2 van 2'); expect(await axeResults(container)).toHaveNoViolations(); }); it('announces nothing on load and only through its own live region', async () => { const { container } = await renderTestimonials(); expect(status()).toHaveTextContent(''); const live = [...container.querySelectorAll('[aria-live]')].filter( (element) => element.getAttribute('aria-live') !== 'off', ); expect(live).toEqual([status()]); }); it('announces a page change as "Review n van m"', async () => { await renderTestimonials(); act(() => { carousel.props?.onPageChange?.({ page: 1, pageSnapPoint: 0 }); }); expect(status()).toHaveTextContent('Review 2 van 2'); }); it('moves with the arrows and the arrow keys', async () => { await renderTestimonials(); fireEvent.click(button('Volgende review')); fireEvent.click(button('Vorige review')); fireEvent.keyDown(button('Vorige review'), { key: 'ArrowRight' }); fireEvent.keyDown(button('Volgende review'), { key: 'ArrowLeft' }); fireEvent.keyDown(button('Volgende review'), { key: 'Enter' }); expect(carousel.calls).toEqual([ ['scrollNext', false], ['scrollPrev', false], ['scrollNext', false], ['scrollPrev', false], ]); }); it('has no dots: only the two arrows and the counter', async () => { await renderTestimonials(); expect(screen.getAllByRole('button').map((b) => b.ariaLabel)).toEqual([ 'Vorige review', 'Volgende review', ]); expect(screen.queryByTestId('testimonials-dot-1')).toBeNull(); }); it('shows the counter as "X / Y" and keeps it away from assistive technology', async () => { await renderTestimonials(); expect(counter()).toHaveTextContent('1 / 2'); expect(counter()).toHaveAttribute('aria-hidden', 'true'); carousel.page = 1; act(() => { carousel.props?.onPageChange?.({ page: 1, pageSnapPoint: 0 }); }); expect(counter()).toHaveTextContent('2 / 2'); // The announcement says the same thing aloud expect(status()).toHaveTextContent('Review 2 van 2'); }); it('does not move by itself', async () => { await renderTestimonials(); expect(carousel.props).not.toHaveProperty('autoplay'); await new Promise((resolve) => setTimeout(resolve, 100)); expect(carousel.calls).toEqual([]); expect(status()).toHaveTextContent(''); expect( screen.queryByRole('button', { name: /paus|afspel/i }), ).toBeNull(); }); it('scrolls instantly for visitors who prefer reduced motion', async () => { preferReducedMotion(); await renderTestimonials(); fireEvent.click(button('Volgende review')); fireEvent.keyDown(button('Vorige review'), { key: 'ArrowLeft' }); expect(carousel.calls).toEqual([ ['scrollNext', true], ['scrollPrev', true], ]); }); it('shows a single review without carousel controls or counter', async () => { await renderTestimonials([testimonials[0]]); expect( screen.getByTestId(`testimonial-${testimonials[0].id}`), ).toBeInTheDocument(); expect(screen.queryByRole('button')).toBeNull(); expect(screen.queryByTestId('testimonials-counter')).toBeNull(); }); it('leaves the section out when no review is valid', async () => { await renderTestimonials([{ ...testimonials[0], quote: '' }]); expect( screen.queryByRole('region', { name: 'Lieve woorden' }), ).toBeNull(); }); }); // Every review is in the prerendered HTML for search engines; the copies // besides the longest one are hidden and inert (BR-LZY-02) describe('Testimonials in the prerendered HTML', () => { const shown = visibleTestimonials(testimonials); const page = ; it('holds the text of every visible review', async () => { const doc = new DOMParser().parseFromString( await serverHtml(page), 'text/html', ); expect(shown.length).toBeGreaterThan(1); for (const testimonial of shown) { expect( doc.querySelector( `[data-testid="testimonial-${testimonial.id}"]`, )?.textContent, ).toContain(testimonial.quote); } }); it('puts the longest in the flow and hides the others from readers', async () => { const doc = new DOMParser().parseFromString( await serverHtml(page), 'text/html', ); const longest = shown.reduce((a, b) => b.quote.length > a.quote.length ? b : a, ); for (const testimonial of shown) { const copy = doc.querySelector( `[data-testid="testimonial-${testimonial.id}"]`, )!; const hidden = copy.closest('[aria-hidden="true"][inert]'); if (testimonial === longest) { expect(hidden).toBeNull(); } else { expect(hidden).not.toBeNull(); } } }); it('exposes one review to readers while the carousel loads, without axe violations', async () => { const { container } = await renderWithProviders(page); const quotes = [...container.querySelectorAll('blockquote')]; expect(quotes).toHaveLength(shown.length); expect( quotes.filter((quote) => !quote.closest('[aria-hidden="true"]')), ).toHaveLength(1); expect(await axeResults(container)).toHaveNoViolations(); }); it('does not add copies for a single review', async () => { const html = await serverHtml( , ); expect(html.match(/data-testid="testimonial-/g)).toHaveLength(1); expect(html).not.toContain('inert'); }); it('marks the controls spacer and keeps the other copies hidden in the prerendered HTML', async () => { const html = await serverHtml( , ); const doc = new DOMParser().parseFromString(html, 'text/html'); const marked = doc.querySelectorAll('[data-requires-js]'); expect(marked).toHaveLength(1); expect(marked[0].textContent).toBe(''); const copies = [...doc.querySelectorAll('[aria-hidden="true"]')].filter( (element) => element.querySelector('blockquote'), ); expect(copies.length).toBeGreaterThan(0); for (const copy of copies) expect(copy.hasAttribute('inert')).toBe(true); }); });