-
-
Notifications
You must be signed in to change notification settings - Fork 198
/
index.js
386 lines (346 loc) · 11.9 KB
/
index.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
import React from 'react'
import {render, screen} from '@testing-library/react'
import userEvent from '@testing-library/user-event'
import {ErrorBoundary, withErrorBoundary} from '..'
function ErrorFallback({error, componentStack, resetErrorBoundary}) {
return (
<div role="alert">
<p>Something went wrong:</p>
<pre>{error.message}</pre>
<pre>{componentStack}</pre>
<button onClick={resetErrorBoundary}>Try again</button>
</div>
)
}
function Bomb() {
throw new Error('💥 CABOOM 💥')
}
const firstLine = str => str.split('\n')[0]
test('standard use-case', async () => {
function App() {
const [username, setUsername] = React.useState('')
function handleChange(e) {
setUsername(e.target.value)
}
return (
<div>
<div>
<label htmlFor="username">Username</label>
<input type="text" id="username" onChange={handleChange} />
</div>
<div>{username === 'fail' ? 'Oh no' : 'things are good'}</div>
<div>
<ErrorBoundary FallbackComponent={ErrorFallback}>
{username === 'fail' ? <Bomb /> : 'type "fail"'}
</ErrorBoundary>
</div>
</div>
)
}
render(<App />)
await userEvent.type(screen.getByRole('textbox', {name: /username/i}), 'fail')
const [[actualError], [componentStack]] = console.error.mock.calls
expect(firstLine(actualError)).toMatchInlineSnapshot(
`"Error: Uncaught [Error: 💥 CABOOM 💥]"`,
)
expect(componentStack).toMatchInlineSnapshot(`
"The above error occurred in the <Bomb> component:
in Bomb
in ErrorBoundary
in div
in div
in Unknown
React will try to recreate this component tree from scratch using the error boundary you provided, ErrorBoundary."
`)
expect(console.error).toHaveBeenCalledTimes(2)
console.error.mockClear()
expect(screen.getByRole('alert')).toMatchInlineSnapshot(`
<div
role="alert"
>
<p>
Something went wrong:
</p>
<pre>
💥 CABOOM 💥
</pre>
<pre>
in Bomb
in ErrorBoundary
in div
in div
in Unknown
</pre>
<button>
Try again
</button>
</div>
`)
// can recover from errors when the component is rerendered and reset is clicked
await userEvent.type(screen.getByRole('textbox', {name: /username/i}), '-not')
userEvent.click(screen.getByRole('button', {name: /try again/i}))
expect(screen.queryByRole('alert')).not.toBeInTheDocument()
})
test('fallbackRender prop', () => {
const workingMessage = 'Phew, we are safe!'
function App() {
const [explode, setExplode] = React.useState(true)
return (
<div>
<ErrorBoundary
fallbackRender={({resetErrorBoundary}) => (
<button
onClick={() => {
setExplode(false)
resetErrorBoundary()
}}
>
Try again
</button>
)}
>
{explode ? <Bomb /> : workingMessage}
</ErrorBoundary>
</div>
)
}
render(<App />)
expect(console.error).toHaveBeenCalledTimes(2)
console.error.mockClear()
// the render prop API allows a single action to reset the app state
// as well as reset the ErrorBoundary state
userEvent.click(screen.getByRole('button', {name: /try again/i}))
expect(screen.getByText(workingMessage)).toBeInTheDocument()
})
test('simple fallback is supported', () => {
render(
<ErrorBoundary fallback={<div>Oh no</div>}>
<Bomb />
<span>child</span>
</ErrorBoundary>,
)
expect(console.error).toHaveBeenCalledTimes(2)
console.error.mockClear()
expect(screen.getByText(/oh no/i)).toBeInTheDocument()
expect(screen.queryByText(/child/i)).not.toBeInTheDocument()
})
test('withErrorBoundary HOC', () => {
const onErrorHandler = jest.fn()
const Boundary = withErrorBoundary(
() => {
throw new Error('💥 CABOOM 💥')
},
{FallbackComponent: ErrorFallback, onError: onErrorHandler},
)
render(<Boundary />)
const [[actualError], [componentStack]] = console.error.mock.calls
const firstLineOfError = firstLine(actualError)
expect(firstLineOfError).toMatchInlineSnapshot(
`"Error: Uncaught [Error: 💥 CABOOM 💥]"`,
)
expect(componentStack).toMatchInlineSnapshot(`
"The above error occurred in one of your React components:
in Unknown (created by withErrorBoundary(Unknown))
in ErrorBoundary (created by withErrorBoundary(Unknown))
in withErrorBoundary(Unknown)
React will try to recreate this component tree from scratch using the error boundary you provided, ErrorBoundary."
`)
expect(console.error).toHaveBeenCalledTimes(2)
console.error.mockClear()
const [error, onErrorComponentStack] = onErrorHandler.mock.calls[0]
expect(error.message).toMatchInlineSnapshot(`"💥 CABOOM 💥"`)
expect(onErrorComponentStack).toMatchInlineSnapshot(`
"
in Unknown (created by withErrorBoundary(Unknown))
in ErrorBoundary (created by withErrorBoundary(Unknown))
in withErrorBoundary(Unknown)"
`)
expect(onErrorHandler).toHaveBeenCalledTimes(1)
})
test('supported but undocumented reset method', () => {
const children = 'Boundry children'
function App() {
const errorBoundaryRef = React.useRef()
const [explode, setExplode] = React.useState(false)
return (
<>
<button onClick={() => setExplode(true)}>explode</button>
<button
onClick={() => {
setExplode(false)
errorBoundaryRef.current.resetErrorBoundary()
}}
>
recover
</button>
<ErrorBoundary ref={errorBoundaryRef} FallbackComponent={ErrorFallback}>
{explode ? <Bomb /> : children}
</ErrorBoundary>
</>
)
}
render(<App />)
userEvent.click(screen.getByText('explode'))
expect(screen.queryByText(children)).not.toBeInTheDocument()
expect(console.error).toHaveBeenCalledTimes(2)
console.error.mockClear()
userEvent.click(screen.getByText('recover'))
expect(screen.getByText(children)).toBeInTheDocument()
expect(console.error).toHaveBeenCalledTimes(0)
})
test('requires either a fallback, fallbackRender, or FallbackComponent', () => {
expect(() =>
render(
<ErrorBoundary>
<Bomb />
</ErrorBoundary>,
),
).toThrowErrorMatchingInlineSnapshot(
`"react-error-boundary requires either a fallback, fallbackRender, or FallbackComponent prop"`,
)
const [, , [actualError], [componentStack]] = console.error.mock.calls
expect(firstLine(actualError)).toMatchInlineSnapshot(
`"Error: Uncaught [Error: react-error-boundary requires either a fallback, fallbackRender, or FallbackComponent prop]"`,
)
expect(componentStack).toMatchInlineSnapshot(`
"The above error occurred in the <ErrorBoundary> component:
in ErrorBoundary
Consider adding an error boundary to your tree to customize error handling behavior.
Visit https://fb.me/react-error-boundaries to learn more about error boundaries."
`)
expect(console.error).toHaveBeenCalledTimes(4)
console.error.mockClear()
})
// eslint-disable-next-line max-statements
test('supports automatic reset of error boundary when resetKeys change', () => {
const handleReset = jest.fn()
const TRY_AGAIN_ARG1 = 'TRY_AGAIN_ARG1'
const TRY_AGAIN_ARG2 = 'TRY_AGAIN_ARG2'
const handleResetKeysChange = jest.fn()
function App() {
const [explode, setExplode] = React.useState(false)
const [extra, setExtra] = React.useState(false)
return (
<div>
<button onClick={() => setExplode(e => !e)}>toggle explode</button>
<ErrorBoundary
fallbackRender={({resetErrorBoundary}) => (
<div role="alert">
<button
onClick={() =>
resetErrorBoundary(TRY_AGAIN_ARG1, TRY_AGAIN_ARG2)
}
>
Try again
</button>
<button onClick={() => setExtra(e => !e)}>
toggle extra resetKey
</button>
</div>
)}
onReset={(...args) => {
setExplode(false)
handleReset(...args)
}}
onResetKeysChange={handleResetKeysChange}
resetKeys={extra ? [explode, extra] : [explode]}
>
{explode || extra ? <Bomb /> : null}
</ErrorBoundary>
</div>
)
}
render(<App />)
// blow it up
userEvent.click(screen.getByText('toggle explode'))
expect(screen.getByRole('alert')).toBeInTheDocument()
expect(console.error).toHaveBeenCalledTimes(2)
console.error.mockClear()
// recover via try again button
userEvent.click(screen.getByText(/try again/i))
expect(screen.queryByRole('alert')).not.toBeInTheDocument()
expect(console.error).not.toHaveBeenCalled()
expect(handleReset).toHaveBeenCalledWith(TRY_AGAIN_ARG1, TRY_AGAIN_ARG2)
expect(handleReset).toHaveBeenCalledTimes(1)
handleReset.mockClear()
expect(handleResetKeysChange).not.toHaveBeenCalled()
// blow it up again
userEvent.click(screen.getByText('toggle explode'))
expect(screen.getByRole('alert')).toBeInTheDocument()
expect(console.error).toHaveBeenCalledTimes(2)
console.error.mockClear()
// recover via resetKeys change
userEvent.click(screen.getByText('toggle explode'))
expect(handleResetKeysChange).toHaveBeenCalledWith([true], [false])
expect(handleResetKeysChange).toHaveBeenCalledTimes(1)
handleResetKeysChange.mockClear()
expect(handleReset).not.toHaveBeenCalled()
expect(screen.queryByRole('alert')).not.toBeInTheDocument()
expect(console.error).not.toHaveBeenCalled()
// blow it up again
userEvent.click(screen.getByText('toggle explode'))
expect(screen.getByRole('alert')).toBeInTheDocument()
expect(console.error).toHaveBeenCalledTimes(2)
console.error.mockClear()
// toggles adding an extra resetKey to the array
// expect error to re-render
userEvent.click(screen.getByText('toggle extra resetKey'))
expect(handleResetKeysChange).toHaveBeenCalledTimes(1)
expect(handleResetKeysChange).toHaveBeenCalledWith([true], [true, true])
handleResetKeysChange.mockClear()
expect(screen.getByRole('alert')).toBeInTheDocument()
expect(console.error).toHaveBeenCalledTimes(2)
console.error.mockClear()
// toggle explode back to false
// expect error to re-render again
userEvent.click(screen.getByText('toggle explode'))
expect(handleReset).not.toHaveBeenCalled()
expect(handleResetKeysChange).toHaveBeenCalledTimes(1)
expect(handleResetKeysChange).toHaveBeenCalledWith(
[true, true],
[false, true],
)
expect(screen.getByRole('alert')).toBeInTheDocument()
handleResetKeysChange.mockClear()
expect(console.error).toHaveBeenCalledTimes(2)
console.error.mockClear()
// toggle extra resetKey
// expect error to be reset
userEvent.click(screen.getByText('toggle extra resetKey'))
expect(handleReset).not.toHaveBeenCalled()
expect(handleResetKeysChange).toHaveBeenCalledTimes(1)
expect(handleResetKeysChange).toHaveBeenCalledWith([false, true], [false])
handleResetKeysChange.mockClear()
expect(screen.queryByRole('alert')).not.toBeInTheDocument()
expect(console.error).not.toHaveBeenCalled()
})
test('should support not only function as FallbackComponent', () => {
const FancyFallback = React.forwardRef(({error}) => (
<div>
<p>Everything is broken. Try again</p>
<pre>{error.message}</pre>
</div>
))
FancyFallback.displayName = 'FancyFallback'
expect(() =>
render(
<ErrorBoundary FallbackComponent={FancyFallback}>
<Bomb />
</ErrorBoundary>,
),
).not.toThrow()
expect(
screen.getByText('Everything is broken. Try again'),
).toBeInTheDocument()
console.error.mockClear()
})
test('should throw error if FallbackComponent is not valid', () => {
expect(() =>
render(
<ErrorBoundary FallbackComponent={{}}>
<Bomb />
</ErrorBoundary>,
),
).toThrowError(/Element type is invalid/i)
console.error.mockClear()
})