I’m currently working on writing a test for a select component using react-hook-forms. I have tried rewriting the test and mocking it many different ways, but I just can’t get the setValue hook mocked to check if it is called. Can someone please help me figure out what I’m doing wrong here?
Code for component
export const RelationshipSelector = () => {
const { setValue } = useFormContext()
const clearForm = (data) => {
if (data === 'child') {
setValue('form', {firstName: '', lastName: ''})
{
}
return (
<select name="relationship" label="Relationship" onChange={(data) => clearForm(data)}>
<option value="Parent">Parent</option>
<option value="Child">Child</option>
<option value="Relative">Relative</option>
</select>
)
}
Test for component
//mock data
const mockData = { relationship: '', form: {firstName: '', lastName: '' }
class WrapperFormProps {
children: ReactNode;
}
const WrapperForm: React.FC<WrapperFormProps> = ({ children }) => {
const methods = useForm({defaultValues: mockData});
return <FormProvider {...methods}>{children}</FormProvider>;
};
const renderRelationshipSelector = () => {
return renderWithProviders(
<WrapperForm>
<RelationshipSelector />
</WrapperForm>
);
};
describe('RelationshipSelector', () => {
it('should clear form values on child select', async () =>{
renderRelationshipSelector()
const selectElement = screen.getByRole('combobox');
fireEvent.change(selectElement, {target: {value: 'Child'}})
//how do I check if setValue is called here with the correct value?
});
});