Skip to content

Commit

Permalink
Fix shallow renderer not allowing hooks in forwardRef render functions (
Browse files Browse the repository at this point in the history
#15100)

* test: Add test for shallow + forwardRef + hook

* fix(react-test-renderer): shallow forwardRef hooks
  • Loading branch information
eps1lon authored and gaearon committed Mar 15, 2019
1 parent f1ff434 commit 52c870c
Show file tree
Hide file tree
Showing 2 changed files with 28 additions and 8 deletions.
18 changes: 10 additions & 8 deletions packages/react-test-renderer/src/ReactShallowRenderer.js
Original file line number Diff line number Diff line change
Expand Up @@ -521,9 +521,7 @@ class ReactShallowRenderer {
if (this._instance) {
this._updateClassComponent(element, this._context);
} else {
if (isForwardRef(element)) {
this._rendered = element.type.render(element.props, element.ref);
} else if (shouldConstruct(element.type)) {
if (shouldConstruct(element.type)) {
this._instance = new element.type(
element.props,
this._context,
Expand Down Expand Up @@ -565,11 +563,15 @@ class ReactShallowRenderer {
ReactCurrentDispatcher.current = this._dispatcher;
this._prepareToUseHooks(element.type);
try {
this._rendered = element.type.call(
undefined,
element.props,
this._context,
);
if (isForwardRef(element)) {
this._rendered = element.type.render(element.props, element.ref);
} else {
this._rendered = element.type.call(
undefined,
element.props,
this._context,
);
}
} finally {
ReactCurrentDispatcher.current = prevDispatcher;
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -304,4 +304,22 @@ describe('ReactShallowRenderer with hooks', () => {
</div>,
);
});

it('should work with with forwardRef + any hook', () => {
const SomeComponent = React.forwardRef((props, ref) => {
const randomNumberRef = React.useRef({number: Math.random()});

return (
<div ref={ref}>
<p>The random number is: {randomNumberRef.current.number}</p>
</div>
);
});

const shallowRenderer = createRenderer();
let firstResult = shallowRenderer.render(<SomeComponent />);
let secondResult = shallowRenderer.render(<SomeComponent />);

expect(firstResult).toEqual(secondResult);
});
});

0 comments on commit 52c870c

Please sign in to comment.