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

使用Jest和React Testing Library测试NextJS组件时文本未渲染问题

问题分析与修复方案

核心问题

你的testimonialMock是数组类型,但TestCard组件直接把data.data当作单个对象来读取card.text、card.name,导致这些属性值为undefined,所以渲染出来的只有空引号和横杠,测试自然找不到目标文本。

修复步骤

1. 修正Mock数据(推荐方案)

因为TestCard是单个卡片组件,应该接收单个对象而非数组。修改testimonialMock.js:

export const testimonialMock = {
  id: 0,
  imgUrl: "/img/mock.png",
  text: "test text",
  name: "test name",
};

2. 修正组件(如果需要保留数组Mock)

如果你确实需要传递数组给组件,需要在组件中取数组的第一个元素:

export default function TestCard(data) {
  // 取数组第一个元素作为卡片数据
  const card = data.data[0];

  return (
    // 原组件代码不变
  );
}

3. 修正测试中的查询逻辑

原测试里的screen.getByRole('p', {name: /test text/i})用法错误,应该直接用getByText或正确的查询方式:

it("renders the passed in data", () => {
  render(<TestCard data={testimonialMock} />);
  // 匹配包含test text的文本(注意组件里有引号包裹)
  expect(screen.getByText(/test text/i)).toBeInTheDocument();
  // 或者精确匹配带引号的文本
  expect(screen.getByText('"test text"')).toBeInTheDocument();
  // 验证名称
  expect(screen.getByText('-test name')).toBeInTheDocument();
});

4. 修复测试中的拼写错误

测试里的containter是拼写错误,应该改成container:

it("renders the component unchanged", () => {
  const { container } = render(<TestCard data={testimonialMock} />);
  expect(container).toMatchSnapshot();
});

验证修复

完成上述修改后,重新运行测试,应该能正常找到文本并通过所有测试。

内容的提问来源于stack exchange,提问作者RC80

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.09 15:15:42