javascript Selenium WebDriver JS - 显式等待
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/16882860/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Selenium WebDriver JS - Explicit Wait
提问by Moiz Raja
I am using the selenium-webdriverjs. I want to wait for a certain element to be displayed for which I have created an explicit wait as follows and it works just fine,
我正在使用 selenium-webdriverjs。我想等待某个元素被显示,我已经为它创建了一个显式等待,如下所示,它工作得很好,
var displayed = false;
driver.wait(function(){
driver.findElement(locator).isDisplayed().then(function(value){
displayed = value;
});
return displayed;
}, timeout);
Is this the best I can do or is there a better way to do this? The reason I ask is that the first time ever the wait callback is called (in my case) it will always return false. Only subsequently when the isDisplayed promise is executed will the value of displayed change.
这是我能做的最好的还是有更好的方法来做到这一点?我问的原因是第一次调用等待回调(在我的情况下)它总是返回 false。只有随后执行 isDisplayed 承诺时,display 的值才会改变。
回答by coudy
Your code is mixing a synchronous return with asynchronous callbacks, the following code should do the right thing:
您的代码将同步返回与异步回调混合在一起,以下代码应该做正确的事情:
return driver.wait(function() {
return driver.findElement(locator).isDisplayed();
}, timeout);
The inner function will return a promise that driver.wait
will wait for and will take its value (true/false) as the waiting condition.
内部函数将返回一个driver.wait
将等待的承诺,并将其值(真/假)作为等待条件。
回答by jsdevel
To avoid much of the confusion involved in the asynchronous flavors of webdriver and js, you could give webdriver-sync a try: https://npmjs.org/package/webdriver-sync
为了避免 webdriver 和 js 的异步风格所涉及的大部分混淆,您可以尝试使用 webdriver-sync:https: //npmjs.org/package/webdriver-sync
It's been my experience that the async versions of the webdriver API become difficult to read after too many nested callbacks.
根据我的经验,在过多的嵌套回调之后,webdriver API 的异步版本变得难以阅读。
This of course assumes that you don't have requirements to remain asynchronous.
这当然假设您没有保持异步的要求。
Disclaimer: I am the creator of this piece of software (webdriver-sync)
免责声明:我是这个软件(webdriver-sync)的创建者