在酶中,您可以检查子组件是否存在,如下所示:
expect(wrapper.find(ChildComponent)).toHaveLength(1)
React 测试库中的这个测试相当于什么?我找到的所有在线示例都只涵盖了寻找 dom 元素的非常简单的测试 - 没有一个包含渲染子组件的示例。如何找到子组件?
您不应该检查您的子组件是否呈现,因为它正在测试实现细节(测试库不鼓励您这样做)。
您可以检查子组件中的一些文本是否已渲染,或者您可以将 data-testid 提供给子组件中的包装元素,然后使用 @testing-library/jest-dom 中的 .toBeInTheDocument
expect(getByText(/some text/i)).toBeInTheDocument();
or
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>
);
}
Test:
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();
});
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)