Skip to content

Commit f75eda0

Browse files
authored
fix: FallbackComponent type (#62)
* test: add failing tests * chore: add react-is as dep * fix: support all kind of component Closes #61 To fix the issue I have used the library from facebook 'react-is'. With this library we can check if the FallbackComponent is a real component. A component is not alwasy a function, but can be also object * chore: remove react-is dep * fix: check FallbackComponent if is defined instead of using react-is * test: simplify test after review
1 parent 7b7329d commit f75eda0

File tree

2 files changed

+37
-1
lines changed

2 files changed

+37
-1
lines changed

src/__tests__/index.js

Lines changed: 36 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -348,3 +348,39 @@ test('supports automatic reset of error boundary when resetKeys change', () => {
348348
expect(screen.queryByRole('alert')).not.toBeInTheDocument()
349349
expect(console.error).not.toHaveBeenCalled()
350350
})
351+
352+
test('should support not only function as FallbackComponent', () => {
353+
const FancyFallback = React.forwardRef(({error}) => (
354+
<div>
355+
<p>Everything is broken. Try again</p>
356+
<pre>{error.message}</pre>
357+
</div>
358+
))
359+
FancyFallback.displayName = 'FancyFallback'
360+
361+
expect(() =>
362+
render(
363+
<ErrorBoundary FallbackComponent={FancyFallback}>
364+
<Bomb />
365+
</ErrorBoundary>,
366+
),
367+
).not.toThrow()
368+
369+
expect(
370+
screen.getByText('Everything is broken. Try again'),
371+
).toBeInTheDocument()
372+
373+
console.error.mockClear()
374+
})
375+
376+
test('should throw error if FallbackComponent is not valid', () => {
377+
expect(() =>
378+
render(
379+
<ErrorBoundary FallbackComponent={{}}>
380+
<Bomb />
381+
</ErrorBoundary>,
382+
),
383+
).toThrowError(/Element type is invalid/i)
384+
385+
console.error.mockClear()
386+
})

src/index.js

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -39,7 +39,7 @@ class ErrorBoundary extends React.Component {
3939
return fallback
4040
} else if (typeof fallbackRender === 'function') {
4141
return fallbackRender(props)
42-
} else if (typeof FallbackComponent === 'function') {
42+
} else if (FallbackComponent) {
4343
return <FallbackComponent {...props} />
4444
} else {
4545
throw new Error(

0 commit comments

Comments
 (0)