-
Notifications
You must be signed in to change notification settings - Fork 36
/
Copy pathErrorBoundary.test.tsx
71 lines (61 loc) · 2.11 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
import React from 'react';
import { render, screen } from '@testing-library/react';
import { ErrorBoundary } from './ErrorBoundary';
beforeEach(() => {
// When an error is thrown a bunch of console.errors are called even though
// the error boundary handles the error. This makes the test output noisy,
// so we'll mock out console.error
jest.spyOn(console, 'error').mockImplementation(() => {});
});
afterEach(() => {
jest.restoreAllMocks();
});
const goodBoyText = 'I am a good boy';
const badBoyText = 'I am a bad boy';
interface ChildProps {
shouldThrow?: boolean;
}
const Child = ({ shouldThrow }: ChildProps) => {
if (shouldThrow) {
throw new Error(badBoyText);
} else {
return <div>{goodBoyText}</div>;
}
};
describe('<ErrorBoundary />', () => {
test('renders its child when there is no error', () => {
render(
<ErrorBoundary>
<Child />
</ErrorBoundary>
);
expect(screen.queryByText(goodBoyText)).toBeInTheDocument();
expect(screen.queryByText(badBoyText)).not.toBeInTheDocument();
// By mocking out console.error we may inadvertently miss out on
// logs due to real errors. Let's reduce that likelihood by adding
// an assertion for how frequently console.error should be called.
expect(console.error).toHaveBeenCalledTimes(0);
});
test('renders the fallback UI when the child throws an error', () => {
render(
<ErrorBoundary>
<Child shouldThrow={true} />
</ErrorBoundary>
);
expect(screen.queryByText(goodBoyText)).not.toBeInTheDocument();
expect(screen.queryByText(badBoyText)).toBeInTheDocument();
expect(console.error).toHaveBeenCalledTimes(2);
});
test('logs the error when the child throws an error', () => {
const logError = jest.fn();
render(
<ErrorBoundary logError={logError}>
<Child shouldThrow={true} />
</ErrorBoundary>
);
expect(screen.queryByText(goodBoyText)).not.toBeInTheDocument();
expect(screen.queryByText(badBoyText)).toBeInTheDocument();
expect(console.error).toHaveBeenCalledTimes(2);
expect(logError).toHaveBeenCalledTimes(1);
});
});