Prerna shah
Prerna shah

Reputation: 321

Unable to test HOC containing hooks using React testing library

Below is the code for HOC

const HOC = ({ component: Component }) => {
  return () => {
     const id = useQuery(query);
     return (<div> 
         {!id ? ( <SomeOtherComponent prop1={'hello'} prop2={'world'} /> ) : ( <Component /> )}
     </div>)
  }
}

Below is the test to render HOC-

const myComponent = () => <div data-testid={'component-testid'}>ABC</div>;
    const renderHOC = HOC({component: myComponent})();
    const {getByTestId} = render(renderHOC);
    expect(getByTestId('component-testid')).toBeInTheDocument();

Getting the error- Invalid hook call. React hooks must be called inside react functional component.

Upvotes: 0

Views: 1298

Answers (1)

johnny peter
johnny peter

Reputation: 4872

It should be as follows

const RenderHOC = HOC({component: myComponent});
const { getByTestId } = render(<RenderHOC />);

You cant call a component as a function if it contains hooks.

Upvotes: 1

Related Questions