[英]How to get an HTMLElement's aria attributes with vanilla JavaScript
My team uses carbon-components-react
which has a TextInput
component.我的团队使用具有TextInput
组件carbon-components-react
。 It renders the <input />
with aria-describedBy="<some_id>"
and, if the field is invalid, adds a <div id="<some_id>" />
.它使用aria-describedBy="<some_id>"
呈现<input />
,如果该字段无效,则添加<div id="<some_id>" />
。
I'm trying to write some React tests using @testing-library/react
to check the value of the div under different conditions.我正在尝试使用@testing-library/react
编写一些 React 测试来检查 div 在不同条件下的值。 I could hardcode the ID in my tests, but I hate to hardcode anything that might change in the future, especially by a 3rd party.我可以在测试中对 ID 进行硬编码,但我讨厌硬编码将来可能会改变的任何内容,尤其是由第 3 方更改。 I can't for the life of me figure out how to get the aria-describedBy
attribute of my input.我一生都无法弄清楚如何获取输入的aria-describedBy
属性。
test('has the right error message', () => {
const wrapper = render(<MyComponent />);
const input = wrapper.findByLabelText('My required field');
fireEvent.click(input);
fireEvent.blur(input);
const error = document.getElementById(input['aria-describedBy']); // input['aria-describedBy'] is undefined
expect(error.innerText).toBe('This field is required, scrub.');
});
As Stack Overflow often does, it provided a fantastic rubber duck, so I figured I'd finish the question and write up the answer.正如 Stack Overflow 经常做的那样,它提供了一个很棒的橡皮鸭,所以我想我会完成这个问题并写下答案。
Use input.getAttribute('aria-describedBy')
.使用input.getAttribute('aria-describedBy')
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.