You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Jest测试中模拟作为Prop传入的MotionValue?

如何在Jest测试中模拟framer-motion的MotionValue并传入组件

你完全可以模拟MotionValue直接作为Prop传入,不需要依赖父组件。核心思路是不通过useMotionValue Hook创建实例,而是直接实例化framer-motion的MotionValue类——因为useMotionValue本质上只是React Hook封装,用于在组件内部管理MotionValue的生命周期,而直接实例化的MotionValue对象同样能满足组件Props的类型要求。

具体实现步骤

  • 直接导入MotionValue类(注意不是useMotionValue Hook)
  • 在测试用例中实例化一个MotionValue对象,传入初始值
  • 将实例化后的对象作为currentIndex Prop传入组件

示例代码如下:

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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.19 16:10:31