在JS中使用异步/等待的硒,找到并单击元素 [英] Selenium with async/await in JS, find and click on element

查看:86
本文介绍了在JS中使用异步/等待的硒,找到并单击元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I'm trying to refactor my tests using Selenium webdriver and Mocha to ES7 with async/await functionality. I have got following piece of code:

await loginPage.loginAsAdmin()

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

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

我不明白为什么该特定功能不起作用-我得到了:

I don't understand why the particular does not work - I get:

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

click方法之前的函数返回webElement,如您所见:

Function before click method returns webElement, as you can see:

布局:

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
}

推荐答案

此处的问题是误解为await是ES2017中的语言关键字,允许您阻止执行调用async函数,直到Promise调用的函数返回的结果将解决.

The problem here is misunderstanding that await is a language keyword in ES2017 that allows you to block execution of the calling async function until a Promise returned by an invoked function resolves.

routePageButton()返回Promise,这就是上面第二种语法起作用的原因,因为执行被阻塞,直到Promise解析为WebElement对象.

routePageButton() returns a Promise, and this is why the second syntax above works, as execution is blocked until the Promise resolves to a WebElement object.

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

However in the syntax you are using in the first example, the function that it is attempting to await on (click()) is never called, because a Promise does not have a click() function. Note that you have two awaits in your second syntax, but only one in your first.

要在一行中完成您想做的事情,您将必须执行以下操作:

To do what you are attempting to do in one line, you would have to do something like:

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

这篇关于在JS中使用异步/等待的硒,找到并单击元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆