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

Ghd*_*dfg 5 unit-testing reactjs jestjs enzyme

在这个视频(2分钟):

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

在1:40左右的标记处,叙述者说:"你可以看到,这个对象只是我们渲染输出的一个深度,这使得编写单元测试变得更加简单,因为我们只需要担心组件,而不是组件所呈现的环境."

"一级深"是什么意思?在CoolComponent示例的上下文中,两级深度渲染输出可能是什么样的?

Bra*_*mus 7

当使用浅渲染时,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>
);
Run Code Online (Sandbox Code Playgroud)
  • <ButtonWithIcon icon="plus" label="Add Item" />使用默认渲染器进行测试时,它将"扩展" <Icon />内部包含的内容<ButtonWithIcon />:

    <a class="btn btn-default">
        <span class="glyphicon glyphicon-plus"></span>
        Add Thing
    </a>
    
    Run Code Online (Sandbox Code Playgroud)
  • <ButtonWithIcon icon="plus" label="Add Item" />使用浅渲染器进行测试时,它不会渲染<Icon />包含在<ButtonWithIcon />:

    <a class="btn btn-default">
        <Icon type="plus" />
        Add Thing
    </a>
    
    Run Code Online (Sandbox Code Playgroud)

浅渲染的好处在于:如果<Icon />组件的HTML 发生变化,那么父<ButtonWithIcon />组件的测试仍然可以正常运行,因为它需要<Icon type="plus" />子组件,而不是<span class="glyphicon glyphicon-plus"></span>HTML.