自从使用@testing-library for react开始,我就被name属性搞糊涂了。可以获得所呈现的按钮的引用,例如:
// <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属性是什么意思,但是我似乎找不到关于它的文档。
发布于 2021-09-16 02:01:12
这里的问题是第一个按钮没有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();
})
});
发布于 2021-09-17 17:19:14
name属性引用您试图查询的元素的可访问名称。
来自ByRole query docs (第三段):
您可以通过元素的accessible name来查询返回的元素。可访问的名称用于简单的情况,例如,表单元素的标签、按钮的文本内容或
aria-label属性的值。如果呈现的内容中存在多个具有相同角色的元素,则可以使用它来查询特定元素。
作为@Moistbobo referred to,由于您的按钮具有aria-label="Close",因此Close将是其可访问名称。
https://stackoverflow.com/questions/69198906
复制相似问题