From 7127e87846f87de4a2ee11e6a6273a4640b2fcd8 Mon Sep 17 00:00:00 2001 From: Toru Kobayashi Date: Tue, 8 May 2018 09:31:33 +0900 Subject: [PATCH] setState returning null and undefined is no-op on the ShallowRenderer (#12756) --- src/ReactShallowRenderer.js | 5 ++++ src/__tests__/ReactShallowRenderer-test.js | 28 ++++++++++++++++++++++ 2 files changed, 33 insertions(+) diff --git a/src/ReactShallowRenderer.js b/src/ReactShallowRenderer.js index 49be844..9cafeeb 100644 --- a/src/ReactShallowRenderer.js +++ b/src/ReactShallowRenderer.js @@ -301,6 +301,11 @@ class Updater { partialState = partialState(currentState, publicInstance.props); } + // Null and undefined are treated as no-ops. + if (partialState === null || partialState === undefined) { + return; + } + this._renderer._newState = { ...currentState, ...partialState, diff --git a/src/__tests__/ReactShallowRenderer-test.js b/src/__tests__/ReactShallowRenderer-test.js index 59ea0d9..b20f316 100644 --- a/src/__tests__/ReactShallowRenderer-test.js +++ b/src/__tests__/ReactShallowRenderer-test.js @@ -1305,4 +1305,32 @@ describe('ReactShallowRenderer', () => { 'UNSAFE_componentWillUpdate', ]); }); + + it('should stop the upade when setState returns null or undefined', () => { + const log = []; + let instance; + class Component extends React.Component { + constructor(props) { + super(props); + this.state = { + count: 0, + }; + } + render() { + log.push('render'); + instance = this; + return null; + } + } + const shallowRenderer = createRenderer(); + shallowRenderer.render(); + log.length = 0; + instance.setState(() => null); + instance.setState(() => undefined); + instance.setState(null); + instance.setState(undefined); + expect(log).toEqual([]); + instance.setState(state => ({count: state.count + 1})); + expect(log).toEqual(['render']); + }); });