测试 child 的 child 的最佳方法是什么?

What's the best way to test the child of a child?

所以我目前正在学习如何对我的组件进行单元测试,以及我的工作原理,但我觉得这不是 "right" 的方法。

在我最近的两次测试中,我正在寻找第一个 child 中的第一个 child。这感觉有点脏,但我正在努力寻找一种更好的方法来实现这一目标。

基本上我要做的是测试 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");
    });
});

根据我上面的评论,您可以采用以下方法,因为您主要关注的是 container.firstChild.firstChild.nodeName

const Text = () => <p data-testid="text">Some text</p>;
const SVG = () => <svg data-testid="svg>Some svg</svg>;

const MyComponent = ({ text = false, svg = false }) => (
    <div>
        {text && <Text/>}
        {svg && <SVG/>}
    </div>
);

describe("<MyComponent />", () => {
    it("should render", () => {
        const { container } = render(<MyComponent />);
        expect(container.firstChild).toBeTruthy();
    });

    it("should not render text or svg", () => {
        const { queryByTestId } = render(<MyComponent />);
        expect(queryByTestId('svg')).toBeFalsy();
        expect(queryByTestId('text')).toBeFalsy();
    });

    it("should render with a text element", () => {
        const { queryByTestId } = render(<MyComponent text={true} />);;
        expect(queryByTestId('text')).toBeTruthy();
    });

    it("should render with a svg element", () => {
        const { queryByTestId } = render(<MyComponent svg={true} />);
        expect(queryByTestId('svg')).toBeTruthy();
    });
});