-
Notifications
You must be signed in to change notification settings - Fork 4
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
test(ErrorBoundary): add error rendering tests
- Loading branch information
1 parent
7136808
commit a2bdffe
Showing
1 changed file
with
47 additions
and
2 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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); | ||
}); | ||
}); |