'Is it possible to test Sentry.ErrorBoundary rendering in jest?

I've just implemented the Sentry.ErrorBoundary component and I was wondering if it was possible to test the rendering of it. For example:

<Sentry.ErrorBoundary>
    <FailComponent />
  </Sentry.ErrorBoundary>

or

<Sentry.ErrorBoundary>
    <SuccessComponent />
  </Sentry.ErrorBoundary>


Solution 1:[1]

I' d suggest another approach on this, which is to work with a custom ErrorBoundary HO-component, as react doc (https://reactjs.org/docs/error-boundaries.html) and catch the error into the componentDidCatch() function, instead.

In this way you can more easily test your hoc component.

The error boundary component will be like so:

import * as Sentry from '@sentry/browser';

type State = {
  hasError?: boolean,
  eventId?: string,
  error: null | Error,
  errorInfo?: null | {componentStack: string},
};

type Props = {
  children: any,
}

class ErrorBoundary extends React.Component<Props, State> {
  constructor(props: Props) {
    super(props);
    this.state = {
      error: null,
    };
  }

  componentDidCatch(error: Error, errorInfo: any) {
    const { children } = this.props;

    // Configure what data you want to update, whenever an error happens.
    // Here, i update the breadcrumbs 
    Sentry.addBreadcrumb({
      type: Sentry.Severity.Error,
      category: 'component',
      message: children.props.name || 'n/a',
      level: Sentry.Severity.Error,
    });

    // Here, i set tag and some extra infos, plus the exception.

    Sentry.configureScope((scope: any) => {
      scope.setTag('component', children.props.name || 'n/a');
      scope.setExtra('component info', error);
      scope.setExtras(errorInfo);
      Sentry.captureException(error, scope);
      this.setState({
        error,
      });
    });
  }

  render() {
    const {
      error,
    } = this.state;

    const {
      children,
    } = this.props;

    // In case of an error, the fallback UI kicks in.
    if (error) {
      // custom fallback UI
      // We return an empty component with 'data-attr'
      //  with the failing component name (for debug purposes)
      return (
        <>
          <div data-attr={children.props.name} />
        </>
      );
    }

    return children;
  }
}

export default ErrorBoundary;

After the above, you can use the errorboundary hoc like so:

      <ErrorBoundary>
        <Mycomponent />
      </ErrorBoundary>

If an error happens into <Mycomponent />, the <ErrorBoundary /> will render, with the UI that you set

You can test it as you test your rest components, like check if it has been rendered. Hope this helps.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Theo Itzaris