如何创建一个等待函数,可以在代码中多次调用它

时间:2019-02-19 07:33:39

标签: javascript selenium

我需要演示我的代码,并需要添加一个函数以等待,以便可以在脚本需要放慢速度的地方调用该函数。请指导。

1 个答案:

答案 0 :(得分:1)

我已经针对硒中的Explicit waitsFluent waits编写了以下可重用的方法

/**
 * Purpose Fluent Wait for an element to appear on screen with a text
 * polling every 100ms
 * 
 * @param sec Time to wait for element
 * @param element WebElement to wait for
 */
public void fluentWaitforElementText(int sec, WebElement element) {
    new FluentWait<WebElement>(element).withTimeout(sec, TimeUnit.SECONDS)
            .pollingEvery(100, TimeUnit.MILLISECONDS)
            .until(new Function<WebElement, Boolean>() {
                public Boolean apply(WebElement element) {
                    Boolean b = null;
                    if (element.getText().isEmpty())
                        b = false;
                    else if (!element.getText().isEmpty())
                        b = true;
                    return b;
                }
            });
}

/**
 * Purpose Wait for an element with text to appear on screen i.e. [Element
 * with expected condition with some text with length>0]
 * 
 * @param sec Time to wait for element
 * @param element WebElement to wait for
 */
public void waitForElementTextBooleanExpectedCondition(int sec,
        final WebElement element) {

    (new WebDriverWait(driver, sec))
            .until(new ExpectedCondition<Boolean>() {
                public Boolean apply(WebDriver dr) {
                    return element.getText().trim().length() > 0;
                }
            });
}

/**
 * Purpose Wait for an element until expected conditions are meet i.e.
 * [Element with expected condition that it is visible on screen]
 * 
 * @param sec Time to wait for element
 * @param Locator By object of webelement to wait
 */
public void waitForVisibilityOfElementLocated(int sec, By Locator,
        WebDriver driver) throws TimeoutException {
    (new WebDriverWait(driver, sec)).until(ExpectedConditions
            .visibilityOfElementLocated(Locator));
}