reactjs 如果组件包含另一个组件,则React测试

mtb9vblg  于 2023-02-12  发布在  React
关注(0)|答案(1)|浏览(129)

我有加载页面:

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

如何测试LoadingBackground是否已渲染?

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); <-- Check if LoadingBackground is rendered or not?
});
0md85ypi

0md85ypi1#

你需要在LoadingBackground中添加一些可以用来标识它的东西,如果你没有任何唯一的文本,你可以把data-testid={'loadingBackground'}作为一个属性添加到你的元素中,并执行如下操作:

within(parent).getByTestId('loadingBackground')

相关问题