Introduction

Why can’t you use the traditional way of unit testing with React Hooks?

Unit testing for React Hooks is an interesting topic. It requires a different approach compared to testing normal React components.

Assume you have a custom hook useContent to return some content value.

const useContent = () => {
  const [state] = useState('something');
  return state;
};

Write a simple test for the above hook using Jest expect like this.

test('useContent hook returns correct content', () => {
  expect(useContent()).toBe('something');
});

When this test is run, the following error occurs:

Invalid hook call. Hooks can only be called inside of the body of a function component.

Oops.

That’s right. You tried to call a React Hook using expect which is not a React component. The next few lessons will explore different approaches to testing React Hooks.

Get hands-on with 1200+ tech skills courses.