【问题标题】:What's the best way to test the child of a child?测试孩子的孩子的最佳方法是什么?
【发布时间】: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


【解决方案1】:

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

【讨论】:

  • 这太棒了!非常感谢!!
  • @Nick 太棒了!如果您也想设置端到端测试,这也很有用,因为您很可能会将测试 ID 附加到要与之交互的元素:)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2018-08-19
  • 1970-01-01
  • 2017-07-19
  • 1970-01-01
  • 1970-01-01
  • 2021-07-24
  • 1970-01-01
相关资源
最近更新 更多