Skip to content

Commit

Permalink
test(ErrorBoundary): add error rendering tests
Browse files Browse the repository at this point in the history
  • Loading branch information
sabertazimi committed Aug 8, 2021
1 parent 7136808 commit a2bdffe
Showing 1 changed file with 47 additions and 2 deletions.
49 changes: 47 additions & 2 deletions src/components/ErrorBoundary/ErrorBoundary.test.tsx
Original file line number Diff line number Diff line change
@@ -1,14 +1,59 @@
import { render } from '@testing-library/react';
import React from 'react';
import { create } from 'react-test-renderer';
import ErrorBoundary from './ErrorBoundary';

const ComponentWithError = ({ shouldThrow }: { shouldThrow?: boolean }) => {
if (shouldThrow) {
console.error('ComponentWithError');
throw new Error('ComponentWithError');
} else {
return <div>App</div>;
}
};

describe('ErrorBoundary', () => {
test('should render correctly (snapshot)', () => {
const OLD_ENV = process.env;
let spy: jest.SpyInstance;

beforeEach(() => {
process.env = { ...OLD_ENV, NODE_ENV: 'development' };
spy = jest.spyOn(console, 'error').mockImplementation(() => {
return;
});
});

afterEach(() => {
process.env = OLD_ENV;
spy.mockRestore();
});

test('should render children correctly (snapshot)', () => {
const tree = create(
<ErrorBoundary>
<ComponentWithError />
</ErrorBoundary>
).toJSON();
expect(tree).toMatchSnapshot();
});

test('should render alert message correctly (snapshot)', () => {
const tree = create(
<ErrorBoundary>
<div>App</div>
<ComponentWithError shouldThrow />
</ErrorBoundary>
).toJSON();
expect(tree).toMatchSnapshot();
});

test('should render alert message when error happened', () => {
const { queryByRole, rerender } = render(<ComponentWithError />, {
wrapper: ErrorBoundary as React.ComponentType<unknown>,
});

expect(queryByRole('alert')).not.toBeInTheDocument();
rerender(<ComponentWithError shouldThrow />);
expect(queryByRole('alert')).toBeInTheDocument();
expect(console.error).toHaveBeenCalledTimes(4);
});
});

0 comments on commit a2bdffe

Please sign in to comment.