【发布时间】:2019-10-09 02:13:49
【问题描述】:
我在这篇文章中在 React 中实现了一个“插槽”系统:Vue Slots in React。但是,由于 Enzyme 包装器的子代和 React 的子代之间“不匹配”,我在尝试测试组件时遇到了麻烦。
这是从 React children 获取“槽”子的函数。当使用 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 函数 always 返回 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);
});
任何帮助或见解将不胜感激!
【问题讨论】:
标签: javascript reactjs testing enzyme