WebdriverIO异步模式下按索引点击元素失效如何解决
错误原因
异步模式下$$选择器返回的是Promise<WebdriverIO.ElementArray>类型,而非同步模式下直接的元素数组。你的原错误写法的执行逻辑是先访问Promise对象的[index]属性,Promise对象本身不存在数字索引属性,因此拿到的是undefined,后续调用waitForExist、click方法自然会抛出错误,TS的类型告警也对应这个逻辑。
正确实现
async clickOnExpandButtonByIndex(index: number) { // 先等待整个元素列表的Promise resolve,得到真实的元素数组 const expandButtons = await this.expandButtons // 可选:添加索引合法性校验,避免越界报错,同时消除TS类型告警 if (index < 0 || index >= expandButtons.length) { throw new Error(`索引${index}不合法,当前共匹配到${expandButtons.length}个展开按钮`) } const expandButton = expandButtons[index] await expandButton.waitForExist() await expandButton.click() }
补充说明
如果你确定传入的索引一定合法,也可以省略校验步骤,直接用非空断言expandButtons[index]!消除TS告警,但更推荐加校验的写法,方便排查越界类的问题。
内容的提问来源于stack exchange,提问作者Bartosz Dybczak
相关产品推荐
相关产品推荐

