Skip to content

Commit

Permalink
fix(rax): add lacked input argument of getDerivedStateFromError (fix #…
Browse files Browse the repository at this point in the history
…2211) (#2212)

* fix(rax): add lacked input argument of getDerivedStateFromError

#2211

* test(rax): add test for getDerivedStateFromError
first argument of getDerivedStateFromError should be the thrown error
  • Loading branch information
Clarence-pan authored Aug 20, 2021
1 parent adc7fe7 commit 4d0c3f4
Show file tree
Hide file tree
Showing 2 changed files with 41 additions and 1 deletion.
40 changes: 40 additions & 0 deletions packages/rax/src/vdom/__tests__/composite.js
Original file line number Diff line number Diff line change
Expand Up @@ -762,6 +762,46 @@ describe('CompositeComponent', function() {
expect(container.childNodes[0].childNodes[0].data).toBe('Something went wrong.');
});

it('should catch the exact error with getDerivedStateFromError.', () => {
let caughtError;
let exampleError = new Error('Example error message');
let container = createNodeElement('div');

class ErrorBoundary extends Component {
constructor(props) {
super(props);
this.state = { hasError: false, error: null };
}

static getDerivedStateFromError(error) {
caughtError = error;
return { hasError: true, error };
}

render() {
if (this.state.hasError) {
return <h1>{this.state.error.message}</h1>;
}

return this.props.children;
}
}

function BrokenRender(props) {
throw exampleError;
}

render(
<ErrorBoundary>
<BrokenRender />
</ErrorBoundary>, container);

jest.runAllTimers();

expect(caughtError).toBe(exampleError);
expect(container.childNodes[0].childNodes[0].data).toBe('Example error message');
});

it('should render correct when prevRenderedComponent did not generate nodes', () => {
let container = createNodeElement('div');
class Frag extends Component {
Expand Down
2 changes: 1 addition & 1 deletion packages/rax/src/vdom/performInSandbox.js
Original file line number Diff line number Diff line change
Expand Up @@ -39,7 +39,7 @@ export function handleError(instance, error) {

// Update state to the next render to show the fallback UI.
if (boundary.constructor && boundary.constructor.getDerivedStateFromError) {
const state = boundary.constructor.getDerivedStateFromError();
const state = boundary.constructor.getDerivedStateFromError(error);
boundary.setState(state);
}
}, boundaryInternal.__parentInstance);
Expand Down

0 comments on commit 4d0c3f4

Please sign in to comment.