gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-03 13:29:32 25 4
gpt4 key购买 nike

在此视频中(2 分钟):

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

在 1:40 左右,旁白说“正如您所看到的,该对象仅是我们渲染输出的一层深度,这使得编写单元测试变得更加简单,因为我们只需要担心组件,而不是组件渲染的环境。”

他所说的“一层深”是什么意思?在 CoolComponent 示例的上下文中,两级深度渲染输出可能是什么样子?

最佳答案

当使用浅层渲染时,Jest 将不会渲染子组件,而是按定义返回它们 - 因此“一级深度渲染”。

一个例子:

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。

关于reactjs - React 中 Jest 单元测试中的浅层渲染是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46881630/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com