I'm trying to write a test that confirms that a <datalist/>
has a list of <option/>
elements using role-based queries from @testing-library/cypress
. Strangely, when I try to query by the option
role:
cy.findByRole('option')
...I get back no results:
Timed out retrying after 4000ms: Unable to find an accessible element with the role "option"
...despite the content appearing in the page:
<datalist id="subjects-list">
<option value="one">one</option>
<option value="two">two</option>
</datalist>
<input list="subjects-list" value=""/>
Is there a way to find these options with @testing-library/cypress
?
The key seems to be using hidden:true
option (from the message received in Cypress).
If you apply that option, the test finds both <option>
s but then complains that there are multiple results, so you then need to switch to the *All
version.
cy.findAllByRole('option', { hidden: true })
.eq(0)
.should('have.value', 'one')
That's the mechanics of it, the why of it is slightly more mysterious.
This is what the docs say about the hidden
option
If you set
hidden
totrue
elements that are normally excluded from the accessibility tree are considered for the query as well.
I think <datalist>
is by default hidden, for example here <datalist>
: The HTML Data List element the sample page does not show the options until you click into the <input>
.