繁体   English   中英

WebDriver 执行 javascript 奇怪行为

[英]WebDriver executing javascript strange behaviour

我正在通过 JBehave-Web 分发(3.3.4)使用 Webdriver 来测试应用程序,但我遇到了一些非常奇怪的事情:

我正在尝试与 Richfaces 的 modalPanel 进行交互,这给了我很多问题,因为它抛出了 ElementNotVisibleException。 我通过使用 javascript 解决了它:

这是我的页面 object 中的代码,它从 org.jbehave.web.selenium.WebDriverPage 扩展而来

protected void changeModalPanelInputText(String elementId, String textToEnter){
    makeNonLazy();
    JavascriptExecutor je = (JavascriptExecutor) webDriver();
    String script ="document.getElementById('" + elementId + "').value = '" + textToEnter + "';";
    je.executeScript(script);
}

奇怪的行为是,如果我正常执行测试,它什么也不做,但是如果我在最后一行(在 Eclipse 中)设置断点,select 行并从 Eclipse(Ctrl + U)执行,我可以看到变化浏览器。

我检查了 JavascriptExecutor 和 WebDriver 类以查看是否有任何类型的缓冲,但我找不到任何东西。 有任何想法吗?

编辑我发现让线程休眠 1 秒可以让它工作,所以它看起来是某种竞争条件,但不知道为什么......

这就是它“工作”的方式,但我对此并不满意:

protected void changeModalPanelInputText(String elementId, String textToEnter){
    String script ="document.getElementById('" + elementId + "').value = '" + textToEnter + "';";
    executeJavascript(script);
}

    private void executeJavascript(String script){
    makeNonLazy();
    JavascriptExecutor je = (JavascriptExecutor) webDriver();
    try {
        Thread.sleep(1500);
    } catch (InterruptedException e) {
        e.printStackTrace();
    }
    je.executeScript(script);       
}

在任何其他 position 中等待也不起作用......

第一个想法:

确保目标元素已初始化且可枚举。 看看这是否返回null

Object objValue = je.executeScript(
    "return document.getElementById('"+elementId+"');");

由于您使用的是makeNonLazy() ,因此可能只需将目标添加为页面 Object 的 WebElement 成员(假设 JBehave 中的页面工厂类型初始化)。

第二个想法:

在变异之前显式等待元素可用:

/**
 * re-usable utility class
 */
public static class ElementAvailable implements Predicate<WebDriver> {

    private static String IS_NOT_UNDEFINED = 
        "return (typeof document.getElementById('%s') != 'undefined');";
    private final String elementId;

    private ElementAvailable(String elementId) {
        this.elementId = elementId;
    }

    @Override
    public boolean apply(WebDriver driver) {
        Object objValue = ((JavascriptExecutor)driver).executeScript(
                String.format(IS_NOT_UNDEFINED, elementId));
        return (objValue instanceof Boolean && ((Boolean)objValue));
    }
}

...

protected void changeModalPanelInputText(String elementId, String textToEnter){
    makeNonLazy();

    // wait at most 3 seconds before throwing an unchecked Exception
    long timeout = 3;
    (new WebDriverWait(webDriver(), timeout))
            .until(new ElementAvailable(elementId));

    // element definitely available now
    String script = String.format(
            "document.getElementById('%s').value = '%s';",
            elementId,
            textToEnter);
    ((JavascriptExecutor) webDriver()).executeScript(script);
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM