Skip to content

Shallow renderer is not handling getDerivedStateFromProps properly #13027

@fatfisz

Description

@fatfisz

Do you want to request a feature or report a bug?

Bug

What is the current behavior?

After using enzyme's setState, getDerivedStateFromProps is called with an older version of state.

If the current behavior is a bug, please provide the steps to reproduce and if possible a minimal demo of the problem. Your bug will get fixed much faster if we can run your code and it doesn't have dependencies other than React. Paste the link to your JSFiddle (https://jsfiddle.net/Luktwrdm/) or CodeSandbox (https://codesandbox.io/s/new) example below:

import { shallow } from 'enzyme';

class Demo extends Component {
  static getDerivedStateFromProps(props, state) {
    return { value: state.value };
  };

  state = { value: 'old' };

  render() {
    return <div />;
  }
}

const wrapper = shallow(<Demo />);
wrapper.setState({ value: 'new' });
assert(wrapper.state().value === 'new'); // this throws

While I don't have a standalone demo, I tracked the problem to the _updateStateFromStaticLifecycle method of ReactShallowRenderer. Inside of it getDerivedStateFromProps is called with this._instance.state, but it should be called with this._newState. This might be related to the change in when getDerivedStateFromProps is being called.

What is the expected behavior?

assert(wrapper.state().value === 'new'); // this doesn't throw

Which versions of React, and which browser / OS are affected by this issue? Did this work in previous versions of React?

react-test-renderer@16.4.0
enzyme-adapter-react-16@1.1.1
enzyme@3.3.0

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions