Shallow renderer: pass component instance to setState updater as `this` (#12784)
* Shallow renderer: pass component instance to setState updater as `this` * Run prettier
Filipp Riabchun committed
May 11, 2018 at 20:03 UTC
4f459bb144cad7c12e49d8afa2449ff6d9ed9e1f
2 files changed
+26
-1
packages/react-test-renderer/src/ReactShallowRenderer.js
+5
-1
@@ -298,7 +298,11 @@ class Updater {
298
const currentState = this._renderer._newState || publicInstance.state;
299
300
if (typeof partialState === 'function') {
301
- partialState = partialState(currentState, publicInstance.props);
301
+ partialState = partialState.call(
302
+ publicInstance,
303
+ currentState,
304
+ publicInstance.props,
305
+ );
306
}
307
308
// Null and undefined are treated as no-ops.
packages/react-test-renderer/src/__tests__/ReactShallowRenderer-test.js
+21
@@ -945,6 +945,27 @@ describe('ReactShallowRenderer', () => {
945
expect(result.props.children).toEqual(2);
946
});
947
948
+ it('can access component instance from setState updater function', done => {
949
+ let instance;
950
+
951
+ class SimpleComponent extends React.Component {
952
+ state = {};
953
+
954
+ render() {
955
+ instance = this;
956
+ return null;
957
+ }
958
+ }
959
+
960
+ const shallowRenderer = createRenderer();
961
+ shallowRenderer.render(<SimpleComponent />);
962
+
963
+ instance.setState(function updater(state, props) {
964
+ expect(this).toBe(instance);
965
+ done();
966
+ });
967
+ });
968
+
969
it('can setState with a callback', () => {
970
let instance;
971