Home > Software design >  How to select an input form that doesn't have a label with React testing library?
How to select an input form that doesn't have a label with React testing library?

Time:10-03

On this example, I'm trying to select the second input, change the value to some text and then fire the enter event. My main issue here is selecting the input since it doesn't have a label nor id

<ul>
  <form>
    <input value="" />
  </form>
  <form>
    <input value="" />
  </form>
</ul>

If anyone can help with I'd appreciate it.

CodePudding user response:

    const inputs = document.getElementsByTagName('input');
    console.log(inputs); // inputs[1] is second input 

Here is inputs

enter image description here

CodePudding user response:

I would suggest adding a name attribute to your input fields as it's something you want to do anyway, regardless of testing. This way the correct values are sent when submitting the form.

<ul>
  <form>
    <input value="" name="firstName" />
  </form>
  <form>
    <input value="" name="lastName" />
  </form>
</ul>

Test could be:

getByRole('textbox', {name: /lastName/i})

Side note: You have 2 form elements, if both inputs relate to the same form they should exist in the same form tag.

  • Related