Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add docs for thrown errors from render #1416

Merged
merged 1 commit into from
Aug 30, 2024
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
41 changes: 41 additions & 0 deletions docs/react-testing-library/faq.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -98,6 +98,47 @@ As you write your tests, keep in mind:

<details>

<summary>How do I test thrown errors in a Component or Hook?</summary>

If a component throws during render, the origin of the state update will throw if wrapped in `act`.
By default, `render` and `fireEvent` are wrapped in `act`.
You can just wrap it in a try-catch or use dedicated matchers if your test runner supports these.
For example, in Jest you can use `toThrow`:

```jsx
function Thrower() {
throw new Error('I throw')
}

test('it throws', () => {
expect(() => render(<Thrower />)).toThrow('I throw')
})
```

The same applies to Hooks and `renderHook`:

```jsx
function useThrower() {
throw new Error('I throw')
}

test('it throws', () => {
expect(() => renderHook(useThrower)).toThrow('I throw')
})
```

:::info

React 18 will call `console.error` with an extended error message.
React 19 will call `console.warn` with an extended error message unless the state update is wrapped in `act`.
`render`, `renderHook` and `fireEvent` are wrapped in `act` by default.

:::

</details>

<details>

<summary>
If I can't use shallow rendering, how do I mock out components in tests?
</summary>
Expand Down