From bcebbc579cc8b950f1f610ab81e4cac6d2ce663f Mon Sep 17 00:00:00 2001 From: "Sebastian \"Sebbie\" Silbermann" Date: Fri, 30 Aug 2024 19:31:23 +0200 Subject: [PATCH] add docs for thrown errors from render (#1416) Closes #1060 --- docs/react-testing-library/faq.mdx | 41 ++++++++++++++++++++++++++++++ 1 file changed, 41 insertions(+) diff --git a/docs/react-testing-library/faq.mdx b/docs/react-testing-library/faq.mdx index 1d93c926d..c2b02f934 100644 --- a/docs/react-testing-library/faq.mdx +++ b/docs/react-testing-library/faq.mdx @@ -98,6 +98,47 @@ As you write your tests, keep in mind:
+How do I test thrown errors in a Component or Hook? + +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()).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. + +::: + +
+ +
+ If I can't use shallow rendering, how do I mock out components in tests?