Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it good practice to give html elements id attributes that are only to be used for testing purposes?

Suppose I have a form like so:

<form action="/foo" method="POST">
    <input type="text" name="username">
    <input type="text" name="password">
    <input type="submit" value="Login">
</form>

In my case, there is no need for me to give any of the input tags an "id" attribute. It isn't styled via CSS, there is no javascript referencing it, etc... However, there is a QA department that would love it if it had a hardcoded "id" such as "login-button" so that their automated test would stay stable.

CONS As the developer a am highly skeptical about adding id attributes that serve no functional purpose.

  • I think it clutters the code.
  • Confuses future developers looking at it.
  • Binds us to whatever testing tool is being used at the time.
  • Binds us to code outside of the product's codebase.
  • Starts down a slippery slope of the code knowing something about how it will be tested and vice-versa.

PROS: From the QA perspective, I can certainly sympathize that this would:

  • make their work easier.
  • provide stability (in the short term)

Can I get some help expanding on the Pros/Cons lists I have started here?

like image 593
Michael Peterson Avatar asked Nov 26 '12 23:11

Michael Peterson


1 Answers

One important functional reason to include id attributes on form inputs is so that you can explicitly associate the corresponding label elements with the inputs:

<form action="/foo" method="POST">
    <label for="username">User Name</label>
    <input type="text" id="username" name="username">
</form>

This is important for accessibility and usability. Screen reader users rely on this association so that they know what input they are typing into. There's also a huge usability difference when the labels are properly associated (user can click on the label to set the focus to the associated input). This is really apparent with checkbox and radio inputs.

Fiddle with example of both on checkboxes. (Note how much easier it is to click on the label rather than the input itself)

As for your opposition... I'm not sure how adding id attributes does any of the "cons" you state. Clutter? nope, valid usable code. Confusing? nope, id's and properly associated labels would be the first thing I'd add if I saw that code. Binds you to a test tool and outside code? how exactly? The fact that it would make your testing crew's life easier is just icing on the cake.

like image 125
steveax Avatar answered Oct 30 '22 08:10

steveax