Cypress选择Autocomplete Material UI的第一个项目

7
我有一个React Hook表单包含自动完成的Material UI控件。
    <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}
    />

我希望运行一个cypress测试用例来填写表单并提交。如何使用cypress选择这个组件中的第一个选项。
目前我只是尝试了以下方法。
cy.get("[data-cy=profileCountry]").select("Germany");

1
可以创建一个 CodeSandbox,这样更容易进行复现吗? - Joshua
6个回答

11

我使用了这个方法,它可以正常工作:

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

2
这对我也起作用了。为了选择列表中想要的选项,无论它们在原来的位置上是什么,我使用了这段代码:cy.get("#state").type("Roma").get('li[data-option-index="0"]').click();...其中 <Autocomplete id="state" ... />. - Jouni Kananen

5

添加自定义命令:

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

那么您只需简单地...

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

0
首先点击自动完成以弹出选项。
cy.get('[data-testing=\'currency-picker\']').click();

然后找到您想选择的具体选项,然后点击它。
cy.contains('Indian Rupee').click();

就像人类一样。有什么让人困惑的呢?

-1
你需要以下内容:
cy.wait(2000) // waiting for ajax to complete (till the request is resolved)
cy.get('#The MUI ID').click({force:true}).focused().type('Germany');
cy.contains('Germany').click({force:true});

-1
  cy.get("#combo-box").click();
        cy.get("li[data-option-index="0"]").contains("ntest_user").then((option)=> 
         {
            option[0].click();
        })

1
在这段代码中完全没有理由使用.then()回调函数。 - Morland

-2
假设我们给自动完成一个ID,例如:
              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();

在这种情况下,该项的索引为0。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接