Selenium with async/await in JS, find and click on element

谁说胖子不能爱 提交于 2020-01-03 02:08:07

问题


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

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

Layout:

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

Method:

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

回答1:


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() returns a Promise, and this is why the second syntax above works, as execution is blocked until the Promise resolves to a WebElement object.

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()


来源:https://stackoverflow.com/questions/43471166/selenium-with-async-await-in-js-find-and-click-on-element

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!