【问题标题】:How to get React children from Enzyme如何从 Enzyme 中获取 React 儿童
【发布时间】: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


    【解决方案1】:

    这里的问题是,当您使用酶的children() 方法时,它会返回ShallowWrapper[1]。为了将子组件作为 React 组件,您必须直接从 props 方法中获取它们。

    所以,以这种方式派生孩子:

    const children = wrapper.props().children;
    

    CodeSandbox example.

    【讨论】:

    • 我相信我也曾尝试过这一点,但如果您检查输出,您会注意到wrapper.children().instance() 的计算结果为null,这也是getSlot 函数的输出(因为通过的孩子是null)。所以这实际上并没有正确地得到孩子或测试功能:(。
    • @Kendall 知道了,我已经编辑了答案并修复了沙箱。
    • @teimurgan 这让我觉得很傻!谢谢!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-07-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-09-22
    相关资源
    最近更新 更多