Skip to content

Commit 3438825

Browse files
Hypnosphigaearon
authored andcommitted
Shallow renderer: pass component instance to setState updater as this (#12784)
* Shallow renderer: pass component instance to setState updater as `this` * Run prettier
1 parent 2013ad2 commit 3438825

File tree

2 files changed

+26
-1
lines changed

2 files changed

+26
-1
lines changed

src/ReactShallowRenderer.js

Lines changed: 5 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -298,7 +298,11 @@ class Updater {
298298
const currentState = this._renderer._newState || publicInstance.state;
299299

300300
if (typeof partialState === 'function') {
301-
partialState = partialState(currentState, publicInstance.props);
301+
partialState = partialState.call(
302+
publicInstance,
303+
currentState,
304+
publicInstance.props,
305+
);
302306
}
303307

304308
// Null and undefined are treated as no-ops.

src/__tests__/ReactShallowRenderer-test.js

Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -945,6 +945,27 @@ describe('ReactShallowRenderer', () => {
945945
expect(result.props.children).toEqual(2);
946946
});
947947

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+
948969
it('can setState with a callback', () => {
949970
let instance;
950971

0 commit comments

Comments
 (0)