Skip to content

Commit 2264e3d

Browse files
Hypnosphigaearon
authored andcommitted
Shallow renderer: support multiple setState invocation (#11167)
1 parent 44c795c commit 2264e3d

File tree

2 files changed

+50
-2
lines changed

2 files changed

+50
-2
lines changed

src/renderers/testing/ReactShallowRendererEntry.js

Lines changed: 4 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -205,12 +205,14 @@ class Updater {
205205
}
206206

207207
enqueueSetState(publicInstance, partialState, callback, callerName) {
208+
const currentState = this._renderer._newState || publicInstance.state;
209+
208210
if (typeof partialState === 'function') {
209-
partialState = partialState(publicInstance.state, publicInstance.props);
211+
partialState = partialState(currentState, publicInstance.props);
210212
}
211213

212214
this._renderer._newState = {
213-
...publicInstance.state,
215+
...currentState,
214216
...partialState,
215217
};
216218

src/renderers/testing/__tests__/ReactShallowRenderer-test.js

Lines changed: 46 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -450,6 +450,52 @@ describe('ReactShallowRenderer', () => {
450450
expect(result).toEqual(<div>doovy</div>);
451451
});
452452

453+
it('can setState in componentWillMount repeatedly when shallow rendering', () => {
454+
class SimpleComponent extends React.Component {
455+
state = {
456+
separator: '-',
457+
};
458+
459+
componentWillMount() {
460+
this.setState({groovy: 'doovy'});
461+
this.setState({doovy: 'groovy'});
462+
}
463+
464+
render() {
465+
const {groovy, doovy, separator} = this.state;
466+
467+
return <div>{`${groovy}${separator}${doovy}`}</div>;
468+
}
469+
}
470+
471+
const shallowRenderer = createRenderer();
472+
const result = shallowRenderer.render(<SimpleComponent />);
473+
expect(result).toEqual(<div>doovy-groovy</div>);
474+
});
475+
476+
it('can setState in componentWillMount with an updater function repeatedly when shallow rendering', () => {
477+
class SimpleComponent extends React.Component {
478+
state = {
479+
separator: '-',
480+
};
481+
482+
componentWillMount() {
483+
this.setState(state => ({groovy: 'doovy'}));
484+
this.setState(state => ({doovy: state.groovy}));
485+
}
486+
487+
render() {
488+
const {groovy, doovy, separator} = this.state;
489+
490+
return <div>{`${groovy}${separator}${doovy}`}</div>;
491+
}
492+
}
493+
494+
const shallowRenderer = createRenderer();
495+
const result = shallowRenderer.render(<SimpleComponent />);
496+
expect(result).toEqual(<div>doovy-doovy</div>);
497+
});
498+
453499
it('can setState in componentWillReceiveProps when shallow rendering', () => {
454500
class SimpleComponent extends React.Component {
455501
state = {count: 0};

0 commit comments

Comments
 (0)