Choose an option from a Material UI Listbox with Autocomplete feature using Cypress

This specific element is crucial for the functionality of the application.

<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">

In this listbox called Category, there are multiple options available when the dropdown arrow is clicked. The numerical value following "mui-" can vary dynamically.

Several attempts have been made to interact with this element:

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

Another approach was:

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

A different strategy attempted was:

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

If anyone has insights on how to effectively select an option from this dynamic listbox, your guidance would be greatly appreciated.

Answer №1

Instead of overthinking the problem, utilize text within the component.

Certain libraries like React Material-UI can create complex HTML structures for styling and animation, making it challenging to extract the necessary components.

In the example source code below (extracted from an MUI demo page)

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

The generated structure looks like this (excluding styling classes)

<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 serves as the outer element – verifying its functionality can be done by examining the text within the elements.

cy.contains('.MuiAutocomplete-root', 'Movie')  
  .click()                                     

cy.contains('The Godfather').click()           

cy.contains('.MuiAutocomplete-root', 'Movie')  
  .find('input')                               
  .should('have.value', 'The Godfather')       

Enhanced Testing with data-cy Attribute

To simplify testing, consider adding 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" />}
/>

This adjustment streamlines the testing process.

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')

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Tips for adjusting the Tab Order in Material-UI Tabs

Can anyone help me with changing the tab index of the MUI Tabs? I want it so that when the Tab key is clicked, it selects the first tab first, then the second, and so on. ...

The MUI TextField doesn't register value changes when using the "ctrl + a" and "backspace/delete" keys

Need help with a coding problem? Check out this link: https://codesandbox.io/s/bold-hooks-ddce6c?file=/src/App.js Having trouble detecting changes in a textfield when using backspace or delete shortcuts? The issue arises when selecting all with ctrl + a ...

The use of Material-UI collapse animation in a table results in the insertion of div elements, triggering a validateDOMNesting warning

Having a data-filled table, I am looking to implement smooth transitions when adding or deleting an item. This is a ReactJS project utilizing Material-UI. The desired effect is similar to the one demonstrated in their example. While they use a List compon ...

Utilizing React in Express: A Step-by-Step Guide

I have a website built with expressjs/nodejs. I am looking to integrate a reactjs module into it. Currently, I have added a build of the reactjs app to 'client/build' within my expressjs application. The static declaration for 'client' ...

Deciphering the Cause of mapStateToPropsCall in Redux and React

When handling an unsuccessful http call resulting in an error message being displayed, I encounter subsequent state changes triggering multiple render calls. Is there a technique to identify the cause of these state changes and mapStateToProps calls? Alter ...

Managing array data in a custom component with react-hook-form

My current setup involves a form that utilizes react-hook-form's Controller type to pass the field and ref into a custom component designed to showcase an array of checkboxes. Each selected checkbox contributes to elements in an object array, represen ...

Create styles for each component based on their specific props when designing a customized Material-UI theme

I am having trouble styling the notchedOutline of a disabled <OutlinedInput /> in my custom MUI theme. My goal is to make the border color lighter than the default color when the input is disabled. Here is what I have attempted so far: const theme = ...

What methods are available to stop the hashing of className in NextJS?

Within our Nextjs application, our team utilizes Google Tag Manager and Optimizely. These tools rely on CSS selectors to target different sections of the page. Currently, we are implementing CSS Modules. However, with every code deployment, our class name ...

Accessing React.FC in Another File with TypeScript - A Step-by-Step Guide

code - const Exne: React.FC <IProps> = ({x}) => { console.log('input', x); const [getx, assignx] = useState(x); console.log(getx, assignx); return(getx) }; Could you please provide instructions on how to acc ...

Launching a new tab with a specific URL using React

I'm attempting to create a function that opens a new tab with the URL stored in item.url. The issue is, the item.url property is provided by the client, not by me. Therefore, I can't guarantee whether it begins with https:// or http://. For insta ...

The concept of asynchronous behavior in ReactJS using the useState hook

I am working on a page to display a list of products. I have included an input file button that allows users to select multiple images. After selecting the images, I use an API to upload them to the server and show the progress visually in the UI with the ...

Are the props for the "/" path not displaying correctly on the website?

Response: [HMR] Waiting for a signal to update from WDS... index.js:1 Warning: Functions cannot be used as a React child. This error may occur if you return a Component instead of from render. Or perhaps you intended to call this function rather than ret ...

Endless re-renders induced by React-Table

While experimenting with a component that includes a table, I decided to give the react-table package a shot. The large component below is triggering endless calls to getRowModel. Additionally, there is a useEffect present to track re-renders unrelated to ...

The post feature is not delivering the object as expected

I have created a Login page that is supposed to post Username and Password using Axios. I wrapped the username and password into an object as shown in the code below, but when I submit the form, I receive a "201" response. Everything seems to be working fi ...

Adjusting the height and paddingTop of the Dialog component in Material-UIredirectTo:

I am attempting to dynamically adjust the height of a dialog box in order to ensure all content is fully displayed within it. Additionally, I am looking to decrease the top padding of the modal to maximize available space.... Any suggestions on how I can ...

Receiving errors in React/TS/material-ui when attempting to use a variable as a value for a grid property. Messages include "No overload matches" and "Type 'number' is not assignable to type..."

tl;dr: When using a variable as the value of a grid xs property in JSX, material-ui throws a TS error. I'm working on implementing grids in material-ui with React/TypeScript. The goal is to make the width of a specific element dependent on the quant ...

What is causing my column's content to be lacking padding on the left side and having excessive padding on the right side?

Edit: Here's the link to the codepen https://codepen.io/maptik/pen/bGKMgpJ In my React project, I'm utilizing Bootstrap to display cards for each "Product". Here is a snippet of how I am rendering it: <div className="container bg-color- ...

Is it possible to use both MUI makeStyles and Theming in the _app.js file?

I've been working on a complex navigation component using MUI Persistent Drawers within a React + Next.js setup. To achieve the desired content shrinking effect based on state changes, I ended up placing the entire navigation system inside the _app.js ...

Using Material UI styles with passed props

Looking at the Card code from this link, I am trying to update the card style or any material UI style like this: const styles = theme => ({ card: { minWidth: 275, }, To something like this: const styles = theme => ({ card: { minWidth: 275, ...

React: trigger render once promise is resolved

Just wanted to mention, I am retrieving data from AWS DynamoDB. ... class Test extends Component { constructor(props) { super(props); this.state = { contactList: [] } } componentDidMount() { var getIte ...