React DevTools adds a feature to trigger an error boundary, making testing easier


React adds a new feature to React DevTools to force components into the error state for testing Error Boundaries. Before going into more details, let’s take a look at what Error Boundaries are.

Error Boundaries

Error boundaries are the React components that catch JavaScript errors anywhere in their child component tree, log those errors, and display a fallback UI instead of the component tree that crashed. Instead of breaking the whole app due to a JavaScript error, Error boundaries fail the part of the app gracefully.

Let’s check out the example mentioned in the PR.

import * as React from 'react';
import { Fragment } from 'react';

class ErrorBoundary extends React.Component {
  state = { hasError: false };

  static getDerivedStateFromError(error) {
    return {hasError: true};
  }
  render() {
    const { hasError } = this.state;
    if (hasError) {
      return (
        <div style=
          {{
            color: 'red',
            border: '1px solid red',
            borderRadius: '0.25rem',
            margin: '0.5rem',
            padding: '0.5rem'
          }}
          
          >
          An error was thrown.
        </div>
      );
    }

    const {children} = this.props;
    return (
      <div style=
        {{
          border: '1px solid gray',
          borderRadius: '0.25rem',
          margin: '0.5rem',
          padding: '0.5rem',
        }}
        
        >
        {children}
      </div>
    );
  }
}

function Component({label}) {
  return <div>{label}</div>;
}

export default function ErrorBoundaries() {
  return (
    <Fragment>
      <h1>Nested error boundaries demo</h1>
      <ErrorBoundary>
        <Component label="Outer component" />
        <ErrorBoundary>
          <Component label="Inner component" />
        </ErrorBoundary>
      </ErrorBoundary>
      <ErrorBoundary>
        <Component label="Neighbour component" />
      </ErrorBoundary>
    </Fragment>
  );
}

Before

Before the toggle feature in DevTools, developers had to explicitly set the state to error, in order to test how Error boundaries are handled. This makes testing a bit difficult.

In the above example, we need to make a below change to test the Error Boundary.

  state = { hasError: true };

After

With the new feature in React, developers can test the Error Boundaries by a toggle error button, added to the DevTools.

When we click on the toggle error button on the component labeled ‘Inner Component’, Error boundary is triggered. We see the An error was thrown text. In this way, we can test the error handling without making any changes to the code.