getByText 找不到元素

getByText doesn't find the element

我想看看是否至少呈现了部分文本..

<li>
   Click here &nbsp;
   <a
     id="myLink"
     className="xxxxx"
     target="_blank"
     rel="noreferrer"
     href="https://www.aaa.com"
   >
      to open xxx.
   </a>
</li>

测试失败:

xxxxxx.getByText('Click here')

但如果 'Click here' 只是那个

  • 的文本,则工作正常 有没有办法进行部分搜索?

  • 如果您将字符串传递给 getByText(),它将查找确切的字符串。您可以改为传递正则表达式来查找部分匹配项:

    x.getByText(/click here/i)
    

    这里我使用 i 标志进行不区分大小写的搜索,但您也可以传递区分大小写的正则表达式:/Click here/.


    来自 About Queries > Using Queries:

    The primary argument to a query can be a string, regular expression, or function. There are also options to adjust how node text is parsed. See TextMatch for documentation on what can be passed to a query.

    来自 TextMatch > Precision:

    Queries that take a TextMatch also accept an object as the final argument that can contain options that affect the precision of string matching:

    • exact: Defaults to true; matches full strings, case-sensitive. When false, matches substrings and is not case-sensitive.
      • exact has no effect on regex or function arguments.
      • In most cases using a regex instead of a string gives you more control over fuzzy matching and should be preferred over { exact: false }.