2

I am wondering how to test component that use react-hook-form. Control object is passed to children component DimensionInput

I used suggested in (How to call or mock useForm on jest react native?) solution but stil getting error

  afterEach(() => {
    cleanup();
  });

  it('renders correct text', () => {
    jest.mock('react-hook-form', () => ({
      ...jest.requireActual('react-hook-form'),
      Controller: () => <></>,
      useForm: () => ({
        control: () => ({}),
        handleSubmit: () => jest.fn(),
      }),
    }));

    const { control } = useForm({
      mode: 'onChange',
    });
    const { queryByText } = render(
      <DimensionsInput fieldId={'id'} buttonAction={null} control={control} />,
    );

    expect(queryByText('text')).toBeTruthy();
  });
});```


my error Error:
```TypeError: Cannot read properties of undefined (reading '__H')```
adampicker
  • 29
  • 1
  • 1
  • 6

2 Answers2

0

Please refer to the actual docs on how to test forms made by react-hook-form. There is no need to invoke the useForm hook in the test.

Use the ByRole method when querying different elements because that's how users recognize your UI component.

  1. Mock the Login function. Something like -
const mockLogin = jest.fn((email, password) => {
  return Promise.resolve({ email, password });
});
  1. Tests for failures / incorrect submissions. Example -
it("should display matching error when email is invalid", async () => {
    fireEvent.input(screen.getByRole("textbox", { name: /email/i }), {
      target: {
        value: "test"
      }
    });

    fireEvent.input(screen.getByLabelText("password"), {
      target: {
        value: "password"
      }
    });

    fireEvent.submit(screen.getByRole("button"));

    expect(await screen.findAllByRole("alert")).toHaveLength(1);
    expect(mockLogin).not.toBeCalled();
    expect(screen.getByRole("textbox", { name: /email/i }).value).toBe("test");
    expect(screen.getByLabelText("password").value).toBe("password");
  });
A G
  • 21,087
  • 11
  • 87
  • 112
  • Yes, but in my case i have to provide control object: ```export function DimensionsInput({ control, unit = 'cm', multiline = false, rows = 1, buttonAction, fieldId, }: DimensionsInputProps): ReactElement {``` – adampicker May 11 '22 at 10:09
  • @adampicker Please create a working codesandbox so we can understand better. – A G May 11 '22 at 17:00
0

This is also a good alternative when you don't want to mock the useForm function https://stackoverflow.com/a/75668939/2774342

dani24
  • 2,108
  • 2
  • 26
  • 28