【发布时间】:2022-10-19 22:27:58
【问题描述】:
问题:
我正在尝试使用 jest 和 React 测试库来模拟包装在 React.ForwardRef() 中的功能组件,但我不断收到此警告(我的测试失败):
Warning: Function components cannot be given refs. Attempts to access this ref will fail. Did you mean to use React.forwardRef()?
这是我要测试的组件:
const ParentComponent = () => {
const childRef = useRef(null);
return (
<div data-testid="parent">
Parent
{/* want to mock this ChildComponent */}
<ChildComponent ref={childRef} />
</div>
);
};
这是我要模拟的组件:
const ChildComponent = forwardRef((props, ref) => (
<div ref={ref} {...props}>
Child
</div>
));
我试过的:
jest.mock("../ChildComponent", () => ({
__esModule: true,
default: () => <div>Mock Child</div>
}));
结果: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} />),
};
});
结果:Objects are not valid as a React child (found: object with keys {$$typeof, render})
【问题讨论】:
标签: reactjs jestjs react-testing-library