Typescript+WinAppDriver自动化测试:下拉框函数类型匹配问题
解决方案
1. 修正自定义函数的参数与逻辑
你的selectDropdownItem函数参数类型完全错误,且内部逻辑存在两处问题:
- 参数应接收单个
WebElement(而非Promise包裹的数组) dropdown.click是属性引用,需改为调用方法dropdown.click()- 多余的
dropdown instanceof WebElement判断可移除,因为参数类型已明确为WebElement
修正后的函数:
/** * Standard function to handle selecting a dropdown item * * @param dropdown - The dropdown to expand * @param dropdownItem - The actual item from the open dropdown * */ async selectDropdownItem(dropdown: WebElement, dropdownItem: string) { // 点击下拉框展开选项 await dropdown.click(); // 定位并点击目标选项 await driver.findElement(By2.nativeName(dropdownItem)).click(); }
2. 修正元素获取与调用逻辑
dropDowns()是异步函数,直接用this.dropDowns[0]会拿到函数本身的无效索引值,必须先通过await获取WebElement数组,再通过索引提取单个元素:
修正后的调用代码:
// 先await拿到下拉框数组,再取第一个元素 const dropdownElements = await this.dropDowns(); await MainPage.selectDropdownItem(dropdownElements[0], 'Test Scenario 1');
3. (可选)简化元素定位器
如果不需要重复获取整个下拉框数组,可以直接封装获取单个下拉框的方法:
async getDropdownByIndex(index: number): Promise<WebElement> { const dropdowns = await this.driver.findElements(By2.nativeClassName('WindowsForms10.COMBOBOX.app.0.37504c8_r8_ad1')); return dropdowns[index]; }
调用时更简洁:
const targetDropdown = await this.getDropdownByIndex(0); await MainPage.selectDropdownItem(targetDropdown, 'Test Scenario 1');
错误根源总结
- 类型不匹配:你错误地将异步函数当作数组使用,且给函数参数定义了
Promise<WebElement[]>类型,实际需要的是单个WebElement - 异步处理错误:async函数必须通过
await才能拿到返回值,直接访问this.dropDowns[0]是无效操作 - 方法调用错误:
click是WebElement的方法,必须加括号调用click()
内容的提问来源于stack exchange,提问作者John Kelley
相关产品推荐
相关产品推荐

