Skip to content

Commit 9e0c6fd

Browse files
fatfiszgaearon
authored andcommitted
Call gDSFP with the right state in react-test-render (#13030)
* Call gDSFP with the right state in react-test-render * Change the test
1 parent 14a6c6c commit 9e0c6fd

File tree

2 files changed

+29
-2
lines changed

2 files changed

+29
-2
lines changed

src/ReactShallowRenderer.js

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -238,14 +238,14 @@ class ReactShallowRenderer {
238238
const {type} = this._element;
239239

240240
if (typeof type.getDerivedStateFromProps === 'function') {
241+
const oldState = this._newState || this._instance.state;
241242
const partialState = type.getDerivedStateFromProps.call(
242243
null,
243244
props,
244-
this._instance.state,
245+
oldState,
245246
);
246247

247248
if (partialState != null) {
248-
const oldState = this._newState || this._instance.state;
249249
const newState = Object.assign({}, oldState, partialState);
250250
this._instance.state = this._newState = newState;
251251
}

src/__tests__/ReactShallowRenderer-test.js

Lines changed: 27 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -915,6 +915,33 @@ describe('ReactShallowRenderer', () => {
915915
expect(result.props.children).toEqual(3);
916916
});
917917

918+
it('should not override state with stale values if prevState is spread within getDerivedStateFromProps', () => {
919+
class SimpleComponent extends React.Component {
920+
state = {value: 0};
921+
922+
static getDerivedStateFromProps(nextProps, prevState) {
923+
return {...prevState};
924+
}
925+
926+
updateState = () => {
927+
this.setState(state => ({value: state.value + 1}));
928+
};
929+
930+
render() {
931+
return <div>{`value:${this.state.value}`}</div>;
932+
}
933+
}
934+
935+
const shallowRenderer = createRenderer();
936+
let result = shallowRenderer.render(<SimpleComponent />);
937+
expect(result).toEqual(<div>value:0</div>);
938+
939+
let instance = shallowRenderer.getMountedInstance();
940+
instance.updateState();
941+
result = shallowRenderer.getRenderOutput();
942+
expect(result).toEqual(<div>value:1</div>);
943+
});
944+
918945
it('can setState with an updater function', () => {
919946
let instance;
920947

0 commit comments

Comments
 (0)