import { render, screen } from '@testing-library/react'; import user from '@testing-library/user-event'; import { JSONSchemaType } from 'ajv'; import React from 'react'; import { useForm } from 'react-hook-form'; import { ajvResolver } from '..'; type FormData = { username: string; password: string }; const schema: JSONSchemaType = { type: 'object', properties: { username: { type: 'string', minLength: 1, errorMessage: { minLength: 'username field is required' }, }, password: { type: 'string', minLength: 1, errorMessage: { minLength: 'password field is required' }, }, }, required: ['username', 'password'], additionalProperties: false, }; interface Props { onSubmit: (data: FormData) => void; } function TestComponent({ onSubmit }: Props) { const { register, formState: { errors }, handleSubmit, } = useForm({ resolver: ajvResolver(schema), // Useful to check TypeScript regressions }); return (
{errors.username && {errors.username.message}} {errors.password && {errors.password.message}}
); } test("form's validation with Ajv 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(/username field is required/i)).toBeInTheDocument(); expect(screen.getByText(/password field is required/i)).toBeInTheDocument(); expect(handleSubmit).not.toHaveBeenCalled(); });