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>
This commit is contained in:
@@ -1,21 +1,89 @@
|
||||
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 from './ContactForm';
|
||||
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',
|
||||
};
|
||||
|
||||
// The time check needs over 3 s between showing and sending (BR-SPAM-01)
|
||||
let now = 0;
|
||||
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(() => {
|
||||
now = 0;
|
||||
vi.spyOn(Date, 'now').mockImplementation(() => now);
|
||||
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 = (
|
||||
@@ -25,10 +93,10 @@ const renderForm = (
|
||||
<ContactForm
|
||||
idPrefix="test"
|
||||
options={options}
|
||||
mailSubject="Vraag via andreaslop.nl"
|
||||
email={siteContent.email}
|
||||
replyTime="1-2 werkdagen"
|
||||
submit={vi.fn().mockResolvedValue(undefined)}
|
||||
availability={open()}
|
||||
client={client}
|
||||
{...props}
|
||||
/>,
|
||||
);
|
||||
@@ -39,13 +107,10 @@ const type = (name: string, value: string) =>
|
||||
const fillIn = () => {
|
||||
type('naam', 'Demi');
|
||||
type('email', 'demi@example.nl');
|
||||
type('shoot', 'newborn');
|
||||
type('shoot', 'Newborn');
|
||||
type('bericht', 'Wanneer heb je plek?');
|
||||
};
|
||||
const send = () => {
|
||||
now = 10_000;
|
||||
fireEvent.click(screen.getByTestId('contact-form-submit'));
|
||||
};
|
||||
const send = () => fireEvent.click(screen.getByTestId('contact-form-submit'));
|
||||
|
||||
describe('ContactForm', () => {
|
||||
it('shows the four labelled fields and the button', async () => {
|
||||
@@ -65,67 +130,59 @@ describe('ContactForm', () => {
|
||||
expect(await axeResults(container)).toHaveNoViolations();
|
||||
});
|
||||
|
||||
it('shows nothing when tabbing through an untouched field', async () => {
|
||||
it('offers the package names and Overig as shoots, the label being the value', async () => {
|
||||
await renderForm();
|
||||
fireEvent.blur(field('naam'));
|
||||
expect(screen.queryByText('Vul je naam in.')).toBeNull();
|
||||
});
|
||||
|
||||
it('checks a field on leaving once typed in, and clears it once fine', async () => {
|
||||
await renderForm();
|
||||
type('email', 'demi@');
|
||||
fireEvent.blur(field('email'));
|
||||
expect(
|
||||
screen.getByText('Dit e-mailadres is ongeldig.'),
|
||||
).toBeInTheDocument();
|
||||
expect(field('email')).toHaveAttribute('aria-invalid', 'true');
|
||||
|
||||
type('email', 'demi@example.nl');
|
||||
expect(screen.queryByText('Dit e-mailadres is ongeldig.')).toBeNull();
|
||||
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 () => {
|
||||
const submit = vi.fn();
|
||||
await renderForm({ submit });
|
||||
await renderForm();
|
||||
type('naam', 'Demi');
|
||||
send();
|
||||
expect(screen.getByText('Vul je e-mailadres in.')).toBeInTheDocument();
|
||||
expect(screen.getByText('Kies een soort shoot.')).toBeInTheDocument();
|
||||
expect(screen.getByText('Kies een onderwerp.')).toBeInTheDocument();
|
||||
expect(screen.getByText('Schrijf hier je vraag.')).toBeInTheDocument();
|
||||
expect(field('email')).toHaveFocus();
|
||||
await waitFor(() => expect(field('email')).toHaveFocus());
|
||||
expect(field('email')).toHaveAttribute('aria-invalid', 'true');
|
||||
expect(submit).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('sends the trimmed form and shows the thank-you with focus', async () => {
|
||||
const submit = vi.fn().mockResolvedValue(undefined);
|
||||
await renderForm({ submit });
|
||||
it('sends the trimmed form with the token and the label as subject', async () => {
|
||||
await renderForm();
|
||||
fillIn();
|
||||
type('naam', ' Demi ');
|
||||
send();
|
||||
expect(screen.getByTestId('contact-form-submit')).toHaveTextContent(
|
||||
'Versturen…',
|
||||
);
|
||||
expect(submit).toHaveBeenCalledWith({
|
||||
naam: 'Demi',
|
||||
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',
|
||||
shoot: 'newborn',
|
||||
bericht: 'Wanneer heb je plek?',
|
||||
subject: 'Newborn',
|
||||
message: 'Wanneer heb je plek?',
|
||||
hpCheck: '',
|
||||
token: 'signed-token',
|
||||
});
|
||||
const thanks = await screen.findByTestId('contact-form-sent');
|
||||
expect(thanks).toHaveTextContent(
|
||||
'Bedankt voor je bericht! Ik reageer binnen 1-2 werkdagen.',
|
||||
);
|
||||
await waitFor(() => expect(thanks).toHaveFocus());
|
||||
expect(screen.queryByTestId('contact-form')).toBeNull();
|
||||
expect(context.idempotencyKey).toMatch(/^[0-9a-f-]{36}$/);
|
||||
});
|
||||
|
||||
it('takes the reply time for the thank-you from the content', async () => {
|
||||
it('shows the thank-you with focus and takes the reply time from the content', async () => {
|
||||
await renderForm({ replyTime: '3 werkdagen' });
|
||||
fillIn();
|
||||
send();
|
||||
expect(
|
||||
await screen.findByTestId('contact-form-sent'),
|
||||
).toHaveTextContent('Ik reageer binnen 3 werkdagen.');
|
||||
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 () => {
|
||||
@@ -137,65 +194,62 @@ describe('ContactForm', () => {
|
||||
).toHaveAttribute('href', '/privacyverklaring');
|
||||
});
|
||||
|
||||
it('keeps the input and offers the mail link when sending fails', async () => {
|
||||
await renderForm({ submit: vi.fn().mockRejectedValue(new Error('x')) });
|
||||
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(
|
||||
screen.getByRole('link', { name: 'info@andreaslop.nl' }),
|
||||
).toHaveAttribute(
|
||||
'href',
|
||||
'mailto:info@andreaslop.nl?subject=Vraag%20via%20andreaslop.nl',
|
||||
);
|
||||
expect(field('naam')).toHaveValue('Demi');
|
||||
expect(screen.getByTestId('contact-form-submit')).not.toBeDisabled();
|
||||
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 submit = vi.fn();
|
||||
const { container } = await renderForm({ submit });
|
||||
const { container } = await renderForm();
|
||||
fillIn();
|
||||
fireEvent.change(
|
||||
container.querySelector('input[name="website"]') as Element,
|
||||
{ target: { value: 'https://spam.example' } },
|
||||
);
|
||||
fireEvent.change(container.querySelector('input[name="test-hp"]')!, {
|
||||
target: { value: 'https://spam.example' },
|
||||
});
|
||||
send();
|
||||
expect(screen.getByTestId('contact-form-sent')).toBeInTheDocument();
|
||||
expect(
|
||||
await screen.findByTestId('contact-form-sent'),
|
||||
).toBeInTheDocument();
|
||||
expect(submit).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('treats a submit within 3 seconds as spam', async () => {
|
||||
const submit = vi.fn();
|
||||
await renderForm({ submit });
|
||||
fillIn();
|
||||
now = 1_000;
|
||||
fireEvent.click(screen.getByTestId('contact-form-submit'));
|
||||
expect(screen.getByTestId('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('ignores a second submit while sending', async () => {
|
||||
let finish = () => {};
|
||||
const submit = vi.fn(
|
||||
() => new Promise<void>((resolve) => (finish = resolve)),
|
||||
);
|
||||
await renderForm({ submit });
|
||||
fillIn();
|
||||
send();
|
||||
fireEvent.click(screen.getByTestId('contact-form-submit'));
|
||||
expect(submit).toHaveBeenCalledTimes(1);
|
||||
await act(async () => finish());
|
||||
});
|
||||
|
||||
it('takes over a preselected package, also again after a change', async () => {
|
||||
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({
|
||||
shoot: 'newborn',
|
||||
subject: 'Newborn',
|
||||
key: 1,
|
||||
});
|
||||
return (
|
||||
@@ -212,44 +266,142 @@ describe('ContactForm', () => {
|
||||
idPrefix="test"
|
||||
options={options}
|
||||
preselect={preselect}
|
||||
mailSubject="Vraag via andreaslop.nl"
|
||||
email={siteContent.email}
|
||||
replyTime="1-2 werkdagen"
|
||||
availability={open()}
|
||||
client={client}
|
||||
/>
|
||||
</>
|
||||
);
|
||||
}
|
||||
await renderWithProviders(<Harness />);
|
||||
expect(field('shoot')).toHaveValue('newborn');
|
||||
type('shoot', 'gezin');
|
||||
expect(field('shoot')).toHaveValue('gezin');
|
||||
await waitFor(() => expect(field('shoot')).toHaveValue('Newborn'));
|
||||
type('shoot', 'Gezin');
|
||||
expect(field('shoot')).toHaveValue('Gezin');
|
||||
fireEvent.click(screen.getByRole('button', { name: 'nog eens' }));
|
||||
expect(field('shoot')).toHaveValue('newborn');
|
||||
await waitFor(() => expect(field('shoot')).toHaveValue('Newborn'));
|
||||
});
|
||||
|
||||
it('keeps the honeypot away from people and assistive technology', async () => {
|
||||
const { container } = await renderForm();
|
||||
const honeypot = container.querySelector('input[name="website"]');
|
||||
expect(honeypot).toHaveAttribute('tabindex', '-1');
|
||||
expect(honeypot?.closest('[aria-hidden="true"]')).not.toBeNull();
|
||||
expect(container.querySelector('[data-robot-check]')).not.toBeNull();
|
||||
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 (BR-MAIL-06)', async () => {
|
||||
it('does not hold the address, a token or a widget (BR-MAIL-06)', async () => {
|
||||
const html = await serverHtml(
|
||||
<ContactForm
|
||||
idPrefix="test"
|
||||
options={options}
|
||||
mailSubject="Vraag via andreaslop.nl"
|
||||
email={siteContent.email}
|
||||
replyTime="1-2 werkdagen"
|
||||
submit={vi.fn()}
|
||||
/>,
|
||||
);
|
||||
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');
|
||||
});
|
||||
});
|
||||
|
||||
Reference in New Issue
Block a user