import { render, screen } from '@testing-library/react'; import user from '@testing-library/user-event'; import React from 'react'; import { useForm } from 'react-hook-form'; import { Infer, object, size, string } from 'superstruct'; import { superstructResolver } from '..'; const schema = object({ username: size(string(), 2), password: size(string(), 6), }); type FormData = Infer; interface Props { onSubmit: (data: FormData) => void; } function TestComponent({ onSubmit }: Props) { const { register, formState: { errors }, handleSubmit, } = useForm({ resolver: superstructResolver(schema), // Useful to check TypeScript regressions }); return (
{errors.username && {errors.username.message}} {errors.password && {errors.password.message}}
); } test("form's validation with Superstruct and TypeScript's integration", async () => { const handleSubmit = vi.fn(); render(); expect(screen.queryAllByRole('alert')).toHaveLength(0); await user.click(screen.getByText(/submit/i)); expect( screen.getByText( /Expected a string with a length of `2` but received one with a length of `0`/i, ), ).toBeInTheDocument(); expect( screen.getByText( /Expected a string with a length of `6` but received one with a length of `0`/i, ), ).toBeInTheDocument(); expect(handleSubmit).not.toHaveBeenCalled(); }); export function TestComponentManualType({ onSubmit, }: { onSubmit: (data: FormData) => void; }) { const { register, handleSubmit, formState: { errors }, } = useForm, undefined, FormData>({ resolver: superstructResolver(schema), // Useful to check TypeScript regressions }); return (
{errors.username && {errors.username.message}} {errors.password && {errors.password.message}}
); }