[英]How to get React children from Enzyme
我在這篇文章中在 React 中實現了一個“插槽”系統:Vue Slots in React 。 但是,由於 Enzyme 包裝器的子代和 React 的子代之間“不匹配”,我在嘗試測試組件時遇到了麻煩。
這是 function 從 React children
獲得一個“插槽”孩子。 function 在提供children
道具時在應用程序組件中按預期工作,但在測試期間不起作用,因為“孩子”的格式與React.children
。
const getSlot = (children, slot) => {
if (!children) return null;
if (!Array.isArray(children)) {
return children.type === slot ? children : null;
}
// Find the applicable React component representing the target slot
return children.find((child) => child.type === slot);
};
TestComponent
不直接在測試中使用,但旨在展示如何在組件中實現“插槽”的示例。
const TestComponent = ({ children }) => {
const slot = getSlot(children, TestComponentSlot);
return (
<div id="parent">
<div id="permanentContent">Permanent Content</div>
{slot && <div id="optionalSlot">{slot}</div>}
</div>
);
};
const TestComponentSlot = () => null;
TestComponent.Slot = TestComponentSlot;
這是我正在嘗試編寫的測試的基礎。 本質上,創建一個超級基本組件樹,然后檢查組件的子組件是否包含預期的“插槽”組件。 但是, getSlot
function始終返回null
,因為輸入與在應用程序中使用時 React children
級提供的輸入不同。
it("Finds slots in React children", () => {
const wrapper = mount(
<div>
<TestComponent.Slot>Test</TestComponent.Slot>
</div>
);
// Unsure how to properly get the React children to test method.
// Below are some example that don't work...
// None of these approaches returns React children like function expects.
// Some return null and other return Enzyme wrappers.
const children = wrapper.children();
const { children } = wrapper.instance();
const children = wrapper.children().instance();
// TODO: Eventually get something I can put into function
const slot = getSlot(children, TestComponentSlot);
});
任何幫助或見解將不勝感激!
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.