【问题标题】:What is the name option in react-testing-library?react-testing-library 中的 name 选项是什么?
【发布时间】:2021-09-15 19:38:45
【问题描述】:

自从使用@testing-library 开始反应以来,我对name 属性感到困惑。可以获取渲染按钮 e 的引用。 G。像这样:

// <button>Button text</button>
screen.getbyRole("button", {name: /button text/gi})

在这种情况下,名称指的是按钮内部的textNode。关于输入的故事与name 可以参考的地方类似,例如id name 或文字内容。

我目前正在尝试获取这样呈现的按钮的引用:

<button
  aria-label="Close"
  class="css-1dliicy"
  type="button"
  >
  Create new
  <svg>...</svg>
</button>

查询时找不到按钮:

const createNewButton = screen.getByRole('button', {
    name: /Create new/gi,
});

我显然不知道 name 属性是什么意思,但我似乎找不到关于它的文档。

【问题讨论】:

    标签: reactjs react-testing-library


    【解决方案1】:

    name 属性是指您尝试查询的元素的可访问名称。

    来自ByRole query docs(第三段):

    您可以通过accessible name 查询返回的元素。这 可访问的名称适用于简单的情况,例如表格的标签 元素,或按钮的文本内容,或 aria-label 属性。它可用于查询特定元素,如果 渲染中存在多个具有相同角色的元素 内容。


    作为@Moistbobo referred to,由于您的按钮具有aria-label="Close",因此Close 将是其可访问的名称。

    【讨论】:

      【解决方案2】:

      这里的问题是第一个按钮没有 aria-label,默认情况下会回退到使用按钮内容来实现可访问性。

      由于第二个按钮将 Close 作为 aria-label,因此在这种情况下,name 属性应为 Close

      我编写了以下测试来证明这一点。

      import {render} from "@testing-library/react";
      
      describe('test', () => {
         it('find by name -> aria-label', () => {
             const {getByRole} = render(<button
                 aria-label="Close"
                 className="css-1dliicy"
                 type="button"
             >
                 Create new
             </button>)
      
             const button = getByRole('button', {name: 'Close'});
      
             expect(button).toBeTruthy();
         })
      
          it('find by name -> button content', () => {
              const {getByRole} = render(
                  <button>button text</button>
              );
      
              const button = getByRole("button", {name: /button text/gi});
      
              expect(button).toBeTruthy();
          })
      
          it('will throw an error', () => {
              const {getByRole} = render(
                  <button>button text</button>
              );
      
              /** will throw this error:
               * Unable to find an accessible element with the role "button" and name `/button texat/gi`
               *  Here are the accessible roles:
               *
               *  button:
               *
               *  Name "button text":
               */
              const button = getByRole("button", {name: /button texta/gi});
      
              expect(button).toBeTruthy();
          })
      });

      【讨论】:

        猜你喜欢
        • 2019-10-26
        • 2023-01-13
        • 2022-10-18
        • 2021-10-20
        • 2019-08-04
        • 2021-06-02
        • 2020-03-28
        • 1970-01-01
        • 2019-08-31
        相关资源
        最近更新 更多