Testing Higher-Order Components

Learn how to test the higher-order components and the core component that the higher-order component is based on.

We'll cover the following

Refactoring with higher-order components

With HasIndex, you can now make Carousel a stateless component. Instead of having an initialState and performing setState operations, Carousel will receive slideIndex as a prop and use the slideIndexDecrement and slideIndexIncrement props to update that value.

This change will make the “core” of Carousel simpler (especially as you add new features related to the slide index), but it complicates the shallow testing story. Up to now, Carousel has been a single component that contains all of its own logic. Now it will, in effect, be two components. You’re going to need three types of test to achieve full coverage:

  1. Tests for the component generated by HasIndex (which you already have)
  2. Tests for the core Carousel component
  3. Tests to ensure that the core and the HOC are properly wired together

The following are the steps to refactor with higher-order components:

  • Start by modifying Carousel.js so that it exports both the core Carousel component and, as the default export, a HasIndex-wrapped version:

Get hands-on with 1200+ tech skills courses.