简体   繁体   English

React中的Jest单元测试中的浅层渲染是什么?

[英]What is shallow rendering in Jest unit tests in React?

In this video (2 mins): 在这个视频(2分钟):

https://egghead.io/lessons/react-testing-intro-to-shallow-rendering https://egghead.io/lessons/react-testing-intro-to-shallow-rendering

at around the 1:40 mark, the narrator says "So as you can see, this object is only one level deep of our rendered output, and that makes writing unit tests a lot simpler because we only have to worry about the component, not the environment the component was rendered in." 在1:40左右的标记处,叙述者说:“你可以看到,这个对象只是我们渲染输出的一个深度,这使得编写单元测试变得更加简单,因为我们只需要担心组件,而不是组件所呈现的环境。“

What does he mean by "one level deep"? “一级深”是什么意思? In the context of the CoolComponent example, what might a two level deep rendered output look like? 在CoolComponent示例的上下文中,两级深度渲染输出可能是什么样的?

When shallow rendering is used, Jest will not render child components but return them as defined — ergo "one level deep rendering". 当使用浅渲染时,Jest不会渲染子组件,而是按照定义返回它们 - ergo“一级深度渲染”。

An example: 一个例子:

const Icon = (props) => {
    const className = 'glyphicon glyphicon-' + props.type;
    return (
        <span className={className} ariaHidden={true}></span>
    )
};

const ButtonWithIcon = (props) => (
    <a className="btn btn-default">
        <Icon type={props.icon} />
        {props.label}
    </a>
);
  • When testing <ButtonWithIcon icon="plus" label="Add Item" /> with the default renderer, it will “expand” the <Icon /> contained inside the <ButtonWithIcon /> : 当检测<ButtonWithIcon icon="plus" label="Add Item" />与默认渲染器,它将“扩大”的<Icon />内部包含的<ButtonWithIcon />

     <a class="btn btn-default"> <span class="glyphicon glyphicon-plus"></span> Add Thing </a> 
  • When testing <ButtonWithIcon icon="plus" label="Add Item" /> with the shallow renderer, it won't render the <Icon /> contained inside the <ButtonWithIcon /> : 当测试<ButtonWithIcon icon="plus" label="Add Item" />与浅渲染器,也不会呈现<Icon />内部包含的<ButtonWithIcon />

     <a class="btn btn-default"> <Icon type="plus" /> Add Thing </a> 

The benefit of shallow rendering lies here: should the HTML of the <Icon /> component ever be changed, the test for the parent <ButtonWithIcon /> component will still run fine as it expects an <Icon type="plus" /> child component, and not the <span class="glyphicon glyphicon-plus"></span> HTML. 浅渲染的好处在于:如果要更改<Icon />组件的HTML,那么父<ButtonWithIcon />组件的测试仍然可以正常运行,因为它需要一个<Icon type="plus" />子元素组件,而不是<span class="glyphicon glyphicon-plus"></span> HTML。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM