Skip to content

Commit

Permalink
Call gDSFP with the right state in react-test-render (#13030)
Browse files Browse the repository at this point in the history
* Call gDSFP with the right state in react-test-render

* Change the test
  • Loading branch information
fatfisz authored and gaearon committed Jun 12, 2018
1 parent 3925301 commit 945fc1b
Show file tree
Hide file tree
Showing 2 changed files with 29 additions and 2 deletions.
4 changes: 2 additions & 2 deletions packages/react-test-renderer/src/ReactShallowRenderer.js
Original file line number Diff line number Diff line change
Expand Up @@ -238,14 +238,14 @@ class ReactShallowRenderer {
const {type} = this._element;

if (typeof type.getDerivedStateFromProps === 'function') {
const oldState = this._newState || this._instance.state;
const partialState = type.getDerivedStateFromProps.call(
null,
props,
this._instance.state,
oldState,
);

if (partialState != null) {
const oldState = this._newState || this._instance.state;
const newState = Object.assign({}, oldState, partialState);
this._instance.state = this._newState = newState;
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -915,6 +915,33 @@ describe('ReactShallowRenderer', () => {
expect(result.props.children).toEqual(3);
});

it('should not override state with stale values if prevState is spread within getDerivedStateFromProps', () => {
class SimpleComponent extends React.Component {
state = {value: 0};

static getDerivedStateFromProps(nextProps, prevState) {
return {...prevState};
}

updateState = () => {
this.setState(state => ({value: state.value + 1}));
};

render() {
return <div>{`value:${this.state.value}`}</div>;
}
}

const shallowRenderer = createRenderer();
let result = shallowRenderer.render(<SimpleComponent />);
expect(result).toEqual(<div>value:0</div>);

let instance = shallowRenderer.getMountedInstance();
instance.updateState();
result = shallowRenderer.getRenderOutput();
expect(result).toEqual(<div>value:1</div>);
});

it('can setState with an updater function', () => {
let instance;

Expand Down

0 comments on commit 945fc1b

Please sign in to comment.