Skip to content

Commit

Permalink
[Shallow] Add tests for effects with inputs and cleanup (facebook#15275)
Browse files Browse the repository at this point in the history
  • Loading branch information
insidewhy committed Jul 25, 2019
1 parent a16136a commit c61ee64
Show file tree
Hide file tree
Showing 2 changed files with 76 additions and 12 deletions.
13 changes: 1 addition & 12 deletions packages/react-test-renderer/src/ReactShallowRenderer.js
Original file line number Diff line number Diff line change
Expand Up @@ -346,7 +346,7 @@ class ReactShallowRenderer {
cleanup: memoizedState.cleanup,
run:
inputs == null ||
shouldRunEffectsBasedOnInputs(memoizedState.inputs, inputs),
!areHookInputsEqual(inputs, memoizedState.inputs),
};
}
}
Expand Down Expand Up @@ -911,15 +911,4 @@ function getMaskedContext(contextTypes, unmaskedContext) {
return context;
}

function shouldRunEffectsBasedOnInputs(
before: Array<mixed> | void | null,
after: Array<mixed>,
) {
if (before == null || before.length !== after.length) {
return true;
}

return before.some((value, i) => after[i] !== value);
}

export default ReactShallowRenderer;
Original file line number Diff line number Diff line change
Expand Up @@ -280,6 +280,81 @@ describe('ReactShallowRenderer with hooks', () => {
'call effect',
]);
});

it('should trigger effects and cleanup depending on inputs', () => {
let _setFriend;
const happenings = [];

function SomeComponent() {
const [friend, setFriend] = React.useState('Bons');
const [cat] = React.useState('Muskus');
_setFriend = setFriend;

React.useEffect(
() => {
happenings.push('call friend effect');
return () => {
happenings.push('cleanup friend effect');
};
},
[friend],
);

React.useEffect(() => {
happenings.push('call empty effect');
return () => {
happenings.push('cleanup empty effect');
};
});

React.useEffect(
() => {
happenings.push('call cat effect');
return () => {
happenings.push('cleanup cat effect');
};
},
[cat],
);

React.useEffect(
() => {
happenings.push('call both effect');
return () => {
happenings.push('cleanup both effect');
};
},
[friend, cat],
);

return (
<div>
Hello {friend} with {cat}
</div>
);
}

const shallowRenderer = createRenderer({callEffects: true});
shallowRenderer.render(<SomeComponent />);

expect(happenings).toEqual([
'call friend effect',
'call empty effect',
'call cat effect',
'call both effect',
]);

happenings.splice(0);
_setFriend('Maryam');
expect(happenings).toEqual([
'cleanup friend effect',
'call friend effect',
'cleanup empty effect',
'call empty effect',
'cleanup both effect',
'call both effect',
]);
});
});

it('should work with useRef', () => {
Expand Down

0 comments on commit c61ee64

Please sign in to comment.