JavaScript - - By Camilo Reyes

A Guide to Testing React Components

For a high-quality, in-depth introduction to React, you can’t go past Canadian full-stack developer Wes Bos. Try his course here, and use the code SITEPOINT to get 25% off and to help support SitePoint.

React is a framework that has made headway within the JavaScript developer community. React has a powerful composition framework for designing components. React components are bits of reusable code you can wield in your web application.

React components are not tightly coupled from the DOM, but how easy are they to unit test? In this take, let’s explore what it takes to unit test React components. I’ll show the thought process for making your components testable.

Keep in mind, I’m only talking about unit tests, which are a special kind of test. (For more on the different kinds of tests, I recommend you read “JavaScript Testing: Unit vs Functional vs Integration Tests”.)

With unit tests, I’m interested in two things: rapid and neck-breaking feedback. With this, I can iterate through changes with a high degree of confidence and code quality. This gives you a level of reassurance that your React components will not land dead on the browser. Being capable of getting good feedback at a rapid rate gives you a competitive edge — one that you’ll want to keep in today’s world of agile software development.

For the demo, let’s do a list of the great apes, which is filterable through a checkbox. You can find the entire codebase on GitHub. For the sake of brevity, I’ll show only the code samples that are of interest. This article assumes a working level of knowledge with React components.

If you go download and run the demo sample code, you’ll see a page like this:

The Great Apes Demo in React Components

Write Testable Components

In React, a good approach is to start with a hierarchy of components. The single responsibility principle comes to mind when building each individual component. React components use object composition and relationships.

For the list of the great apes, for example, I have this approach:

FilterableGreatApeList
|_ GreatApeSearchBar
|_ GreatApeList
   |_ GreatApeRow

Take a look at how a great ape list has many great ape rows with data. React components make use of this composition data model, and it’s also testable.

In React components, avoid using inheritance to build reusable components. If you come from a classic object-oriented programming background, keep this in mind. React components don’t know their children ahead of time. Testing components that descend from a long chain of ancestors can be a nightmare.

I’ll let you explore the FilterableGreatApeList on your own. It’s a React component with two separate components that are of interest here. Feel free to explore the unit tests that come with it, too.

To build a testable GreatApeSearchBar, for example, do this:

class GreatApeSearchBar extends Component {
  constructor(props) {
    super(props);

    this.handleShowExtantOnlyChange = this.handleShowExtantOnlyChange.bind(this);
  }

  handleShowExtantOnlyChange(e) {
    this.props.onShowExtantOnlyInput(e.target.checked);
  }

  render() {
    return(
      <form>
        <input
          id="GreatApeSearchBar-showExtantOnly"
          type="checkbox"
          checked={this.props.showExtantOnly}
          onChange={this.handleShowExtantOnlyChange}
        />

        <label htmlFor="GreatApeSearchBar-showExtantOnly">Only show extant species</label>
      </form>
    );
  }
}

This component has a checkbox with a label and wires up a click event. This approach may already be all too familiar to you, which is a very good thing.

Note that with React, testable components come for free, straight out of the box. There’s nothing special here — an event handler, JSX, and a render method.

The next React component in the hierarchy is the GreatApeList, and it looks like this:

class GreatApeList extends Component {
  render() {
    let rows = [];

    this.props.apes.forEach((ape) => {
      if (!this.props.showExtantOnly) {
        rows.push(<GreatApeRow key={ape.name} ape={ape} />);

        return;
      }

      if (ape.isExtant) {
        rows.push(<GreatApeRow key={ape.name} ape={ape} />);
      }
    });

    return (
      <div>
        {rows}
      </div>
    );
  }
}

It’s a React component that has the GreatApeRow component and it’s using object composition. This is React’s most powerful composition model at work. Note the lack of inheritance when you build reusable yet testable components.

In programming, object composition is a design pattern that enables data-driven elements. To think of it another way, a GreatApeList has many GreatApeRow objects. It’s this relationship between UI components that drives the design. React components have this mindset built in. This way of looking at UI elements allows you to write some nice unit tests.

Here, you check for the this.props.showExtantOnly flag that comes from the checkbox. This showExtantOnly property gets set through the event handler in GreatApeSearchBar.

For unit tests, how do you unit test React components that depend on other components? How about components intertwined with each other? These are great questions to keep in mind as we get into testing soon. React components may yet have secrets one can unlock.

For now, let’s look at the GreatApeRow, which houses the great ape data:

class GreatApeRow extends Component {
  render() {
    return (
      <div>
        <img
          className="GreatApeRow-image"
          src={this.props.ape.image}
          alt={this.props.ape.name}
        />

        <p className="GreatApeRow-detail">
          <b>Species:</b> {this.props.ape.name}
        </p>

        <p className="GreatApeRow-detail">
          <b>Age:</b> {this.props.ape.age}
        </p>
      </div>
    );
  }
}

With React components, it’s practical to isolate each UI element with a laser focus on a single concern. This has key advantages when it comes to unit testing. As long as you stick to this design pattern, you’ll find it seamless to write unit tests.

Test Utilities

Let’s recap our biggest concern when it comes to testing React components. How do I unit test a single component in isolation? Well, as it turns out, there’s a nifty utility that enables you to do that.

The Shallow Renderer in React allows you to render a component one level deep. From this, you can assert facts about what the render method does. What’s remarkable is that it doesn’t require a DOM.

Using ES6, you use it like this:

import ShallowRenderer from 'react-test-renderer/shallow';

In order for unit tests to run fast, you need a way to test components in isolation. This way, you can focus on a single problem, test it, and move on to the next concern. This becomes empowering as the solution grows and you’re able to refactor at will — staying close to the code, making rapid changes, and gaining reassurance it will work in a browser.

One advantage of this approach is you think better about the code. This produces the best solution that deals with the problem at hand. I find it liberating when you’re not chained to a ton of distractions. The human brain does a terrible job at dealing with more than one problem at a time.

The only question remaining is, how far can this little utility take us with React components?

Put It All Together

Take a look at GreatApeList, for example. What’s the main concern you’re trying to solve? This component shows you a list of great apes based on a filter.

An effective unit test is to pass in a list and check facts about what this React component does. We want to ensure it filters the great apes based on a flag.

One approach is to do this:

import GreatApeList from './GreatApeList';

const APES = [{ name: 'Australopithecus afarensis', isExtant: false },
  { name: 'Orangutan', isExtant: true }];

// Arrange
const renderer = new ShallowRenderer();
renderer.render(<GreatApeList
  apes={APES}
  showExtantOnly={true} />);

// Act
const component = renderer.getRenderOutput();
const rows = component.props.children;

// Assert
expect(rows.length).toBe(1);

Note that I’m testing React components using Jest. For more on this, check out “How to Test React Components Using Jest”.

In JSX, take a look at showExtantOnly={true}. The JSX syntax allows you to set a state to your React components. This opens up many ways to unit test components given a specific state. JSX understands basic JavaScript types, so a true flag gets set as a boolean.

With the list out of the way, how about the GreatApeSearchBar? It has this event handler in the onChange property that might be of interest.

One good unit test is to do this:

import GreatApeSearchBar from './GreatApeSearchBar';

// Arrange
let showExtantOnly = false;
const onChange = (e) => { showExtantOnly = e };

const renderer = new ShallowRenderer();
renderer.render(<GreatApeSearchBar
  showExtantOnly={true}
  onShowExtantOnlyInput={onChange} />);

// Act
const component = renderer.getRenderOutput();
const checkbox = component.props.children[0];

checkbox.props.onChange({ target: { checked: true } });

// Assert
expect(showExtantOnly).toBe(true);

To handle and test events, you use the same shallow rendering method. The getRenderOutput method is useful for binding callback functions to components with events. Here, the onShowExtantOnlyInput property gets assigned the callback onChange function.

On a more trivial unit test, what about the GreatApeRow React component? It displays great ape information using HTML tags. Turns out, you can use the shallow renderer to test this component too.

For example, let’s ensure we render an image:

import GreatApeRow from './GreatApeRow';

const APE = {
  image: 'https://en.wikipedia.org/wiki/File:Australopithecus_afarensis.JPG',
  name: 'Australopithecus afarensis'
};

// Arrange
const renderer = new ShallowRenderer();
renderer.render(<GreatApeRow ape={APE} />);

// Act
const component = renderer.getRenderOutput();
const apeImage = component.props.children[0];

// Assert
expect(apeImage).toBeDefined();
expect(apeImage.props.src).toBe(APE.image);
expect(apeImage.props.alt).toBe(APE.name);

With React components, it all centers around the render method. This makes it somewhat intuitive to know exactly what you need to test. A shallow renderer makes it so you can laser focus on a single component while eliminating noise.

Recommended Courses

Wes Bos
A step-by-step training course to get you building real world React.js + Firebase apps and website components in a couple of afternoons. Use coupon code 'SITEPOINT' at checkout to get 25% off.

Conclusion

As shown, React components are very testable. There’s no excuse to forgo writing good unit tests for your components.

The nice thing is that JSX works for you in each individual test, not against you. With JSX, you can pass in booleans, callbacks, or whatever else you need. Keep this in mind as you venture out into unit testing React components on your own.

The shallow renderer test utility gives you all you need for good unit tests. It only renders one level deep and allows you to test in isolation. You’re not concerned with any arbitrary child in the hierarchy that might break your unit tests.

With the Jest tooling, I like how it gives you feedback only on the specific files you’re changing. This shortens the feedback loop and adds laser focus. I hope you see how valuable this can be when you tackle some tough issues.