簡體   English   中英

React中的Jest單元測試中的淺層渲染是什么?

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM