Cypress select first item of Autocomplete Material UI

Viewed 4193

I have a react hook forms that contains Autocomplete material UI controls.

    <Controller
      as={
        <Autocomplete
          data-cy="profileCountry"
          options={countries}
          getOptionLabel={option => option.name}
          renderInput={params => (
            <TextField
              {...params}
              label="* Country"
              placeholder="Select a Country"

              InputLabelProps={{
                shrink: true
              }}
              variant="outlined"
            />
          )}
        />
      }
      rules={{ required: true }}
      onChange={([, data]) => data}
      defaultValue={{ id: 0, name: "" }}
      getOptionSelected={(option, value) => option.id === value.id}
      name="country"
      id="country"
      control={control}
    />

I want to run a cypress test case to fill up the form and submit. How can I select like the first option in this component using cypress.

Currently I just tried my luck like the following.

cy.get("[data-cy=profileCountry]").select("Germany");
3 Answers

I used this and it works:

 cy.get('.MuiAutocomplete-popper li[data-option-index="0"]').click();

Add a custom command:

Cypress.Commands.add('getDropdownOptions', () => {
  return cy.get('.MuiAutocomplete-popper [role="listbox"] [role="option"]', {
    timeout: 10000,
  });
});

Then you can simply...

cy.getDropdownOptions().contains('Germany').click();

Assuming we give an id to the autocomplete such as

              id="pool-leg-autoComplete"
              freeSolo
              options={legOptions.map((option) => option.title)}
              onChange={updateNewLegItemText}
              renderInput={(params: any) => (
                <TextField
                  {...params}
                  label="Add a leg to the pool"
                  margin="normal"
                  autoFocus
                  variant="outlined"
                  value={newLegItemText}                 
                />

cy.get('#pool-leg-autoComplete-option-0').click();

Where the index of the item is 0 in this case.

Related