Search code examples
reactjsjestjsreact-testing-libraryreact-hook-form

TypeError: Cannot destructure property 'ref' of 'register(...)' as it is undefined when testing React Hook Form V7


I'm trying to upgrade from React Hook Form V6 to V7. I've been able to do the update, but a few of my tests are broken now. The error that appears is:

TypeError: Cannot destructure property 'ref' of 'register(...)' as it is undefined.

I do some destructuring as the documentation shows:

const { register } = useForm();
const { ref, ...rest } = register('test');

So, I understand that the error message is regarding this destructure. The component takes the register as a prop. My previous tests worked with this code:

const register = jest.fn();

This unfortunately does not work any more. I've tried to do a good amount of searching, but all the problems regarding testing of React Hook Form is related to V6.

I have a feeling that you might need to do some mocking, but haven't been able to mock out something that would work.


Solution

  • I wouldn't give up. After trying a lot of different testing methhods, then it would seem that the answer to my problem was to mock out the jest function.

    const register = jest.fn(ref => 'Test');