Cypress测试:如何选择select元素中任意非禁用option选项
解决方案
要解决选择<select>中任意有效非禁用选项的问题,可以通过先定位所有可用选项,再提取其值或文本进行选择,具体代码修改如下:
cy.contains('button', /Add Another Child Record/i).click(); cy.get('[name=child_id_name][value=""]') // 定位刚添加的空字段行 .parents('tr') .within(tr => { cy.get('input[name=child_id_name]').type(randomAlpha()); cy.get('input[name=description]').type(randomAlpha()); // 处理select选择非禁用选项 cy.get('select[name=type]').then($select => { // 筛选出所有未被禁用的<option>元素 const validOptions = $select.find('option:not(:disabled)'); // 方案1:选择第一个有效选项 const firstValidOption = validOptions.first(); cy.wrap($select).select(firstValidOption.val()); // 方案2:随机选择一个有效选项(可选) // const randomIndex = Math.floor(Math.random() * validOptions.length); // const randomValidOption = validOptions.eq(randomIndex); // cy.wrap($select).select(randomValidOption.val()); }); });
原理说明
Cypress的select()方法确实需要明确的选项名称、值或索引,但我们可以借助jQuery的DOM操作能力:
- 通过
then()获取到<select>的DOM元素 - 用
find('option:not(:disabled)')筛选出所有非禁用的有效选项 - 提取目标选项的
value属性(也可以用text()获取文本内容,视页面实际情况选择) - 再用
cy.wrap($select).select()完成选择操作
内容的提问来源于stack exchange,提问作者Ron Newcomb
相关产品推荐
相关产品推荐

