The Problem:
I am trying to use jest and React Testing Library to mock a functional component that is wrapped in React.ForwardRef(), but I keep getting this warning (which is failing my test):
Warning: Function components cannot be given refs. Attempts to access this ref will fail. Did you mean to use React.forwardRef()?
Here is the component I want to test:
const ParentComponent = () => {
const childRef = useRef(null);
return (
<div data-testid="parent">
Parent
{/* want to mock this ChildComponent */}
<ChildComponent ref={childRef} />
</div>
);
};
Here is the component I want to mock:
const ChildComponent = forwardRef((props, ref) => (
<div ref={ref} {...props}>
Child
</div>
));
What I've tried:
jest.mock("../ChildComponent", () => ({
__esModule: true,
default: () => <div>Mock Child</div>
}));
result: Warning: Function components cannot be given refs. Attempts to access this ref will fail. Did you mean to use React.forwardRef()?
jest.mock('../ChildComponent', () => {
const { forwardRef } = jest.requireActual('react');
return {
__esModule: true,
default: () => forwardRef((props, ref) => <div ref={ref} />),
};
});
result: Objects are not valid as a React child (found: object with keys {$$typeof, render})