如何在Jest测试中模拟作为Prop传入的MotionValue?
如何在Jest测试中模拟framer-motion的MotionValue并传入组件
你完全可以模拟MotionValue直接作为Prop传入,不需要依赖父组件。核心思路是不通过useMotionValue Hook创建实例,而是直接实例化framer-motion的MotionValue类——因为useMotionValue本质上只是React Hook封装,用于在组件内部管理MotionValue的生命周期,而直接实例化的MotionValue对象同样能满足组件Props的类型要求。
具体实现步骤
- 直接导入
MotionValue类(注意不是useMotionValueHook) - 在测试用例中实例化一个MotionValue对象,传入初始值
- 将实例化后的对象作为
currentIndexProp传入组件
示例代码如下:
import { MotionValue } from "framer-motion"; import { render, screen } from "@testing-library/react"; import Card from "./HeroCards"; it("renders a card", () => { const container = document.createElement("div"); // 直接实例化MotionValue,传入初始数值 const mockCurrentIndex = new MotionValue(0); render( <Card containerRef={{ current: container }} currentIndex={mockCurrentIndex} /> ); // 示例断言:检查卡片是否渲染(需根据组件实际结构调整选择器) expect(screen.getByTestId("card-element")).toBeInTheDocument(); });
额外说明
如果需要验证MotionValue变化时组件的行为,可以手动调用mockCurrentIndex.set(newValue)更新数值,再断言组件的响应,示例如下:
it("updates when currentIndex changes", () => { const container = document.createElement("div"); const mockCurrentIndex = new MotionValue(0); render( <Card containerRef={{ current: container }} currentIndex={mockCurrentIndex} /> ); // 更新MotionValue数值 mockCurrentIndex.set(1); // 断言组件的响应逻辑(需根据组件实际行为调整) expect(screen.getByText("Card 2")).toBeInTheDocument(); });
内容的提问来源于stack exchange,提问作者UWEM ISRAEL
相关产品推荐
相关产品推荐

