Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Fix shallow renderer not allowing hooks in forwardRef render functions #15100

Merged
merged 2 commits into from Mar 15, 2019
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
18 changes: 10 additions & 8 deletions packages/react-test-renderer/src/ReactShallowRenderer.js
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
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);
});
});