Files
AndreaSlopFotografie/web/src/components/ContactForm/ContactForm.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

408 lines
15 KiB
TypeScript

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<string, Listener>();
reset = vi.fn();
destroy = vi.fn();
options: Record<string, unknown>;
constructor(options: Record<string, unknown>) {
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<string, unknown>) {
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<typeof vi.fn>;
let refreshToken: ReturnType<typeof vi.fn>;
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<React.ComponentProps<typeof ContactForm>> = {},
) =>
renderWithProviders(
<ContactForm
idPrefix="test"
options={options}
email={siteContent.email}
replyTime="1-2 werkdagen"
availability={open()}
client={client}
{...props}
/>,
);
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 (
<>
<button
type="button"
onClick={() =>
setPreselect((p) => ({ ...p, key: p.key + 1 }))
}
>
nog eens
</button>
<ContactForm
idPrefix="test"
options={options}
preselect={preselect}
email={siteContent.email}
replyTime="1-2 werkdagen"
availability={open()}
client={client}
/>
</>
);
}
await renderWithProviders(<Harness />);
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" <b>'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(
<ContactForm
idPrefix="test"
options={options}
email={siteContent.email}
replyTime="1-2 werkdagen"
/>,
);
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');
});
});