![](/img/trans.png)
[英]React Testing: Event handlers in React Shallow Rendering unit tests
[英]What is shallow rendering in Jest unit tests in React?
在这个视频(2分钟):
https://egghead.io/lessons/react-testing-intro-to-shallow-rendering
在1:40左右的标记处,叙述者说:“你可以看到,这个对象只是我们渲染输出的一个深度,这使得编写单元测试变得更加简单,因为我们只需要担心组件,而不是组件所呈现的环境。“
“一级深”是什么意思? 在CoolComponent示例的上下文中,两级深度渲染输出可能是什么样的?
当使用浅渲染时,Jest不会渲染子组件,而是按照定义返回它们 - ergo“一级深度渲染”。
一个例子:
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>
);
当检测<ButtonWithIcon icon="plus" label="Add Item" />
与默认渲染器,它将“扩大”的<Icon />
内部包含的<ButtonWithIcon />
<a class="btn btn-default"> <span class="glyphicon glyphicon-plus"></span> Add Thing </a>
当测试<ButtonWithIcon icon="plus" label="Add Item" />
与浅渲染器,也不会呈现<Icon />
内部包含的<ButtonWithIcon />
<a class="btn btn-default"> <Icon type="plus" /> Add Thing </a>
浅渲染的好处在于:如果要更改<Icon />
组件的HTML,那么父<ButtonWithIcon />
组件的测试仍然可以正常运行,因为它需要一个<Icon type="plus" />
子元素组件,而不是<span class="glyphicon glyphicon-plus"></span>
HTML。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.