import { render, screen } from '@testing-library/react'; import user from '@testing-library/user-event'; import { Validator } from 'fluentvalidation-ts'; import React from 'react'; import { useForm } from 'react-hook-form'; import { fluentValidationResolver } from '../fluentvalidation-ts'; const USERNAME_REQUIRED_MESSAGE = 'username field is required'; const PASSWORD_REQUIRED_MESSAGE = 'password field is required'; type FormData = { username: string; password: string; }; class FormDataValidator extends Validator { constructor() { super(); this.ruleFor('username').notEmpty().withMessage(USERNAME_REQUIRED_MESSAGE); this.ruleFor('password').notEmpty().withMessage(PASSWORD_REQUIRED_MESSAGE); } } interface Props { onSubmit: (data: FormData) => void; } function TestComponent({ onSubmit }: Props) { const { register, handleSubmit } = useForm({ resolver: fluentValidationResolver(new FormDataValidator()), shouldUseNativeValidation: true, }); return (
); } test("form's native validation with fluentvalidation-ts", async () => { const handleSubmit = vi.fn(); render(); // username let usernameField = screen.getByPlaceholderText( /username/i, ) as HTMLInputElement; expect(usernameField.validity.valid).toBe(true); expect(usernameField.validationMessage).toBe(''); // password let passwordField = screen.getByPlaceholderText( /password/i, ) as HTMLInputElement; expect(passwordField.validity.valid).toBe(true); expect(passwordField.validationMessage).toBe(''); await user.click(screen.getByText(/submit/i)); // username usernameField = screen.getByPlaceholderText(/username/i) as HTMLInputElement; expect(usernameField.validity.valid).toBe(false); expect(usernameField.validationMessage).toBe(USERNAME_REQUIRED_MESSAGE); // password passwordField = screen.getByPlaceholderText(/password/i) as HTMLInputElement; expect(passwordField.validity.valid).toBe(false); expect(passwordField.validationMessage).toBe(PASSWORD_REQUIRED_MESSAGE); await user.type(screen.getByPlaceholderText(/username/i), 'joe'); await user.type(screen.getByPlaceholderText(/password/i), 'password'); // username usernameField = screen.getByPlaceholderText(/username/i) as HTMLInputElement; expect(usernameField.validity.valid).toBe(true); expect(usernameField.validationMessage).toBe(''); // password passwordField = screen.getByPlaceholderText(/password/i) as HTMLInputElement; expect(passwordField.validity.valid).toBe(true); expect(passwordField.validationMessage).toBe(''); });