import { useState } from 'react'; import { act, fireEvent, screen, waitFor } from '@testing-library/react'; import { beforeEach, describe, expect, it, vi } from 'vitest'; import type { CaptchaInfo, ContactClient, ContactToken, SubmitResult, } from '@/cms-client/contact'; import packages from '@/content/packages'; import siteContent from '@/content/siteContent'; import { shootOptions } from '@/lib/shootOptions'; import { axeResults } from '@/test/axe'; import { serverHtml } from '@/test/hydrate'; import { renderWithProviders } from '@/test/renderWithProviders'; import ContactForm, { type FormAvailability } from './ContactForm'; // A stand-in for the Friendly Captcha SDK: widgets the test can solve, // expire and watch const sdk = vi.hoisted(() => { type Listener = (event: { detail: { response: string } }) => void; class FakeWidget { listeners = new Map(); reset = vi.fn(); destroy = vi.fn(); options: Record; constructor(options: Record) { this.options = options; } addEventListener(type: string, listener: Listener) { this.listeners.set(type, listener); } emit(type: string, response = '') { this.listeners.get(type)?.({ detail: { response } }); } } const state = { widgets: [] as FakeWidget[], sdkOptions: [] as unknown[], }; class FriendlyCaptchaSDK { constructor(options: unknown) { state.sdkOptions.push(options); } createWidget(options: Record) { const widget = new FakeWidget(options); state.widgets.push(widget); return widget; } } return { state, FriendlyCaptchaSDK }; }); vi.mock('@friendlycaptcha/sdk', () => ({ FriendlyCaptchaSDK: sdk.FriendlyCaptchaSDK, })); const options = shootOptions(packages); const CAPTCHA: CaptchaInfo = { provider: 'friendlycaptcha', siteKey: 'FCMTEST', apiEndpoint: 'global', }; const tokenWith = (captcha: CaptchaInfo | null): ContactToken => ({ token: 'signed-token', minSeconds: 3, captcha, }); let submit: ReturnType; let refreshToken: ReturnType; let client: ContactClient; beforeEach(() => { sdk.state.widgets.length = 0; sdk.state.sdkOptions.length = 0; submit = vi.fn().mockResolvedValue({ kind: 'ok' } satisfies SubmitResult); refreshToken = vi.fn().mockResolvedValue({ kind: 'failed' }); client = { getToken: vi.fn(), submit: submit as unknown as ContactClient['submit'], }; }); const open = (captcha: CaptchaInfo | null = null): FormAvailability => ({ token: tokenWith(captcha), refreshToken: refreshToken as unknown as FormAvailability['refreshToken'], }); const renderForm = ( props: Partial> = {}, ) => renderWithProviders( , ); const field = (name: string) => screen.getByTestId(`contact-form-${name}`); const type = (name: string, value: string) => fireEvent.change(field(name), { target: { value } }); const fillIn = () => { type('naam', 'Demi'); type('email', 'demi@example.nl'); type('shoot', 'Newborn'); type('bericht', 'Wanneer heb je plek?'); }; const send = () => fireEvent.click(screen.getByTestId('contact-form-submit')); describe('ContactForm', () => { it('shows the four labelled fields and the button', async () => { const { container } = await renderForm(); expect(screen.getByLabelText(/Naam/)).toBe(field('naam')); expect(screen.getByLabelText(/E-mail/)).toBe(field('email')); expect(screen.getByLabelText(/In welke shoot/)).toBe(field('shoot')); expect(screen.getByLabelText(/Stel hier je vraag/)).toBe( field('bericht'), ); expect( screen.getByRole('option', { name: 'Kies een optie...' }), ).toBeInTheDocument(); expect( screen.getByRole('button', { name: '(Aan)vraag versturen' }), ).toBeInTheDocument(); expect(await axeResults(container)).toHaveNoViolations(); }); it('offers the package names and Overig as shoots, the label being the value', async () => { await renderForm(); const values = [...field('shoot').querySelectorAll('option')].map( (option) => option.getAttribute('value'), ); expect(values).toEqual([ '', ...packages.map((pkg) => pkg.name), 'Overig', ]); }); it('stops an incomplete submit and focuses the first invalid field', async () => { await renderForm(); type('naam', 'Demi'); send(); expect(screen.getByText('Vul je e-mailadres in.')).toBeInTheDocument(); expect(screen.getByText('Kies een onderwerp.')).toBeInTheDocument(); expect(screen.getByText('Schrijf hier je vraag.')).toBeInTheDocument(); await waitFor(() => expect(field('email')).toHaveFocus()); expect(field('email')).toHaveAttribute('aria-invalid', 'true'); expect(submit).not.toHaveBeenCalled(); }); it('sends the trimmed form with the token and the label as subject', async () => { await renderForm(); fillIn(); type('naam', ' Demi '); send(); await screen.findByTestId('contact-form-sent'); expect(submit).toHaveBeenCalledTimes(1); const [payload, context] = submit.mock.calls[0]; expect(payload).toEqual({ name: 'Demi', email: 'demi@example.nl', subject: 'Newborn', message: 'Wanneer heb je plek?', hpCheck: '', token: 'signed-token', }); expect(context.idempotencyKey).toMatch(/^[0-9a-f-]{36}$/); }); it('shows the thank-you with focus and takes the reply time from the content', async () => { await renderForm({ replyTime: '3 werkdagen' }); fillIn(); send(); const thanks = await screen.findByTestId('contact-form-sent'); expect(thanks).toHaveTextContent( 'Bedankt voor je bericht! Ik reageer binnen 3 werkdagen.', ); await waitFor(() => expect(thanks).toHaveFocus()); expect(screen.queryByTestId('contact-form')).toBeNull(); }); it('shows the privacy line under the submit button', async () => { await renderForm(); const form = screen.getByTestId('contact-form'); expect(form).toContainElement(screen.getByTestId('privacy-note')); expect( screen.getByRole('link', { name: 'privacyverklaring' }), ).toHaveAttribute('href', '/privacyverklaring'); }); it('keeps the input and names the address when sending fails', async () => { submit.mockResolvedValue({ kind: 'failed' }); await renderForm(); fillIn(); send(); const status = await screen.findByRole('alert'); expect(status).toHaveTextContent( 'Versturen lukte niet. Probeer het later nog eens of mail naar info@andreaslop.nl', ); expect(field('naam')).toHaveValue('Demi'); await waitFor(() => expect( screen.getByTestId('contact-form-submit'), ).not.toBeDisabled(), ); }); it('uses the text of the package for a rate limit (minutes from Retry-After)', async () => { submit.mockResolvedValue({ kind: 'rateLimited', retryAfterSeconds: 120, }); await renderForm(); fillIn(); send(); expect(await screen.findByRole('alert')).toHaveTextContent( 'Je hebt net al een bericht gestuurd. Probeer het over 2 minuten opnieuw.', ); }); it('treats a filled honeypot as spam: thank-you, nothing sent', async () => { const { container } = await renderForm(); fillIn(); fireEvent.change(container.querySelector('input[name="test-hp"]')!, { target: { value: 'https://spam.example' }, }); send(); expect( await screen.findByTestId('contact-form-sent'), ).toBeInTheDocument(); expect(submit).not.toHaveBeenCalled(); }); it('keeps the honeypot away from people and assistive technology', async () => { const { container } = await renderForm(); const honeypot = container.querySelector('input[name="test-hp"]'); expect(honeypot).toHaveAttribute('tabindex', '-1'); expect(honeypot).toHaveAttribute('autocomplete', 'off'); expect(honeypot?.closest('[aria-hidden="true"]')).not.toBeNull(); }); it('applies a choice made before the form existed, and later clicks too', async () => { // A second "Boek" click for the same package raises the key function Harness() { const [preselect, setPreselect] = useState({ subject: 'Newborn', key: 1, }); return ( <> ); } await renderWithProviders(); await waitFor(() => expect(field('shoot')).toHaveValue('Newborn')); type('shoot', 'Gezin'); expect(field('shoot')).toHaveValue('Gezin'); fireEvent.click(screen.getByRole('button', { name: 'nog eens' })); await waitFor(() => expect(field('shoot')).toHaveValue('Newborn')); }); it('sends a label with special characters unchanged', async () => { const special = `Zwanger & "mooi" 's`; await renderForm({ options: [{ value: special, label: special }], }); type('naam', 'Demi'); type('email', 'demi@example.nl'); type('shoot', special); type('bericht', 'Hoi'); send(); await screen.findByTestId('contact-form-sent'); expect(submit.mock.calls[0][0].subject).toBe(special); }); }); describe('ContactForm with a captcha', () => { const lastWidget = () => sdk.state.widgets[sdk.state.widgets.length - 1]; const widget = async () => { await waitFor(() => expect(sdk.state.widgets).toHaveLength(1)); return lastWidget(); }; it('mounts the widget with the key and region from the server', async () => { await renderForm({ availability: open({ ...CAPTCHA, apiEndpoint: 'eu' }), }); const created = await widget(); expect(created.options).toMatchObject({ sitekey: 'FCMTEST', language: 'nl', startMode: 'focus', }); expect(sdk.state.sdkOptions[0]).toEqual({ apiEndpoint: 'eu' }); expect(screen.getByTestId('contact-form-captcha')).toBeInTheDocument(); }); it('sends nothing and says so until the captcha is solved', async () => { await renderForm({ availability: open(CAPTCHA) }); await widget(); fillIn(); send(); expect( await screen.findByText('Bevestig eerst dat je geen robot bent.'), ).toBeInTheDocument(); expect(submit).not.toHaveBeenCalled(); }); it('sends the solved response with the form', async () => { await renderForm({ availability: open(CAPTCHA) }); const created = await widget(); fillIn(); act(() => created.emit('frc:widget.complete', 'solved-response')); send(); await screen.findByTestId('contact-form-sent'); expect(submit.mock.calls[0][0].captchaToken).toBe('solved-response'); }); it('never sends an expired response', async () => { await renderForm({ availability: open(CAPTCHA) }); const created = await widget(); fillIn(); act(() => created.emit('frc:widget.complete', 'old-response')); act(() => created.emit('frc:widget.expire', '.EXPIRED')); send(); expect( await screen.findByText('Bevestig eerst dat je geen robot bent.'), ).toBeInTheDocument(); expect(submit).not.toHaveBeenCalled(); }); it('never sends a response of a failed widget', async () => { await renderForm({ availability: open(CAPTCHA) }); const created = await widget(); fillIn(); act(() => created.emit('frc:widget.complete', 'a-response')); act(() => created.emit('frc:widget.error', '.ERROR')); send(); await screen.findByText('Bevestig eerst dat je geen robot bent.'); expect(submit).not.toHaveBeenCalled(); }); it('resets the widget after a send attempt (a response is single-use)', async () => { submit.mockResolvedValue({ kind: 'failed' }); await renderForm({ availability: open(CAPTCHA) }); const created = await widget(); fillIn(); act(() => created.emit('frc:widget.complete', 'r1')); send(); await screen.findByRole('alert'); await waitFor(() => expect(created.reset).toHaveBeenCalled()); }); it('destroys the widget when the form goes away', async () => { const { unmount } = await renderForm({ availability: open(CAPTCHA) }); const created = await widget(); unmount(); expect(created.destroy).toHaveBeenCalled(); }); it('shows no widget without a captcha', async () => { await renderForm(); expect(screen.queryByTestId('contact-form-captcha')).toBeNull(); expect(sdk.state.widgets).toHaveLength(0); }); }); describe('ContactForm in the prerendered HTML', () => { it('does not hold the address, a token or a widget (BR-MAIL-06)', async () => { const html = await serverHtml( , ); expect(html).toContain('contact-form-submit'); expect(html.toLowerCase()).not.toContain('info@andreaslop.nl'); expect(html).not.toContain('mailto:'); expect(html).not.toContain('signed-token'); expect(html).not.toContain('contact-form-captcha'); }); });