gpt4 book ai didi

reactjs - 如何测试子组件是否已呈现?

转载 作者:行者123 更新时间:2023-12-04 11:04:58 24 4
gpt4 key购买 nike

在 enzyme 中,您可以像这样检查子组件的存在:

expect(wrapper.find(ChildComponent)).toHaveLength(1)

react 测试库中的这个测试相当于什么?我发现的所有在线示例都只涵盖了寻找 dom 元素的非常简单的测试——没有一个包含渲染子组件的示例。你如何找到一个子组件?

最佳答案

你不应该检查你的子组件是否被渲染,因为它正在测试实现细节(哪个测试库不鼓励你这样做)。
您可以检查子组件中的一些文本是否已呈现,或者您可以将 data-testid 提供给子组件中的包装元素,然后使用来自 @testing-library/jest-dom 的 .toBeInTheDocument

expect(getByText(/some text/i)).toBeInTheDocument();
或者
expect(getByTestId('your-test-id')).toBeInTheDocument();
更新:示例
// Child Component
function ChildComponent() {
return <div>Child Element</div>;
};

// Parent
export default function Parent() {
return (
<div className="App">
<ChildComponent />
</div>
);
}
测试:
import { render } from "@testing-library/react";
import "@testing-library/jest-dom/extend-expect";
import Parent from "./App";

test("test child component", () => {
const { getByText } = render(<Parent />);
expect(getByText(/child element/i)).toBeInTheDocument();
});

关于reactjs - 如何测试子组件是否已呈现?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60041468/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com