Let's say I had a component with the following error boundary and componentDidCatch method:
return (
<ErrorBoundary
componentDidCatch(error, info) {
handleError(error, info);
}
>
<MyComponent>
// The rest of the component & its children
</MyComponent>
</ErrorBoundary>
)
Now, in my Jest unit test, I have rendered MyComponent but want to throw an error inside of it or one of its children in order to trigger the ErrorBoundary and its handleError method.
When I manually tested the ErrorBoundary, I just threw an error using throw new Error('Error') inside of a useEffect.
It seems like the solution is to add some sort of onError prop to the component and pass an Error into it on render in order to trigger the error boundary. This feels unintuitive and like a forced solution when it could be elegant.
Is there a better way to go about this??
I tried to mock a component that solely throws an error, but it did not trigger my ErrorBoundary:
test('Error Boundary', () => {
const ThrowError = () => {
throw new Error('Test');
};
render(
<ChildOfMyComponent>
<ThrowError />
);
// etc