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.
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.
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.