如何测试函数在 react-testing-library 中返回 jsx?

How to test a function is returning jsx in react-testing-library?

如何使用 jest/react-testing-library 测试某个组件是否 returning 特定的 JSX?

我必须toBeInstanceOf等,但是很难找到关于"react-testing-library"

的信息

这是几个例子

  const className = props.className;

  if (!props.action) {
    return props.children;
  }

  const { id, type, target } = props.action;
  if (type === "EXTERNAL") {
    return (
      <a className={className} href={target}>
        {props.children}
      </a>
    );
  }

  if (["page"].includes(type.toLowerCase())) {
    return (
      <Link className={className} key={id} to={"/" + target}>
        {props.children}
      </Link>
    );
  }

  if (type.toLowerCase() === "play") {
    return props.children;
  } ...

如您所见,每个 return 都是不同的 jsx。

理想情况下,您应该寻找面向用户的 DOM 元素,例如文本、标签等。但是,对于此类组件,您可能需要回退到使用测试 ID。您可以将 data-test-id="SomeComponent" 添加到要返回的各种元素,然后使用 getByTestId(或 queryByTestId 等)查找它。