Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to select a specific element when returned multiple elements in React Testing Library?

So I am trying to select an element using their placeholder like this:

fireEvent.focus(screen.getByPlaceholderText('DD/MM/YYYY'));

And this is giving me an error saying it found multiple elements with the said placeholder. Here are the matching elements.:

<input
      class="StyledInput"
      hasvalue=""
      label="Date of birth"
      placeholder="DD/MM/YYYY"
      tabindex="0"
      value=""
      variant=""
    />

    <input
      class="StyledInput"
      hasvalue=""
      label="Expiry date"
      placeholder="DD/MM/YYYY"
      tabindex="0"
      value=""
      variant=""
    />

It’s returning me two elements but I only want to select the first one. How can I get that specific element?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

You should use the getAllByPlaceholderText method, otherwise, you will get an error:

TestingLibraryElementError: Found multiple elements with the placeholder text of: DD/MM/YYYY

The return value of const inputs = screen.getAllByPlaceholderText('DD/MM/YYYY') is an element list, you can get the first input element by array index – inputs[0]

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading