Skip to content

Commit 1728977

Browse files
authored
feat: adding fallback component (#533)
1 parent 9f4f5fd commit 1728977

File tree

2 files changed

+33
-3
lines changed

2 files changed

+33
-3
lines changed

src/react/ErrorBoundary.jsx

Lines changed: 6 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -11,7 +11,7 @@ import ErrorPage from './ErrorPage';
1111
* @memberof module:React
1212
* @extends {Component}
1313
*/
14-
export default class ErrorBoundary extends Component {
14+
class ErrorBoundary extends Component {
1515
constructor(props) {
1616
super(props);
1717
this.state = { hasError: false };
@@ -28,17 +28,20 @@ export default class ErrorBoundary extends Component {
2828

2929
render() {
3030
if (this.state.hasError) {
31-
return <ErrorPage />;
31+
return this.props.fallbackComponent || <ErrorPage />;
3232
}
33-
3433
return this.props.children;
3534
}
3635
}
3736

3837
ErrorBoundary.propTypes = {
3938
children: PropTypes.node,
39+
fallbackComponent: PropTypes.node,
4040
};
4141

4242
ErrorBoundary.defaultProps = {
4343
children: null,
44+
fallbackComponent: undefined,
4445
};
46+
47+
export default ErrorBoundary;

src/react/ErrorBoundary.test.jsx

Lines changed: 27 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,7 @@ import React from 'react';
22
import { mount } from 'enzyme';
33

44
import ErrorBoundary from './ErrorBoundary';
5+
import ErrorPage from './ErrorPage';
56
import { initializeMockApp } from '..';
67

78
describe('ErrorBoundary', () => {
@@ -54,4 +55,30 @@ describe('ErrorBoundary', () => {
5455
}),
5556
);
5657
});
58+
it('should render the fallback component when an error occurs', () => {
59+
function FallbackComponent() {
60+
return <div>Oops, something went wrong!</div>;
61+
}
62+
function ComponentError() {
63+
throw new Error('An error occurred during the click event!');
64+
}
65+
const wrapper = mount(
66+
<ErrorBoundary fallbackComponent={<FallbackComponent />}>
67+
<ComponentError />
68+
</ErrorBoundary>,
69+
);
70+
expect(wrapper.contains(<FallbackComponent />)).toBe(true);
71+
});
72+
73+
it('should render the ErrorPage fallbackComponent is null', () => {
74+
function ComponentError() {
75+
throw new Error('An error occurred during the click event!');
76+
}
77+
const wrapper = mount(
78+
<ErrorBoundary fallbackComponent={null}>
79+
<ComponentError />
80+
</ErrorBoundary>,
81+
);
82+
expect(wrapper.contains(<ErrorPage />)).toBe(true);
83+
});
5784
});

0 commit comments

Comments
 (0)