javascript - 如何从 Enzyme 获取 React children

标签 javascript reactjs testing enzyme

我在 React 中实现了一个来自这篇文章的“插槽”系统:Vue Slots in React .但是,由于 Enzyme 包装器的子项和 React 的子项之间的“不匹配”,我在尝试测试该组件时遇到了麻烦。

这是从 React 获取“slot”子项的函数 children .当与 children 一起提供时,该函数在应用程序组件中按预期工作。 prop,但在测试期间不起作用,因为“子项”与 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;

这是我尝试编写的测试的基础。本质上,创建一个 super 基本组件树,然后检查组件的子组件是否包含预期的“插槽”组件。然而,getSlot函数总是 返回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);
});

如有任何帮助或见解,我们将不胜感激!

最佳答案

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

因此,以这种方式派生 child :

const children = wrapper.props().children;

CodeSandbox example .

关于javascript - 如何从 Enzyme 获取 React children,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58296160/

相关文章:

javascript - 如何衡量 React App 随时间推移的首次渲染性能?

javascript - Node.js 在接收 SIGTERM 时的默认行为是什么?

javascript - 为什么if语句在这个else if下面执行呢?

javascript - 为什么我在这个三元赋值中总是得到 null?

javascript - 屏幕没有更新

javascript - Angular Controller 测试 : check dependency injection is done right

php - 即使存在片段,assertJson 也会失败

javascript - JSFiddle环境,与backbone一起设置

javascript - Passport local 使用 Angular 返回错误 400 错误请求

javascript - 在状态中使用方法参数进行 react