【发布时间】:2020-01-24 17:12:28
【问题描述】:
所以我目前正在学习如何对我的组件进行单元测试,以及我所拥有的工作,但我觉得这不是“正确”的方法。
在我最近的两个测试中,我正在寻找第一个孩子的第一个孩子。这感觉有点脏,但我正在努力寻找更好的方法来实现这一点。
基本上我要做的是测试该场景中是否存在 svg - 如果不存在,则在下一个测试中,文本是否存在。
任何帮助都会很棒!
谢谢
我的组件输出:
<h1>
<svg...> <!--(if hasIcon prop is set to true)-->
My Header Text
</h1>
我目前的测试:
let wrapper;
beforeEach(() => {
wrapper = render(<MyComponent />);
});
describe("<MyComponent />", () => {
it("should render", () => {
const { container } = wrapper;
expect(container.firstChild);
});
it("should match snapshot", () => {
const { container } = wrapper;
expect(container.firstChild).toMatchSnapshot();
});
it("should render with an icon", () => {
const { container } = wrapper;
expect(container.firstChild.firstChild.nodeName).toBe("svg");
});
it("should render without an icon", () => {
const { container } = render(<AppHeader hasIcon={false} />);
expect(container.firstChild.firstChild.nodeName).toBe("#text");
});
});
【问题讨论】:
-
为什么不将 data-testid 属性附加到 svg 和文本父元素,然后只使用 queryByTestId 来断言该元素存在?
-
@Win 那会直接进入我的组件吗?在测试文件之外?
标签: reactjs unit-testing jestjs react-testing-library