Home > Software engineering >  How to select a specific element when returned multiple elements in React Testing Library?
How to select a specific element when returned multiple elements in React Testing Library?

Time:02-16

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
      
      hasvalue=""
      label="Date of birth"
      placeholder="DD/MM/YYYY"
      tabindex="0"
      value=""
      variant=""
    />

    <input
      
      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?

CodePudding user response:

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]

  • Related