【问题标题】:Selenium with async/await in JS, find and click on elementSelenium 在 JS 中使用 async/await,找到并单击元素
【发布时间】:2017-09-14 05:35:54
【问题描述】:

我正在尝试使用 Selenium webdriver 和 Mocha 将我的测试重构为具有异步/等待功能的 ES7。我有以下代码:

await loginPage.loginAsAdmin()

/* THIS DOES NOT WORK */
//await layout.Elements.routePageButton().click()

/* THIS DOES WORK */
let a = await layout.Elements.routePageButton()
await a.click()

我不明白为什么这个特别不起作用 - 我明白了:

TypeError: layout.Elements.routePageButton(...).click is not a function

click方法返回webElement之前的函数,可以看到:

布局:

routePageButton:  async () => await findVisibleElement('#route_info a')
const findVisibleElement = utils.Methods.Element.findVisible

方法:

findVisible: async (cssSelector) => {
  let elm = await driver().findElement(by.css(cssSelector))
  return elm
}

【问题讨论】:

  • async/await 是 ES2017 的一部分,不是 ES2016 (ES7)。

标签: javascript selenium-webdriver ecmascript-2017


【解决方案1】:

这里的问题是误解 await 是 ES2017 中的语言关键字,它允许您阻止调用 async 函数的执行,直到被调用函数返回的 Promise 解决。

routePageButton() 返回一个Promise,这就是上面第二个语法有效的原因,因为在Promise 解析为WebElement 对象之前,执行被阻塞。

但是,在您在第一个示例中使用的语法中,它试图 await on (click()) 的函数永远不会被调用,因为 Promise 没有 click() 函数。请注意,第二个语法中有两个 awaits,但第一个语法中只有一个。

要在一行中执行您尝试执行的操作,您必须执行以下操作:

await (await layout.Elements.routePageButton()).click()

【讨论】:

  • 感谢您的澄清,很抱歉我弄错了,我会尽快编辑。
猜你喜欢
  • 2021-09-07
  • 2020-07-09
  • 2021-12-26
  • 2023-03-15
  • 2018-03-25
  • 2019-04-24
  • 1970-01-01
  • 2019-05-23
  • 1970-01-01
相关资源
最近更新 更多