Manual Approach to Testing Hooks

Explore the techniques for manually testing React Hooks.

Testing hooks by creating a test component

The most simple way to test a hook is by using a test component and then calling the custom hook in this component.

From the previous example, if you have a custom hook like this:

const useContent = () => {
  const [state] = useState("some text");
  return state;
};

Then, you can create a TestComponent to return output of the above hook:

const TestComponent = () => {
  return useContent();
};

The following example demonstrates testing with Enzyme and Jest in useContent.test.js. shallow on Line #14 renders TestComponent. Line #15 tests the text available in the wrapper. This test is enough to determine whether the output of the hook was correctly available or not.

Get hands-on with 1200+ tech skills courses.