import { StrictMode } from 'react'; import { act, screen, waitFor, within } from '@testing-library/react'; import userEvent from '@testing-library/user-event'; import { ChakraProvider } from '@chakra-ui/react'; import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'; import portfolioContent from '@/content/portfolioContent'; import Reveal from '@/components/Reveal/Reveal'; import { FakeIntersectionObserver as FakeObserver } from '@/test/fakeIntersectionObserver'; import { hydrate, hydrateAppAsStart } from '@/test/hydrate'; import system from './theme'; afterEach(() => { vi.restoreAllMocks(); vi.unstubAllGlobals(); FakeObserver.reset(); }); // jsdom has no layout: place the elements by their test id function stubTops(tops: Record) { vi.spyOn(Element.prototype, 'getBoundingClientRect').mockImplementation( function (this: Element) { const top = tops[this.getAttribute('data-testid') ?? ''] ?? 0; return { top } as DOMRect; }, ); } describe('Reveal while hydrating (BR-RVL-01, 02)', () => { const page = ( in view below the fold ); it('keeps an element in view visible and hides one below the fold only after hydration', () => { vi.stubGlobal('IntersectionObserver', FakeObserver); stubTops({ 'in-view': innerHeight - 1, 'below-fold': innerHeight }); const { container, errors } = hydrate(page); const inView = container.querySelector('[data-testid="in-view"]')!; const belowFold = container.querySelector( '[data-testid="below-fold"]', )!; expect(errors).toEqual([]); expect(inView).toHaveAttribute('data-reveal', 'visible'); expect(belowFold).toHaveAttribute('data-reveal', 'hidden'); act(() => FakeObserver.instances.at(-1)!.trigger(true)); expect(belowFold).toHaveAttribute('data-reveal', 'visible'); expect(inView).toHaveAttribute('data-reveal', 'visible'); }); }); // The pages the way Start hands them over: Router's own hydrate() runs first // (BR-HYD-01). IntersectionObserver is a fake, so Reveal can hide what is // below the fold. describe('pages hydrate with the display fallbacks in place', () => { beforeEach(() => { vi.stubGlobal('IntersectionObserver', FakeObserver); Element.prototype.scrollTo = () => {}; }); afterEach(() => { // @ts-expect-error -- jsdom has no Element.scrollTo of its own delete Element.prototype.scrollTo; }); it.each([ '/', '/over-mij', '/portfolio', '/contact', '/soorten-fotoshoots/loveshoot', ])('hydrates %s without a recoverable error', async (path) => { const { errors } = await hydrateAppAsStart(path, path); expect( await screen.findByRole('heading', { level: 1 }), ).toBeInTheDocument(); if (path === '/contact') { await screen.findByTestId('contact-form', undefined, { timeout: 10_000, }); } expect(errors).toEqual([]); }); it('hydrates the first-row picture tiles of /portfolio, which keep their source', async () => { const { container, errors } = await hydrateAppAsStart( '/portfolio', '/portfolio', ); expect( await screen.findByRole('button', { name: 'Alles', pressed: true }), ).toBeInTheDocument(); const media = (number: number) => container .querySelector( `[data-testid="portfolio-tile-${number}"] picture > source`, ) ?.getAttribute('media'); expect(media(1)).toBeUndefined(); expect(media(2)).toBe('(min-width: 48em)'); expect(media(3)).toBe('(min-width: 64em)'); expect( container.querySelector('[data-testid="portfolio-tile-4"] picture'), ).toBeNull(); expect(errors).toEqual([]); }); it('applies ?shoot=gezin after hydrating, with a first row of its own', async () => { const { container, errors } = await hydrateAppAsStart( '/portfolio', '/portfolio?shoot=gezin', ); await waitFor(() => expect( within(screen.getByTestId('portfolio-grid')).getAllByRole( 'link', ), ).toHaveLength(2), ); const first = container.querySelector( '[data-testid="portfolio-tile-1"] img', )!; expect(first.closest('picture')).toBeNull(); expect(first).toHaveAttribute('fetchpriority', 'high'); expect(first).not.toHaveAttribute('data-deferred'); expect( container .querySelector( '[data-testid="portfolio-tile-2"] picture > source', ) ?.getAttribute('media'), ).toBe('(min-width: 48em)'); expect(errors).toEqual([]); }); it('remounts the photos of the filtered list as its first row', async () => { const { container, errors } = await hydrateAppAsStart( '/portfolio', '/portfolio', ); const user = userEvent.setup(); await screen.findByRole('button', { name: 'Alles', pressed: true }); const gezinHref = portfolioContent.photos.find( (photo) => photo.shootType === 'gezin', )!.full.src; const imageOf = (href: string) => container.querySelector(`a[href="${href}"] img`)!; const before = imageOf(gezinHref); expect(before).toHaveAttribute('data-deferred'); await user.click(screen.getByRole('button', { name: 'Gezin' })); await waitFor(() => expect( within(screen.getByTestId('portfolio-grid')).getAllByRole( 'link', ), ).toHaveLength(2), ); const after = imageOf(gezinHref); expect(after).not.toBe(before); expect(after).toHaveAttribute('src'); expect(errors).toEqual([]); }); it('keeps the Reveals that are in view visible through hydration', async () => { vi.spyOn(Element.prototype, 'getBoundingClientRect').mockImplementation( function (this: Element) { if (!this.hasAttribute('data-reveal')) { return { top: 0 } as DOMRect; } const [inView] = document.querySelectorAll('[data-reveal]'); return { top: this === inView ? 0 : innerHeight + 100, } as DOMRect; }, ); const changes = new MutationObserver(() => {}); changes.observe(document.body, { subtree: true, attributes: true, attributeFilter: ['data-reveal'], attributeOldValue: true, }); const { container, errors } = await hydrateAppAsStart( '/over-mij', '/over-mij', ); await screen.findByRole('heading', { level: 1 }); const reveals = [...container.querySelectorAll('[data-reveal]')]; const [inView, ...below] = reveals; expect(below.length).toBeGreaterThan(0); expect(inView).toHaveAttribute('data-reveal', 'visible'); expect( changes.takeRecords().filter((record) => record.target === inView), ).toEqual([]); for (const reveal of below) { expect(reveal).toHaveAttribute('data-reveal', 'hidden'); } changes.disconnect(); expect(errors).toEqual([]); }); });