DEV Community

SonicDev
SonicDev

Posted on • Edited on

2 ways of making your form inputs accessible

Recently, my team has been working on accessibility for testing. And we've had problems with getting our input elements to be following the principles of the testing-library

As per the priority in the docs, we should be using getByRole most often for the test to resemble how the user interacts with it in the browser. For example:

// get the textbox that has the label of 'Bar'
getByRole('textbox', { name: 'Bar' });
Enter fullscreen mode Exit fullscreen mode

So for us to use getByRole, we should make sure that the <input /> is related to the <label />.

There are 2 ways we can do this:

<label htmlFor="foo">Bar</label>
<input id="foo" type="text" />
Enter fullscreen mode Exit fullscreen mode

and

<label>Bar
  <input type="text" />
</label>
Enter fullscreen mode Exit fullscreen mode

This way, we can make sure that our form elements are accessible, not only by the user but also by our tests.

Cheers! ☕ 🍺

Reference: https://developer.mozilla.org/en-US/docs/Web/HTML/Element/label

Top comments (0)