我正在尝试使用 Cypress 编写 React 组件的集成测试。我可以登录并打开一个表单对话框。但是我无法选择一个选项,如下所示。总的来说,这个测试我已经运行了好几次了,只有两三次通过,但99%的时间都失败了。
这是对话框:
<Grid item xs={12}>
<FormikFormControlSelect
formik={formik}
label="Insurers"
id="insurers"
variant="outlined"
fullWidth
multiple
disabled={promiseInProgress}
>
{memberships.insurers?.map((membership, index) => (
<MenuItem
key={index}
value={formatCordaX500Name(membership.identity)}
>
{formatCordaX500Name(membership.identity)}
</MenuItem>
))}
</FormikFormControlSelect>
</Grid>
这是我的测试代码:
describe('MachineDialog', () => {
it('should add a new machine successfully', () => {
// Login
cy.visit('https://xx.xx.test.xxxxxx.com/machines');
cy.get('input#username').type('xxx');
cy.get('input#password').type('xxxxxxxx');
cy.get('input#kc-login').click();
// Go to machines page and open New Machine btn
cy.get('[data-cy="new-machine-btn"]').click({ force: true });
cy.get('#insurers-select', { timeout: 1000 })
.parent()
.click({ force: true })
.get('ul > li[data-value="RuV (Wiesbaden, DE)"]', { timeout: 5000 })
.click({ force: true });
错误:
timed out retrying after 4000ms: expected to find element ul > li[data-value="RuV (Wiesbaden, DE)"], but never found it
这是结果。请注意,图中的选项已被选中,但实际上我没有,我只是手动选择了它。
总的来说,问题似乎是您在单击打开下拉菜单后没有等待页面响应。
Cypress 告诉我们最佳实践是
.click()
我不能确切地说,因为需要更多细节。
对测试代码的一些改进:
cy.get('#insurers-select', {timeout:5000) // increase not don't reduce timeout
.parent()
.should('be.visible')
.as('insurers-select') // alias the parent for further queries
.click() // don't force click
cy.get('@insurers-select')
.find('li')
.should('have.length.gt', 0) // make sure the options are loaded
cy.get('ul > li[data-value="RuV (Wiesbaden, DE)"]', {timeout:5000})
.should('be.visible')
.click()
显然这可能无法解决您的问题,但您应该修改您的问题以提供足够的细节。