}).__rhf;
return (
{schema.fields.map((f) => (
))}
);
}
describe('a minimal third-party renderer over AddressRendererProps', () => {
let container: HTMLElement | undefined;
let root: ReturnType | undefined;
afterEach(() => {
act(() => root?.unmount());
container?.remove();
});
it('submits a complete address and rejects a bad ZIP through the schema rules', async () => {
let form!: ReturnType;
function Page() {
form = useForm({ mode: 'onSubmit' });
(globalThis as unknown as { __rhf: typeof form }).__rhf = form;
return (
);
}
container = document.createElement('div');
document.body.appendChild(container);
root = createRoot(container);
await act(async () => {
root!.render();
});
expect(container.querySelectorAll('input[data-field]')).toHaveLength(us.fields.length);
const fill = (values: Record) => {
for (const [id, value] of Object.entries(values)) {
form.setValue(`shippingAddress.${id}`, value);
}
};
const onValid = jest.fn();
const onInvalid = jest.fn();
await act(async () => {
fill({ country: 'US', recipient: 'Ada Lovelace', telephone: '+14085551234', address_line_1: '1 Infinite Loop', locality: 'Cupertino', administrative_area: 'CA', postal_code: '9501' });
await form.handleSubmit(onValid, onInvalid)();
});
expect(onValid).not.toHaveBeenCalled();
expect(onInvalid).toHaveBeenCalledTimes(1);
const errors = onInvalid.mock.calls[0][0] as { shippingAddress?: Record };
expect(errors.shippingAddress?.postal_code?.message).toBe('ZIP code is not valid');
await act(async () => {
fill({ postal_code: '95014' });
await form.handleSubmit(onValid, onInvalid)();
});
expect(onValid).toHaveBeenCalledTimes(1);
// Every schema field is in the payload (optional ones empty), nothing else.
const expected: Record = Object.fromEntries(us.fields.map((f) => [f.id, '']));
Object.assign(expected, {
country: 'US',
recipient: 'Ada Lovelace',
telephone: '+14085551234',
address_line_1: '1 Infinite Loop',
locality: 'Cupertino',
administrative_area: 'CA',
postal_code: '95014'
});
expect(onValid.mock.calls[0][0]).toEqual({ shippingAddress: expected });
});
});