-
-
Notifications
You must be signed in to change notification settings - Fork 1.7k
/
Copy patherrorboundary.test.tsx
349 lines (290 loc) · 10.8 KB
/
errorboundary.test.tsx
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
import { Scope } from '@sentry/browser';
import { fireEvent, render, screen } from '@testing-library/react';
import * as React from 'react';
import { useState } from 'react';
import {
ErrorBoundary,
ErrorBoundaryProps,
isAtLeastReact17,
UNKNOWN_COMPONENT,
withErrorBoundary,
} from '../src/errorboundary';
const mockCaptureException = jest.fn();
const mockShowReportDialog = jest.fn();
const EVENT_ID = 'test-id-123';
jest.mock('@sentry/browser', () => {
const actual = jest.requireActual('@sentry/browser');
return {
...actual,
captureException: (...args: unknown[]) => {
mockCaptureException(...args);
return EVENT_ID;
},
showReportDialog: (options: any) => {
mockShowReportDialog(options);
},
};
});
function Boo({ title }: { title: string }): JSX.Element {
throw new Error(title);
}
function Bam(): JSX.Element {
const [title] = useState('boom');
return <Boo title={title} />;
}
const TestApp: React.FC<ErrorBoundaryProps> = ({ children, ...props }) => {
const [isError, setError] = React.useState(false);
return (
<ErrorBoundary
{...props}
onReset={(...args) => {
setError(false);
if (props.onReset) {
props.onReset(...args);
}
}}
>
{isError ? <Bam /> : children}
<button
data-testid="errorBtn"
onClick={() => {
setError(true);
}}
/>
</ErrorBoundary>
);
};
describe('withErrorBoundary', () => {
it('sets displayName properly', () => {
const TestComponent = () => <h1>Hello World</h1>;
const Component = withErrorBoundary(TestComponent, { fallback: <h1>fallback</h1> });
expect(Component.displayName).toBe('errorBoundary(TestComponent)');
});
it('defaults to an unknown displayName', () => {
const Component = withErrorBoundary(() => <h1>Hello World</h1>, { fallback: <h1>fallback</h1> });
expect(Component.displayName).toBe(`errorBoundary(${UNKNOWN_COMPONENT})`);
});
});
describe('ErrorBoundary', () => {
jest.spyOn(console, 'error').mockImplementation();
afterEach(() => {
mockCaptureException.mockClear();
mockShowReportDialog.mockClear();
});
it('renders null if not given a valid `fallback` prop', () => {
const { container } = render(
// @ts-ignore Passing wrong type on purpose
<ErrorBoundary fallback="Not a ReactElement">
<Bam />
</ErrorBoundary>,
);
expect(container.innerHTML).toBe('');
});
it('renders null if not given a valid `fallback` prop function', () => {
const { container } = render(
// @ts-ignore Passing wrong type on purpose
<ErrorBoundary fallback={() => 'Not a ReactElement'}>
<Bam />
</ErrorBoundary>,
);
expect(container.innerHTML).toBe('');
});
it('renders a fallback on error', () => {
const { container } = render(
<ErrorBoundary fallback={<h1>Error Component</h1>}>
<Bam />
</ErrorBoundary>,
);
expect(container.innerHTML).toBe('<h1>Error Component</h1>');
});
it('calls `onMount` when mounted', () => {
const mockOnMount = jest.fn();
render(
<ErrorBoundary fallback={<h1>Error Component</h1>} onMount={mockOnMount}>
<h1>children</h1>
</ErrorBoundary>,
);
expect(mockOnMount).toHaveBeenCalledTimes(1);
});
it('calls `onUnmount` when unmounted', () => {
const mockOnUnmount = jest.fn();
const { unmount } = render(
<ErrorBoundary fallback={<h1>Error Component</h1>} onUnmount={mockOnUnmount}>
<h1>children</h1>
</ErrorBoundary>,
);
expect(mockOnUnmount).toHaveBeenCalledTimes(0);
unmount();
expect(mockOnUnmount).toHaveBeenCalledTimes(1);
expect(mockOnUnmount).toHaveBeenCalledWith(null, null, null);
});
it('renders children correctly when there is no error', () => {
const { container } = render(
<ErrorBoundary fallback={<h1>Error Component</h1>}>
<h1>children</h1>
</ErrorBoundary>,
);
expect(container.innerHTML).toBe('<h1>children</h1>');
});
it('supports rendering children as a function', () => {
const { container } = render(
<ErrorBoundary fallback={<h1>Error Component</h1>}>{() => <h1>children</h1>}</ErrorBoundary>,
);
expect(container.innerHTML).toBe('<h1>children</h1>');
});
describe('fallback', () => {
it('renders a fallback component', async () => {
const { container } = render(
<TestApp fallback={<p>You have hit an error</p>}>
<h1>children</h1>
</TestApp>,
);
expect(container.innerHTML).toContain('<h1>children</h1>');
const btn = screen.getByTestId('errorBtn');
fireEvent.click(btn);
expect(container.innerHTML).not.toContain('<h1>children</h1>');
expect(container.innerHTML).toBe('<p>You have hit an error</p>');
});
it('renders a render props component', async () => {
let errorString = '';
let compStack = '';
let eventIdString = '';
const { container } = render(
<TestApp
fallback={({ error, componentStack, eventId }) => {
if (error && componentStack && eventId) {
errorString = error.toString();
compStack = componentStack;
eventIdString = eventId;
}
return <div>Fallback here</div>;
}}
>
<h1>children</h1>
</TestApp>,
);
expect(container.innerHTML).toContain('<h1>children</h1>');
const btn = screen.getByTestId('errorBtn');
fireEvent.click(btn);
expect(container.innerHTML).not.toContain('<h1>children</h1');
expect(container.innerHTML).toBe('<div>Fallback here</div>');
expect(errorString).toBe('Error: boom');
/*
at Boo (/path/to/sentry-javascript/packages/react/test/errorboundary.test.tsx:23:20)
at Bam (/path/to/sentry-javascript/packages/react/test/errorboundary.test.tsx:40:11)
at ErrorBoundary (/path/to/sentry-javascript/packages/react/src/errorboundary.tsx:2026:39)
at TestApp (/path/to/sentry-javascript/packages/react/test/errorboundary.test.tsx:22:23)
*/
expect(compStack).toMatch(
/\s+(at Boo) \(.*?\)\s+(at Bam) \(.*?\)\s+(at ErrorBoundary) \(.*?\)\s+(at TestApp) \(.*?\)/g,
);
expect(eventIdString).toBe(EVENT_ID);
});
});
describe('error', () => {
it('calls `componentDidCatch() when an error occurs`', () => {
const mockOnError = jest.fn();
render(
<TestApp fallback={<p>You have hit an error</p>} onError={mockOnError}>
<h1>children</h1>
</TestApp>,
);
expect(mockOnError).toHaveBeenCalledTimes(0);
expect(mockCaptureException).toHaveBeenCalledTimes(0);
const btn = screen.getByTestId('errorBtn');
fireEvent.click(btn);
expect(mockOnError).toHaveBeenCalledTimes(1);
expect(mockOnError).toHaveBeenCalledWith(expect.any(Error), expect.any(String), expect.any(String));
expect(mockCaptureException).toHaveBeenCalledTimes(1);
expect(mockCaptureException).toHaveBeenLastCalledWith(expect.any(Error), {
contexts: { react: { componentStack: expect.any(String) } },
});
expect(mockOnError.mock.calls[0][0]).toEqual(mockCaptureException.mock.calls[0][0]);
// Check if error.cause -> react component stack
const error = mockCaptureException.mock.calls[0][0];
const cause = error.cause;
expect(cause.stack).toEqual(mockCaptureException.mock.calls[0][1].contexts.react.componentStack);
expect(cause.name).toContain('React ErrorBoundary');
expect(cause.message).toEqual(error.message);
});
it('calls `beforeCapture()` when an error occurs', () => {
const mockBeforeCapture = jest.fn();
const testBeforeCapture = (...args: any[]) => {
expect(mockCaptureException).toHaveBeenCalledTimes(0);
mockBeforeCapture(...args);
};
render(
<TestApp fallback={<p>You have hit an error</p>} beforeCapture={testBeforeCapture}>
<h1>children</h1>
</TestApp>,
);
expect(mockBeforeCapture).toHaveBeenCalledTimes(0);
expect(mockCaptureException).toHaveBeenCalledTimes(0);
const btn = screen.getByTestId('errorBtn');
fireEvent.click(btn);
expect(mockBeforeCapture).toHaveBeenCalledTimes(1);
expect(mockBeforeCapture).toHaveBeenLastCalledWith(expect.any(Scope), expect.any(Error), expect.any(String));
expect(mockCaptureException).toHaveBeenCalledTimes(1);
});
it('shows a Sentry Report Dialog with correct options', () => {
const options = { title: 'custom title' };
render(
<TestApp fallback={<p>You have hit an error</p>} showDialog dialogOptions={options}>
<h1>children</h1>
</TestApp>,
);
expect(mockShowReportDialog).toHaveBeenCalledTimes(0);
const btn = screen.getByTestId('errorBtn');
fireEvent.click(btn);
expect(mockShowReportDialog).toHaveBeenCalledTimes(1);
expect(mockShowReportDialog).toHaveBeenCalledWith({ ...options, eventId: EVENT_ID });
});
it('resets to initial state when reset', async () => {
const { container } = render(
<TestApp fallback={({ resetError }) => <button data-testid="reset" onClick={resetError} />}>
<h1>children</h1>
</TestApp>,
);
expect(container.innerHTML).toContain('<h1>children</h1>');
const btn = screen.getByTestId('errorBtn');
fireEvent.click(btn);
expect(container.innerHTML).toContain('<button data-testid="reset">');
const reset = screen.getByTestId('reset');
fireEvent.click(reset);
expect(container.innerHTML).toContain('<h1>children</h1>');
});
it('calls `onReset()` when reset', () => {
const mockOnReset = jest.fn();
render(
<TestApp
onReset={mockOnReset}
fallback={({ resetError }) => <button data-testid="reset" onClick={resetError} />}
>
<h1>children</h1>
</TestApp>,
);
expect(mockOnReset).toHaveBeenCalledTimes(0);
const btn = screen.getByTestId('errorBtn');
fireEvent.click(btn);
expect(mockOnReset).toHaveBeenCalledTimes(0);
const reset = screen.getByTestId('reset');
fireEvent.click(reset);
expect(mockOnReset).toHaveBeenCalledTimes(1);
expect(mockOnReset).toHaveBeenCalledWith(expect.any(Error), expect.any(String), expect.any(String));
});
});
});
describe('isAtLeastReact17', () => {
test.each([
['React 15 with no patch', '15.0', false],
['React 15 with no patch and no minor', '15.5', false],
['React 16', '16.0.4', false],
['React 17', '17.0.0', true],
['React 17 with no patch', '17.4', true],
['React 17 with no patch and no minor', '17', true],
['React 18', '18.1.0', true],
['React 19', '19.0.0', true],
])('%s', (_: string, input: string, output: ReturnType<typeof isAtLeastReact17>) => {
expect(isAtLeastReact17(input)).toBe(output);
});
});