![](/img/trans.png)
[英]Testing a child component's conditional rendering in React Jest/Enzyme
[英]Jest and Enzyme conditional testing
我有一個 react 組件,其中的一部分有一個基於useState
鈎子呈現的條件代碼塊。
{show && (
<div className={styles.detailsModel}>
<div className={styles.modelContentBox}>
<span
className={styles.close}
onClick={() => {
setShow(false);
document.body.classList.remove(styles.noScroll);
}}
>
<CrossIcon />
</span>
</div>
</div>
)
}
現在覆蓋率顯示這個onClick
語句沒有被覆蓋。
在我的測試中,我查找close
類並模擬單擊,但它返回的Method “simulate” is meant to be run on 1 node. 0 found instead.
Method “simulate” is meant to be run on 1 node. 0 found instead.
這是有道理的,因為這個塊不在 DOM 中,直到狀態通過另一次單擊發生變化並且也不在snapshot
。
這是測試;
test('clicking close in modal', () => {
component.find('.close').simulate('click');
expect(onClick).toHaveBeenCalled();
});
所以我想我的問題是你應該如何在這種情況下進行測試?
通過在組件中添加一個 prop 來修復這個問題,如果組件傳遞了這個 prop,則更改useState
鈎
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.