Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

React - How to mock useFormContext (react-hook-form)

I am using useFormContext in one the child component. this is the code for it:

const { register } = useFormContext<CustomerProfileFormData>();

How can I Mock useFormContext so that I can test child component. this is the test

it('should render properly', () => {
    render(<AddressDetails isEdit={false} />);
    expect(screen.getByTestId('address-details')).toBeInTheDocument();
});

I am getting this error TypeError: Cannot destructure property 'register' of '(0 , _reactHookForm.useFormContext)(...)' as it is null.Jest.

which makes sense since I did not mock useFormContext . How can I Mock it? any help will be appreciated.

like image 708
Amit Uppal Avatar asked Jan 23 '26 00:01

Amit Uppal


1 Answers

You can either mock the context methods as indicated in other responses, or you can provide your component with an actual FormContext by creating an ad hoc wrapper component inside your test like this:

it('should do something', () => {
  const Wrapper = (props) => {
    const formMethods = useForm<CustomerProfileFormData>();

    return (
      <FormProvider {...formMethods}>
        {props.children}
      </FormProvider>
    );
  };

  render(
    <Wrapper>
      <AddressDetails />
    </Wrapper>
  );

  // your assertions here ... 
})

If you want to verify that your components behaves correctly upon form values, you could e.g. override the getValues method with preconfigured data.

const mockedGetValues = (key: string) => {
   // return test data for form key
}

return (
  <FormProvider {...formMethods} getValues={mockedGetValues}>
    {props.children}
  </FormProvider>
);
like image 88
Johannes Charra Avatar answered Jan 25 '26 20:01

Johannes Charra



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!