Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Call gDSFP with the right state in react-test-render #13030

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.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
4 changes: 2 additions & 2 deletions packages/react-test-renderer/src/ReactShallowRenderer.js
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
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