Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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