E2E测试中如何点击同data-cy属性的指定顺序按钮?
解决方案
可以通过Cypress的.eq()方法实现按顺序点击指定位置的按钮,它能精准定位匹配元素集合中的第N个元素(索引从0开始)。
修改你的Cypress命令
更新现有命令,新增一个索引参数来指定要点击的按钮顺序:
When('I click on the {int}th button with data-cy:{string}', (position, element) => { // 因为.eq()索引从0开始,所以要将用户传入的位置减1 cy.get(`[data-cy="${element}"]`).eq(position - 1).click(); });
使用示例
- 点击第一个匹配的按钮:
When('I click on the 1th button with data-cy:"your-button-identifier"') - 点击第三个匹配的按钮:
When('I click on the 3th button with data-cy:"your-button-identifier"')
补充说明
如果你的测试场景中习惯用"1st"、"2nd"这类序数词,也可以调整命令的参数匹配逻辑:
When('I click on the {string} button with data-cy:{string}', (ordinal, element) => { // 提取序数词中的数字部分,比如"2nd"→2 const position = parseInt(ordinal); cy.get(`[data-cy="${element}"]`).eq(position - 1).click(); });
调用时即可写:When('I click on the 2nd button with data-cy:"your-button-identifier"')
内容的提问来源于stack exchange,提问作者Sebastian Lillo
相关产品推荐
相关产品推荐

