import * as React from 'react'; import { useForm, UseFormReturn, SubmitHandler,…
- User
import * as React from 'react'; import { useForm, UseFormReturn, SubmitHandler, UnpackNestedValue, DeepPartial, FormProvider, } from 'react-hook-form';
import { StyledFormContainer } from './styled';
export const FormContainer = < TFormValues extends Record<string, any> = Record<string, any>
({ children, onSubmit, defaultValues, mode = 'onChange', id, }: FormContainerProps) => { const methods = useForm({ mode, defaultValues, });
const handleKeyDown = (e: React.KeyboardEvent) => { if (e.key === 'Enter') { e.preventDefault(); } };
return ( <FormProvider {...methods}>{children(methods)} ); };
export type FormContainerProps = { defaultValues?: UnpackNestedValue<DeepPartial>; onSubmit: SubmitHandler; children: (methods: UseFormReturn) => React.ReactNode; mode?: 'onChange' | 'onBlur' | 'onTouched'; id?: string; };
could you create a form submission unit test for this component? using Jest and react resting library
- Assistant
Sure! Here's an example of how you can write a unit test for the
FormContainercomponent using Jest and React Testing Library:import { render, screen, fireEvent } from '@testing-library/react'; import userEvent from '@testing-library/user-event'; import { useForm } from 'react-hook-form'; import { FormContainer, FormContainerProps } from './FormContainer'; describe('FormContainer', () => { const onSubmitMock = jest.fn(); const setup = (props?: Partial<FormContainerProps<any>>) => { const TestForm = () => { const methods = useForm(); return ( <FormContainer onSubmit={onSubmitMock} {...props}> {methods => ( <form onSubmit={methods.handleSubmit}> <input type="text" {...methods.register('example')} /> <button type="submit">Submit</button> </form> )} </FormContainer> ); }; return render(<TestForm />); }; it('should call onSubmit when form is submitted with valid data', () => { setup(); const input = screen.getByRole('textbox'); const submitButton = screen.getByRole('button', { name: /submit/i }); userEvent.type(input, 'example value'); fireEvent.click(submitButton); expect(onSubmitMock).toHaveBeenCalledWith({ example: 'example value' }); }); it('should not call onSubmit when form is submitted with invalid data', () => { setup(); const submitButton = screen.getByRole('button', { name: /submit/i }); fireEvent.click(submitButton); expect(onSubmitMock).not.toHaveBeenCalled(); }); // Add more test cases as needed });