Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I mock return value for handleSubmit from react-hook-form during tests?

I'm currently trying to test my form which has some very nested components and complex logic. So rather than actually mocking the userEvents and then submitting the form I want to mock a return value for handleSubmit

This is my react component:

import React from 'react';
import { FormProvider, useForm } from 'react-hook-form';

export const MyForm = (): JSX.Element => {
    const methods = useForm<{ name: string }>();

    const onSubmit = async (data: { name: string }): Promise<void> => {
        console.log(data);

        // logic to handle data.name
    };

    return (
        <div>
            <FormProvider {...methods}>
                <form onSubmit={methods.handleSubmit(onSubmit)}>
                    <div>{/* deeply nested components */}</div>
                    <div>
                        <button type="submit">Submit</button>
                        <button>Cancel</button>
                    </div>
                </form>
            </FormProvider>
        </div>
    );
};

And this is my test:

import { render } from '@testing-library/react';
import React from 'react';
import userEvent from '@testing-library/user-event';

jest.mock('react-hook-form', () => ({
    ...jest.requireActual('react-hook-form'),
    // handleSubmit: console.log('This log works when submitted'),
    handleSubmit: () => jest.fn().mockReturnValue({name: 'test'})
}));

describe('MyForm', () => {
    test('handles onSubmit correctly', async () => {
        render(<MyForm />);

        userEvent.click(screen.getByText('Submit'));
    });
});

So this is how much I've been able to mock. When I use userEvent to click the submit button. I can do a console.log in the test per above. But when I try to mock a value, in my React component inside the onSubmit function, the console.log(data) returns an empty object.

How can I mock it so that console.log(data) returns {name: 'test'} in my onSubmit function?

like image 674
ffx292 Avatar asked Dec 06 '25 10:12

ffx292


1 Answers

I would recommend not mocking useForm at all. This goes against the guiding principles of @testing-library.

Instead, use async testing utilities like waitFor and findBy*. See the react-hook-form docs at https://react-hook-form.com/advanced-usage#TestingForm for examples like this one:

it("should display required error when value is invalid", async () => {
  fireEvent.submit(screen.getByRole("button"));

  expect(await screen.findAllByRole("alert")).toHaveLength(2);
  expect(mockLogin).not.toBeCalled();
});
like image 200
Christian Jensen Avatar answered Dec 08 '25 00:12

Christian Jensen



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!