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

React Testing Library测试报错:第二个测试无法找到[data-testid="descriptive-slogan"]元素

问题分析与解决方案

你遇到的问题根源在于组件渲染的时机不对。React Testing Library有个默认行为:每个test(或it)块执行完毕后,会自动清理DOM,确保测试之间不会互相干扰。

你把render(<Home />)写在了所有测试的外面,这意味着:

  • 第一个测试运行时,组件确实被渲染了,所以能找到main-slogan元素
  • 第一个测试结束后,Testing Library清空了DOM
  • 第二个测试运行时,没有重新渲染组件,自然找不到descriptive-slogan

修复方案

有两种简单的修复方式,选哪种都可以:

方案1:把render移到每个测试内部

修改你的测试代码,让每个测试都单独渲染组件:

import { render, screen } from "@testing-library/react";
import '@testing-library/jest-dom'
import Home from "../src/pages/index"

test("main slogan", () => {
  render(<Home />); // 移到当前测试内部
  const text = /^Create Beautiful Coversfor blogs like a pro😎/
  expect(screen.getByTestId('main-slogan')).toHaveTextContent(text);
})

test("descriptive slogan", () => {
  render(<Home />); // 每个测试都单独渲染组件
  const text = /^We at Cover Builders are aimed to provide you simple and easy tools, that helps you in generating blog covers easily/
  expect(screen.getByTestId("descriptive-slogan")).toHaveTextContent(text);
})

方案2:用beforeEach钩子统一渲染

如果有多个测试都需要渲染同一个组件,用beforeEach可以避免重复代码,让每个测试执行前都自动渲染一次组件:

import { render, screen } from "@testing-library/react";
import '@testing-library/jest-dom'
import Home from "../src/pages/index"

// 每个测试执行前都会触发这个钩子,渲染组件
beforeEach(() => {
  render(<Home />);
})

test("main slogan", () => {
  const text = /^Create Beautiful Coversfor blogs like a pro😎/
  expect(screen.getByTestId('main-slogan')).toHaveTextContent(text);
})

test("descriptive slogan", () => {
  const text = /^We at Cover Builders are aimed to provide you simple and easy tools, that helps you in generating blog covers easily/
  expect(screen.getByTestId("descriptive-slogan")).toHaveTextContent(text);
})

另外提个小细节:你第一个测试的正则表达式/^Create Beautiful Coversfor blogs like a pro😎/,和组件里的文本Create Beautiful Covers<br /> for blogs like a pro😎相比,Covers后面少了空格(组件里是换行加空格)。不过toHaveTextContent会忽略HTML标签和多余空白,这个不会导致测试失败,但如果要严格匹配的话,可以把正则改成/^Create Beautiful Covers\s+for blogs like a pro😎/。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.04.29 00:47:44