I am writing a Cypress test for a React project. I need to be able to target an <input>
nested inside of a <label>
so I can type into that input field. The <input>
s have no class ids.
Here is my HTML.
<label class="Input">
<div class="label">LABEL TEXT</div>
<input type="text">
</label>
I have numerous inputs in the same form with the exact HTML shown above. They only differ by the text in the <div>
(i.e. LABEL TEXT).
The reason that I am surrounding the <input>
in a label tag is that I want the user to be able to target the input by clicking anywhere surrounding the label text OR the input. Adding a class to the inputs doesn't make sense for our code-base just for the sake of Cypress testing. I cannot use pseudo selectors such as :first cy.get('input[type="text"]:first')
because I don't want my tests to break if I add additional inputs to the form.
I have tried the following, but it tries to type into the label instead of the input.
cy.contains('LABEL TEXT')
.click()
.type('test')
Even though it puts focus on the in the Cypress test runner, it still tries to type into the <div>
instead of the focused input.
As I am very new to Cypress and assertions, I am left scratching my head. I'm interested in a solution (if possible) that doesn't involve adding classes to my inputs just for the sake of Cypress testing. I'm hoping this is just a shortcoming in my CSS, Cypress, or assertion knowledge.
Thank you