Jest / React测试库-测试孩子的最好方法是什么?

时间:2019-09-24 14:31:51

标签: reactjs unit-testing jestjs react-testing-library

因此,我目前正在学习如何对组件进行单元测试以及我的工作原理,但是我不认为这是“正确”的方法。

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

基本上我要做的是测试该情况下是否存在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");
    });
});

1 个答案:

答案 0 :(得分:2)

根据我在上面的评论中的内容,以下是您可以采用的一种方法,因为您的主要关注点围绕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();
    });
});