I am trying to write a test in jest for a react component. In this component I use a ref
, which exposes the parent element inside the component.
In this way I can react on size changes of the parent in the component and do some magic.
const ChildComponent = ({parentRef}) => {
...variable declaration
// do something when there are changes in
useEffect(() => {
let parentOffSet = parentRef.current.offsetWidth
... do some more things
}, [parentRef])
... more content
}
This component is used in this way
import {useRef } from "react";
const ParentComponent = () => {
const currentRef = useRef(null);
return(
<div ref={currentRef
<ChildComponent />
</div>
);
}
Now I would like to test my ChildComponent in jest.
it('reders component'){
const testRef = {current: {offsetWidth: 600}};
render(<ChildComponent parentRef={testRef} />);
}
This test passes, but gives me a warning:
Warning: Function components cannot be given refs. Attempts to access this ref will fail. Did you mean to use React.forwardRef()?
I tried to modify my test e.g. via wrapping the <ChildComponent />
in another component in the test
const TestComponent = () => {
const testRef = useRef();
return(
<div ref={testRef}>
<ChildComponent parentRef={testRef} />
</div>
);
};
it('reders component'){
render(<TestComponent />);
}
But this gives the same warning.
I did a search for the last couple of days on how to resolve the warning method.
Most of the time the answers I found are on the subject of how to test a ref
within the component that is testet via a ‘mock’ here or here.
Or if a ref
has a certain state.
But I did not find any answer on how to solve my Problem.
The error message states that there might be a forwardRef involved. However, as far as I understand a forwardRef
this would be the other way arround: let the <ChildComponent>
be exposed to the <ParentComponent />
via a ref
.
Is there a workable way of testing such a component in jest and get rid of the warning?