reactjs React测试库中的名称选项是什么?

xytpbqjk  于 2022-12-18  发布在  React
关注(0)|答案(2)|浏览(98)

自从用@testing-library作为react的开始,我就被name属性弄糊涂了。它可以得到一个渲染按钮的引用,例如:

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

在这种情况下,name指的是按钮内部的textNode。输入的情况类似,name可以指idname或文本内容。
我正在尝试获取一个按钮的引用,该按钮呈现为如下所示:

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

并且查询时找不到该按钮:

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


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

yfjy0ee7

yfjy0ee71#

name属性引用您试图查询的元素的可访问名称。
来自ByRole查询文档(第三段):
您可以按元素的accessible name查询返回的元素。可访问名称适用于简单情况,例如,等于表单元素的标签、按钮的文本内容或aria-label属性的值。如果呈现的内容中存在多个具有相同角色的元素,则可使用该名称查询特定元素。
正如@Moistbobo所提到的,由于您的按钮有aria-label="Close",那么Close将是它的可访问名称。

de90aj5v

de90aj5v2#

这里的问题是第一个按钮没有一个aria-label,默认情况下将回退到使用按钮内容来实现可访问性。
由于第二个按钮的aria-label为Close,因此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();
    })
});

相关问题