-1

This is the element.

<input aria-invalid="false" autocomplete="off" placeholder="Category" type="text" class="MuiOutlinedInput-input MuiInputBase-input MuiInputBase-inputAdornedEnd MuiAutocomplete-input MuiAutocomplete-inputFocused MuiAutocomplete-input MuiAutocomplete-inputFocused css-16sx77j" aria-autocomplete="list" autocapitalize="none" spellcheck="false" value="" id="mui-621338585" aria-controls="mui-621338585-listbox" aria-activedescendant="mui-621338585-option-3"> 

This is a listbox with the name Category that contains various options when I click the dropdown arrow. The number after "mui-" is dynamic.

This is what I tried:

cy.get('[id^=”mui-"]').eq(2); 

Also tried:

cy.get('[id^=”mui-"]') .find('[aria-activedescendant*="-option-"]') .eq(2); 

And tried:

cy.get('[aria-activedescendant*="-option-2"]'); 

Could someone point me in the right direction to select an option from the listbox?

1 Answer 1

3

Don't over-think the problem, just use text in the component.

Libraries like React Material-UI generate quite complicated HTML to handle styling and animation and it's difficult to pick the right parts from that generated HTML.

Given source code like this (taken from MUI demo page)

<Autocomplete disablePortal id="combo-box-demo" options={top100Films} sx={{ width: 300 }} renderInput={(params) => <TextField {...params} label="Movie" />} /> 

You get a generated structure like this (leaving out classes used for styling)

<div class="MuiAutocomplete-root" data-cy="movie-autocomplete"> <div> <label for="combo-box-demo" id="combo-box-demo-label">Movie</label> <div> <input id="combo-box-demo" type="text" role="combobox" value=""> ... </div> </div> </div> 

The MUIAutocomplete-root is outer element - you can test it using the text in the elements.

cy.contains('.MuiAutocomplete-root', 'Movie') // identify Autocomplete component .click() // open it cy.contains('The Godfather').click() // choose an option cy.contains('.MuiAutocomplete-root', 'Movie') .find('input') .should('have.value', 'The Godfather') // verify the value in the input 

With data-cy attribute

If you add a data-cy attribute to the component,

<Autocomplete data-cy='movie-autocomplete' disablePortal id="combo-box-demo" options={top100Films} sx={{ width: 300 }} renderInput={(params) => <TextField {...params} label="Movie" />} /> 

The test becomes simpler

cy.get('[data-cy="movie-autocomplete"]').click() cy.contains('The Godfather').click() cy.get('[data-cy="movie-autocomplete"]') .find('input') .should('have.value', 'The Godfather') 
Sign up to request clarification or add additional context in comments.

1 Comment

thankyou Fody! It really did work, somehow I never thought or always had it in mind that it might recognize using the text in the elements or the label!!

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.