0

I have built a component which requires a methods and data supplied by custom hook

const MyComponent = () => {
  const { data, methods } = useMyCustomHook({ defaultValues: defaultValues });

  return <MyAnotherComponent data={data} label="Some Text" method={methods} />;
}

I am writing test using react testing library to test MyComponent or to be more specific to test MyAnotherComponent

Here is my testing code

test("Test MyAnotherComponent Label", () => {
  const { data, methods } = useMyCustomHook({ defaultValues: defaultValues });
  render(
    <MyAnotherComponent
      data={data}
      label="Some Text"
      method={methods}
    />
  );
  expect(screen.getByLabelText("Some Text")).toBeInTheDocument();
});

My testcase fails with an error saying Invalid hook call. Hooks can only be called inside of the body of a function component. This could happen for one of the following reasons

I have looked up for solutions but some are too simple and some are too complex. Thanks in advance

2
  • Error seems pretty self-explanatory, no? You're calling a hook outside the body of a function component in your test case. Just render the component. Commented Aug 4, 2022 at 22:52
  • Rendering the component doesn't work either. It will cause useContext error in the test. I'm working through this myself. Commented Mar 10, 2023 at 14:25

1 Answer 1

1

The error is caused by the fact that you are calling the hook inside a function, not inside a React component. Since you only want to test MyAnotherComponent, I don't see why you'd need to call the hook and not mock the data and methods directly to pass them to MyAnotherComponent because what you are currently doing is to re-write MyComponent.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.