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

如何测试React的Loading组件是否渲染了LoadingBackground组件?

如何测试React组件是否渲染指定子组件?

你的Loading组件代码

const Loading: React.FunctionComponent = () => {
    return (
        <div className="w-screen h-screen overflow-hidden">
            <LoadingBackground />
        </div>
    );
};

你的测试疑问

你尝试了以下测试代码,但不确定是否正确:

import { render } from "@testing-library/react";
import Loading from "./Loading";
import LoadingBackground from "../../components/LoadingBackground";

test("Loading", () => {
        const parent = render(<Loading />);
        expect(parent).toContainElement(loadingBackground); <-- 此处是否能检测LoadingBackground是否渲染?
});

你原测试代码的问题

这段代码无法正确检测LoadingBackground是否渲染,原因有两点:

  1. render返回的parent是包含工具方法的对象,并非DOM元素,toContainElement断言需要作用于DOM节点。
  2. loadingBackground(你还写错了大小写,正确应为LoadingBackground)是组件定义,不是渲染后的DOM元素,不能直接传入toContainElement。

正确的测试方式

方式1:通过data-testid查询(推荐)

给LoadingBackground的根元素添加唯一的data-testid属性:

// LoadingBackground.tsx
const LoadingBackground = () => {
  return <div data-testid="loading-background">...</div>;
};

然后编写测试代码:

import { render, screen } from "@testing-library/react";
import Loading from "./Loading";

test("Loading组件应渲染LoadingBackground", () => {
  render(<Loading />);
  // 查询到对应测试ID的元素,说明子组件已渲染
  expect(screen.getByTestId("loading-background")).toBeInTheDocument();
});

方式2:模拟组件并检查调用次数

如果不需要关心子组件的DOM结构,只需要确认它被渲染,可以用Jest模拟组件:

import { render } from "@testing-library/react";
import Loading from "./Loading";
import LoadingBackground from "../../components/LoadingBackground";

// 模拟LoadingBackground组件
jest.mock("../../components/LoadingBackground", () => ({
  __esModule: true,
  default: jest.fn(() => <div />),
}));

test("Loading组件应渲染LoadingBackground", () => {
  render(<Loading />);
  // 检查组件是否被调用了一次(即被渲染)
  expect(LoadingBackground).toHaveBeenCalledTimes(1);
});

方式3:通过类名/角色查询(依赖DOM结构)

如果LoadingBackground有唯一的类名或ARIA角色,可以直接查询DOM:

import { render, screen } from "@testing-library/react";
import Loading from "./Loading";

test("Loading组件应渲染LoadingBackground", () => {
  render(<Loading />);
  // 假设LoadingBackground渲染了带有progressbar角色的元素
  expect(screen.getByRole("progressbar")).toBeInTheDocument();
  
  // 或者通过类名查询(不推荐,类名可能随样式修改)
  const container = render(<Loading />).container;
  expect(container.querySelector(".loading-background")).toBeInTheDocument();
});

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.01 05:00:32