Skip to content

Commit

Permalink
Mock SCU if gDSFP defined in shallow renderer rerender
Browse files Browse the repository at this point in the history
  • Loading branch information
chenesan committed Feb 28, 2019
1 parent 6fda886 commit 9e2b05e
Showing 1 changed file with 22 additions and 0 deletions.
22 changes: 22 additions & 0 deletions packages/enzyme/src/ShallowWrapper.js
Expand Up @@ -243,6 +243,26 @@ function privateSetChildContext(adapter, wrapper, instance, renderedNode, getChi
}
}

function mockSCUIfgDSFPReturnNonNull(node, state) {
const { getDerivedStateFromProps } = node.type;
const { instance } = node;
if (typeof getDerivedStateFromProps === 'function') {
// we try to fix a React shallow renderer bug here.
// (facebook/react#14607, which has been fixed in react 16.8):
// when gDSFP return derived state, it will set instance state in shallow renderer before SCU,
// this will cause `this.state` in sCU be the updated state, which is wrong behavior.
// so we have to wrap sCU to pass the old state to original sCU.
const originalSCU = instance.shouldComponentUpdate;
instance.shouldComponentUpdate = (...args) => {
instance.state = state;
const sCUResult = originalSCU.apply(instance, args);
const nextState = args[1];
instance.state = nextState;
instance.shouldComponentUpdate = originalSCU;
return sCUResult;
};
}
}

/**
* @class ShallowWrapper
Expand Down Expand Up @@ -452,6 +472,7 @@ class ShallowWrapper {
&& instance
) {
if (typeof instance.shouldComponentUpdate === 'function') {
mockSCUIfgDSFPReturnNonNull(node, state);
shouldComponentUpdateSpy = spyMethod(instance, 'shouldComponentUpdate');
}
if (
Expand Down Expand Up @@ -601,6 +622,7 @@ class ShallowWrapper {
&& lifecycles.componentDidUpdate.onSetState
&& typeof instance.shouldComponentUpdate === 'function'
) {
mockSCUIfgDSFPReturnNonNull(node, state);
shouldComponentUpdateSpy = spyMethod(instance, 'shouldComponentUpdate');
}
if (
Expand Down

0 comments on commit 9e2b05e

Please sign in to comment.