import React from 'react'; import { render, screen, act } from '@testing-library/react'; import user from '@testing-library/user-event'; import { SubmitHandler, useForm } from 'react-hook-form'; import { classValidatorResolver } from '..'; import { IsNotEmpty } from 'class-validator'; class Schema { @IsNotEmpty() username: string; @IsNotEmpty() password: string; } interface Props { onSubmit: SubmitHandler; } function TestComponent({ onSubmit }: Props) { const { register, formState: { errors }, handleSubmit, } = useForm({ resolver: classValidatorResolver(Schema), }); return (
{errors.username && {errors.username.message}} {errors.password && {errors.password.message}}
); } test("form's validation with Class Validator and TypeScript's integration", async () => { const handleSubmit = jest.fn(); render(); expect(screen.queryAllByRole(/alert/i)).toHaveLength(0); await act(async () => { user.click(screen.getByText(/submit/i)); }); expect(screen.getByText(/username should not be empty/i)).toBeInTheDocument(); expect(screen.getByText(/password should not be empty/i)).toBeInTheDocument(); expect(handleSubmit).not.toHaveBeenCalled(); });