1

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.

6
  • Are you using React Testing Library? Can you post some sample test code you've tried so far? Commented Oct 2, 2021 at 21:07
  • Yes, I'm using the RTL. So, I've been able to fix this issue by first selecting the input like this userEvent.type(screen.getAllByRole('textbox')[0], 'some random comment') and then selecting the input again and firing the submit event fireEvent.submit(screen.getAllByRole('textbox')[0]) Please keep in mind that I'm not well versed into how to use the RTL, so I'm sure there might be a better way to achieve this. Commented Oct 3, 2021 at 0:03
  • From a user perspective, is there a reason you don't have some sort of label next to the input? Or a placeholder in the input? Commented Oct 3, 2021 at 9:31
  • I've added a possible answer for you using the name attribute. Commented Oct 3, 2021 at 9:44
  • 1
    Gotcha. I'd recommend dynamically adding a name or id while adding the Todo. Then use getByRole or getByTestId. I've added an answer for the name approach as I think it's better than id. Commented Oct 3, 2021 at 22:02

2 Answers 2

2

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.

Sign up to request clarification or add additional context in comments.

Comments

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

Here is inputs

enter image description here

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.