|
| 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 | + * @jest-environment node |
| 9 | + */ |
| 10 | +'use strict'; |
| 11 | + |
| 12 | +let React; |
| 13 | +let ReactNoop; |
| 14 | +let Scheduler; |
| 15 | + |
| 16 | +describe('ReactFragment', () => { |
| 17 | + beforeEach(function() { |
| 18 | + jest.resetModules(); |
| 19 | + |
| 20 | + React = require('react'); |
| 21 | + ReactNoop = require('react-noop-renderer'); |
| 22 | + Scheduler = require('scheduler'); |
| 23 | + }); |
| 24 | + |
| 25 | + function componentStack(components) { |
| 26 | + return components |
| 27 | + .map(component => `\n in ${component} (at **)`) |
| 28 | + .join(''); |
| 29 | + } |
| 30 | + |
| 31 | + function normalizeCodeLocInfo(str) { |
| 32 | + return ( |
| 33 | + str && |
| 34 | + str.replace(/\n +(?:at|in) ([\S]+)[^\n]*/g, function(m, name) { |
| 35 | + return '\n in ' + name + ' (at **)'; |
| 36 | + }) |
| 37 | + ); |
| 38 | + } |
| 39 | + |
| 40 | + it('retains component stacks when rethrowing an error', () => { |
| 41 | + function Foo() { |
| 42 | + return ( |
| 43 | + <RethrowingBoundary> |
| 44 | + <Bar /> |
| 45 | + </RethrowingBoundary> |
| 46 | + ); |
| 47 | + } |
| 48 | + function Bar() { |
| 49 | + return <SomethingThatErrors />; |
| 50 | + } |
| 51 | + function SomethingThatErrors() { |
| 52 | + throw new Error('uh oh'); |
| 53 | + } |
| 54 | + |
| 55 | + class RethrowingBoundary extends React.Component { |
| 56 | + static getDerivedStateFromError(error) { |
| 57 | + throw error; |
| 58 | + } |
| 59 | + |
| 60 | + render() { |
| 61 | + return this.props.children; |
| 62 | + } |
| 63 | + } |
| 64 | + |
| 65 | + const errors = []; |
| 66 | + class CatchingBoundary extends React.Component { |
| 67 | + constructor() { |
| 68 | + super(); |
| 69 | + this.state = {}; |
| 70 | + } |
| 71 | + static getDerivedStateFromError(error) { |
| 72 | + return {errored: true}; |
| 73 | + } |
| 74 | + componentDidCatch(err, errInfo) { |
| 75 | + errors.push(err.message, normalizeCodeLocInfo(errInfo.componentStack)); |
| 76 | + } |
| 77 | + render() { |
| 78 | + if (this.state.errored) { |
| 79 | + return null; |
| 80 | + } |
| 81 | + return this.props.children; |
| 82 | + } |
| 83 | + } |
| 84 | + |
| 85 | + ReactNoop.render( |
| 86 | + <CatchingBoundary> |
| 87 | + <Foo /> |
| 88 | + </CatchingBoundary>, |
| 89 | + ); |
| 90 | + expect(Scheduler).toFlushWithoutYielding(); |
| 91 | + expect(errors).toEqual([ |
| 92 | + 'uh oh', |
| 93 | + componentStack([ |
| 94 | + 'SomethingThatErrors', |
| 95 | + 'Bar', |
| 96 | + 'RethrowingBoundary', |
| 97 | + 'Foo', |
| 98 | + 'CatchingBoundary', |
| 99 | + ]), |
| 100 | + ]); |
| 101 | + }); |
| 102 | +}); |
0 commit comments