Skip to content

Commit

Permalink
feat: adding fallback component (#533)
Browse files Browse the repository at this point in the history
  • Loading branch information
johnvente authored Sep 21, 2023
1 parent 9f4f5fd commit 1728977
Show file tree
Hide file tree
Showing 2 changed files with 33 additions and 3 deletions.
9 changes: 6 additions & 3 deletions src/react/ErrorBoundary.jsx
Original file line number Diff line number Diff line change
Expand Up @@ -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 };
Expand All @@ -28,17 +28,20 @@ export default class ErrorBoundary extends Component {

render() {
if (this.state.hasError) {
return <ErrorPage />;
return this.props.fallbackComponent || <ErrorPage />;
}

return this.props.children;
}
}

ErrorBoundary.propTypes = {
children: PropTypes.node,
fallbackComponent: PropTypes.node,
};

ErrorBoundary.defaultProps = {
children: null,
fallbackComponent: undefined,
};

export default ErrorBoundary;
27 changes: 27 additions & 0 deletions src/react/ErrorBoundary.test.jsx
Original file line number Diff line number Diff line change
Expand Up @@ -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', () => {
Expand Down Expand Up @@ -54,4 +55,30 @@ describe('ErrorBoundary', () => {
}),
);
});
it('should render the fallback component when an error occurs', () => {
function FallbackComponent() {
return <div>Oops, something went wrong!</div>;
}
function ComponentError() {
throw new Error('An error occurred during the click event!');
}
const wrapper = mount(
<ErrorBoundary fallbackComponent={<FallbackComponent />}>
<ComponentError />
</ErrorBoundary>,
);
expect(wrapper.contains(<FallbackComponent />)).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(
<ErrorBoundary fallbackComponent={null}>
<ComponentError />
</ErrorBoundary>,
);
expect(wrapper.contains(<ErrorPage />)).toBe(true);
});
});

0 comments on commit 1728977

Please sign in to comment.