Skip to content

Commit

Permalink
Shallow renderer: support multiple setState invocation (#11167)
Browse files Browse the repository at this point in the history
  • Loading branch information
Hypnosphi authored and gaearon committed Oct 10, 2017
1 parent 44c795c commit 2264e3d
Show file tree
Hide file tree
Showing 2 changed files with 50 additions and 2 deletions.
6 changes: 4 additions & 2 deletions src/renderers/testing/ReactShallowRendererEntry.js
Original file line number Diff line number Diff line change
Expand Up @@ -205,12 +205,14 @@ class Updater {
}

enqueueSetState(publicInstance, partialState, callback, callerName) {
const currentState = this._renderer._newState || publicInstance.state;

if (typeof partialState === 'function') {
partialState = partialState(publicInstance.state, publicInstance.props);
partialState = partialState(currentState, publicInstance.props);
}

this._renderer._newState = {
...publicInstance.state,
...currentState,
...partialState,
};

Expand Down
46 changes: 46 additions & 0 deletions src/renderers/testing/__tests__/ReactShallowRenderer-test.js
Original file line number Diff line number Diff line change
Expand Up @@ -450,6 +450,52 @@ describe('ReactShallowRenderer', () => {
expect(result).toEqual(<div>doovy</div>);
});

it('can setState in componentWillMount repeatedly when shallow rendering', () => {
class SimpleComponent extends React.Component {
state = {
separator: '-',
};

componentWillMount() {
this.setState({groovy: 'doovy'});
this.setState({doovy: 'groovy'});
}

render() {
const {groovy, doovy, separator} = this.state;

return <div>{`${groovy}${separator}${doovy}`}</div>;
}
}

const shallowRenderer = createRenderer();
const result = shallowRenderer.render(<SimpleComponent />);
expect(result).toEqual(<div>doovy-groovy</div>);
});

it('can setState in componentWillMount with an updater function repeatedly when shallow rendering', () => {
class SimpleComponent extends React.Component {
state = {
separator: '-',
};

componentWillMount() {
this.setState(state => ({groovy: 'doovy'}));
this.setState(state => ({doovy: state.groovy}));
}

render() {
const {groovy, doovy, separator} = this.state;

return <div>{`${groovy}${separator}${doovy}`}</div>;
}
}

const shallowRenderer = createRenderer();
const result = shallowRenderer.render(<SimpleComponent />);
expect(result).toEqual(<div>doovy-doovy</div>);
});

it('can setState in componentWillReceiveProps when shallow rendering', () => {
class SimpleComponent extends React.Component {
state = {count: 0};
Expand Down

0 comments on commit 2264e3d

Please sign in to comment.