| 1 | /** |
| 2 | * Copyright (c) Meta Platforms, Inc. and affiliates. |
| 3 | * |
| 4 | * This source code is licensed under the MIT license found in the |
| 5 | * LICENSE file in the root directory of this source tree. |
| 6 | * |
| 7 | * @emails react-core |
| 8 | */ |
| 9 | |
| 10 | 'use strict'; |
| 11 | |
| 12 | let React; |
| 13 | let ReactDOMClient; |
| 14 | let act; |
| 15 | |
| 16 | describe('ReactErrorBoundariesHooks', () => { |
| 17 | beforeEach(() => { |
| 18 | jest.resetModules(); |
| 19 | React = require('react'); |
| 20 | ReactDOMClient = require('react-dom/client'); |
| 21 | act = require('internal-test-utils').act; |
| 22 | }); |
| 23 | |
| 24 | it('should preserve hook order if errors are caught', async () => { |
| 25 | function ErrorThrower() { |
| 26 | React.useMemo(() => undefined, []); |
| 27 | throw new Error('expected'); |
| 28 | } |
| 29 | |
| 30 | function StatefulComponent() { |
| 31 | React.useState(null); |
| 32 | return ' | stateful'; |
| 33 | } |
| 34 | |
| 35 | class ErrorHandler extends React.Component { |
| 36 | state = {error: null}; |
| 37 | |
| 38 | componentDidCatch(error) { |
| 39 | return this.setState({error}); |
| 40 | } |
| 41 | |
| 42 | render() { |
| 43 | if (this.state.error !== null) { |
| 44 | return <p>Handled error: {this.state.error.message}</p>; |
| 45 | } |
| 46 | return this.props.children; |
| 47 | } |
| 48 | } |
| 49 | |
| 50 | function App(props) { |
| 51 | return ( |
| 52 | <React.Fragment> |
| 53 | <ErrorHandler> |
| 54 | <ErrorThrower /> |
| 55 | </ErrorHandler> |
| 56 | <StatefulComponent /> |
| 57 | </React.Fragment> |
| 58 | ); |
| 59 | } |
| 60 | |
| 61 | const container = document.createElement('div'); |
| 62 | const root = ReactDOMClient.createRoot(container); |
| 63 | await act(() => { |
| 64 | root.render(<App />); |
| 65 | }); |
| 66 | |
| 67 | await expect( |
| 68 | act(() => { |
| 69 | root.render(<App />); |
| 70 | }), |
| 71 | ).resolves.not.toThrow(); |
| 72 | }); |
| 73 | }); |