Testing react-hook-form's V7 Controller API using Jest

Viewed 107

Is there a way to test a component that uses react-hook-form's Controller API using Jest?

I'm trying to create a unit test component that is using the controller API to make a function radio button , as you can see in the code below;

<Controller
    name="test"
    control={control}
    defaultValue="one"
    render={({ field: { onChange, value } }) => (
      <ToggleButtonGroup
        type="radio"
        name="test"
        value={value}
        onChange={onChange}
      >
        {collection.map((item) => (
          <ToggleButton key={item} value={item} variant="outline-primary">
            {item}
          </ToggleButton>
        ))}
      </ToggleButtonGroup>
    )}
  />

I did try mocking Controller using the below for a snapshot test;

jest.mock('react-hook-form', () => {
  return {
    Controller: () => (<></>),
    useFormContext() {
      return {
        control: jest.fn(),
      }
    },
  }
})

I used the test below to debug just to check the component;

describe('PaymentOptions component', () => {
  it('renders correctly billet, pix and card credit radio button', () => {
    const { debug } = render(<PaymentOptions />)

    debug()
  })
})

But what is returned in the component has nothing to do with the component as shown in the image below;

enter image description here

Any idea how to do this?

0 Answers
Related