File tree 1 file changed +41
-0
lines changed
docs/react-testing-library
1 file changed +41
-0
lines changed Original file line number Diff line number Diff line change @@ -98,6 +98,47 @@ As you write your tests, keep in mind:
98
98
99
99
<details >
100
100
101
+ <summary >How do I test thrown errors in a Component or Hook?</summary >
102
+
103
+ If a component throws during render, the origin of the state update will throw if wrapped in ` act ` .
104
+ By default, ` render ` and ` fireEvent ` are wrapped in ` act ` .
105
+ You can just wrap it in a try-catch or use dedicated matchers if your test runner supports these.
106
+ For example, in Jest you can use ` toThrow ` :
107
+
108
+ ``` jsx
109
+ function Thrower () {
110
+ throw new Error (' I throw' )
111
+ }
112
+
113
+ test (' it throws' , () => {
114
+ expect (() => render (< Thrower / > )).toThrow (' I throw' )
115
+ })
116
+ ```
117
+
118
+ The same applies to Hooks and ` renderHook ` :
119
+
120
+ ``` jsx
121
+ function useThrower () {
122
+ throw new Error (' I throw' )
123
+ }
124
+
125
+ test (' it throws' , () => {
126
+ expect (() => renderHook (useThrower)).toThrow (' I throw' )
127
+ })
128
+ ```
129
+
130
+ :::info
131
+
132
+ React 18 will call ` console.error ` with an extended error message.
133
+ React 19 will call ` console.warn ` with an extended error message unless the state update is wrapped in ` act ` .
134
+ ` render ` , ` renderHook ` and ` fireEvent ` are wrapped in ` act ` by default.
135
+
136
+ :::
137
+
138
+ </details >
139
+
140
+ <details >
141
+
101
142
<summary >
102
143
If I can't use shallow rendering, how do I mock out components in tests?
103
144
</summary >
You can’t perform that action at this time.
0 commit comments