You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
Copy file name to clipboardExpand all lines: docs/react-testing-library/faq.mdx
+50Lines changed: 50 additions & 0 deletions
Original file line number
Diff line number
Diff line change
@@ -81,6 +81,56 @@ as part of the `change` method call.
81
81
82
82
<details>
83
83
84
+
<summary>How do I test error boundaries</summary>
85
+
86
+
To test if an error boundary successfully catches an error, you should make sure that if the fallback of the boundary is displayed when a child threw.
87
+
88
+
Here's an example of how you can test an error boundary:
89
+
90
+
```jsx
91
+
import React from 'react'
92
+
import {render, screen} from '@testing-library/react'
93
+
94
+
class ErrorBoundary extends React.Component {
95
+
state = {error: null}
96
+
static getDerivedStateFromError(error) {
97
+
return {error}
98
+
}
99
+
render() {
100
+
const {error} = this.state
101
+
if (error) {
102
+
return <div>Something went wrong</div>
103
+
}
104
+
return this.props.children
105
+
}
106
+
}
107
+
108
+
test('error boundary catches error', () => {
109
+
const {container} = render(
110
+
<ErrorBoundary>
111
+
<BrokenComponent />
112
+
</ErrorBoundary>,
113
+
)
114
+
expect(container.textContent).toEqual('Something went wrong.')
115
+
})
116
+
117
+
If the error boundary did not catch the error, the test would fail since the `render` call would throw the error the Component produced.
118
+
119
+
120
+
:::info
121
+
122
+
React 18 will call `console.error` with an extended error message.
123
+
React 19 will call `console.warn` with an extended error message.
124
+
125
+
To disable the additional `console.warn` call in React 19, you can provide a custom `onCaughtError` callback e.g. `render(<App />, {onCaughtError: () => {}})`
126
+
`onCaughtError` is not supported in React 18.
127
+
128
+
:::
129
+
130
+
</details>
131
+
132
+
<details>
133
+
84
134
<summary>Can I write unit tests with this library?</summary>
85
135
86
136
Definitely yes! You can write unit and integration tests with this library. See
0 commit comments