首页 > 解决方案 > 如何测试函数在 react-testing-library 中返回 jsx?

问题描述

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

我必须要BeInstanceOf等,但很难找到有关“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;
  } ...

正如你所看到的,每个回报都是不同的 jsx。

标签: jestjsreact-testing-library

解决方案


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


推荐阅读