如何在Karate中获取mat-select下拉框的mat-options选项
在Karate中获取下拉框所有选项并验证
在Karate里,你可以通过两种常用方式获取下拉框的所有选项,替代Selenium的getOptions()方法:
方法1:使用Karate定位器API
通过locateAll()定位所有<option>元素,再提取文本或属性值:
# 定位下拉框下的所有option元素(替换为你的下拉框定位器,比如id、name或XPath) * def allOptions = locateAll('#state option') # 提取所有选项的显示文本 * def stateOptionTexts = allOptions.map(option => option.text) # 如果需要提取选项的value属性值,用下面的代码 * def stateOptionValues = allOptions.map(option => option.value)
方法2:执行原生JavaScript脚本
通过script()方法运行JS直接获取选项:
# 获取所有选项的显示文本(自动去除首尾空格) * def stateOptionTexts = script('Array.from(document.querySelectorAll("#state option")).map(e => e.textContent.trim())') # 获取所有选项的value属性值 * def stateOptionValues = script('Array.from(document.querySelectorAll("#state option")).map(e => e.value)')
与印度州列表比对验证
定义预期的印度州列表,用Karate断言验证所有预期州都存在于下拉选项中:
# 定义完整的印度州/联邦属地列表 * def expectedIndianStates = [ "Andhra Pradesh", "Arunachal Pradesh", "Assam", "Bihar", "Chhattisgarh", "Goa", "Gujarat", "Haryana", "Himachal Pradesh", "Jharkhand", "Karnataka", "Kerala", "Madhya Pradesh", "Maharashtra", "Manipur", "Meghalaya", "Mizoram", "Nagaland", "Odisha", "Punjab", "Rajasthan", "Sikkim", "Tamil Nadu", "Telangana", "Tripura", "Uttar Pradesh", "Uttarakhand", "West Bengal", "Andaman and Nicobar Islands", "Chandigarh", "Dadra and Nagar Haveli and Daman and Diu", "Lakshadweep", "Delhi", "Puducherry", "Ladakh", "Jammu and Kashmir" ] # 验证所有预期州都存在于下拉选项中 * match stateOptionTexts includes all expectedIndianStates # 可选:验证下拉框没有额外的非印度州选项 * match stateOptionTexts is subset of expectedIndianStates
注意事项
- 替换代码中的
#state为你实际的下拉框定位器(比如select[name='state']或对应XPath) - 如果下拉框是动态加载的,需先等待元素加载完成:
* waitFor('#state').toBeVisible()
内容的提问来源于stack exchange,提问作者shilpa
相关产品推荐
相关产品推荐

