Shallow renderer: support multiple `setState` invocation (#11167)
Filipp Riabchun committed
Oct 10, 2017 at 13:33 UTC
2264e3d04401fc15192a253baaf0ad923096f4b8
2 files changed
+50
-2
src/renderers/testing/ReactShallowRendererEntry.js
+4
-2
@@ -205,12 +205,14 @@ class Updater {
205
}
206
207
enqueueSetState(publicInstance, partialState, callback, callerName) {
208
+ const currentState = this._renderer._newState || publicInstance.state;
209
+
210
if (typeof partialState === 'function') {
209
- partialState = partialState(publicInstance.state, publicInstance.props);
211
+ partialState = partialState(currentState, publicInstance.props);
212
}
213
214
this._renderer._newState = {
213
- ...publicInstance.state,
215
+ ...currentState,
216
...partialState,
217
};
218
src/renderers/testing/__tests__/ReactShallowRenderer-test.js
+46
@@ -450,6 +450,52 @@ describe('ReactShallowRenderer', () => {
450
expect(result).toEqual(<div>doovy</div>);
451
});
452
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
+
499
it('can setState in componentWillReceiveProps when shallow rendering', () => {
500
class SimpleComponent extends React.Component {
501
state = {count: 0};