From 17289772adbb92f9931729482277b161a117eba7 Mon Sep 17 00:00:00 2001 From: Jhon Vente <134975835+johnvente@users.noreply.github.com> Date: Thu, 21 Sep 2023 06:16:14 -0500 Subject: [PATCH] feat: adding fallback component (#533) --- src/react/ErrorBoundary.jsx | 9 ++++++--- src/react/ErrorBoundary.test.jsx | 27 +++++++++++++++++++++++++++ 2 files changed, 33 insertions(+), 3 deletions(-) diff --git a/src/react/ErrorBoundary.jsx b/src/react/ErrorBoundary.jsx index 9b69e3853..a655e659f 100644 --- a/src/react/ErrorBoundary.jsx +++ b/src/react/ErrorBoundary.jsx @@ -11,7 +11,7 @@ import ErrorPage from './ErrorPage'; * @memberof module:React * @extends {Component} */ -export default class ErrorBoundary extends Component { +class ErrorBoundary extends Component { constructor(props) { super(props); this.state = { hasError: false }; @@ -28,17 +28,20 @@ export default class ErrorBoundary extends Component { render() { if (this.state.hasError) { - return ; + return this.props.fallbackComponent || ; } - return this.props.children; } } ErrorBoundary.propTypes = { children: PropTypes.node, + fallbackComponent: PropTypes.node, }; ErrorBoundary.defaultProps = { children: null, + fallbackComponent: undefined, }; + +export default ErrorBoundary; diff --git a/src/react/ErrorBoundary.test.jsx b/src/react/ErrorBoundary.test.jsx index 3e4ce0a28..538f2b6fa 100644 --- a/src/react/ErrorBoundary.test.jsx +++ b/src/react/ErrorBoundary.test.jsx @@ -2,6 +2,7 @@ import React from 'react'; import { mount } from 'enzyme'; import ErrorBoundary from './ErrorBoundary'; +import ErrorPage from './ErrorPage'; import { initializeMockApp } from '..'; describe('ErrorBoundary', () => { @@ -54,4 +55,30 @@ describe('ErrorBoundary', () => { }), ); }); + it('should render the fallback component when an error occurs', () => { + function FallbackComponent() { + return
Oops, something went wrong!
; + } + function ComponentError() { + throw new Error('An error occurred during the click event!'); + } + const wrapper = mount( + }> + + , + ); + expect(wrapper.contains()).toBe(true); + }); + + it('should render the ErrorPage fallbackComponent is null', () => { + function ComponentError() { + throw new Error('An error occurred during the click event!'); + } + const wrapper = mount( + + + , + ); + expect(wrapper.contains()).toBe(true); + }); });