等待使用带有mocha / chai的webdriverjs加载页面

时间:2015-02-16 09:34:13

标签: javascript selenium-webdriver webdriver

在下面的代码示例中,单击标识为openPage的锚点应该会打开一个新页面。当使用短暂延迟sleep(1000)时,测试只会成功,因为getCurrentUrl似乎不等到页面加载。

var element = driver.findElement(webdriver.By.id('openPage'));
element.click();

driver.sleep(1000);

var promise = driver.getCurrentUrl();
promise.then(function (url) {
   assert.strictEqual(url, 'page title');
});

在不使用延迟的情况下对此进行编码的正确(异步)方法是什么?

1 个答案:

答案 0 :(得分:3)

This great article将我的问题完美地回答,并产生了以下帮助函数,我现在正在等待页面加载:

function waitForPageLoad (driver, timeout) {
    var oldHtmlElement;

    // check the arguments
    if (typeof timeout === 'undefined') {
        timeout = 5000;
    } else {
        if (typeof timeout !== 'number' || timeout <= 0) {
            throw new TypeError('The argument timeout must be a integer > 0');
        }
    }

    // get the html tag on the old page
    oldHtmlElement = driver.findElement(webdriver.By.tagName('html'));

    // wait until the function returns true or the timeout expires
    driver.wait(function () {
        // get the html tag on the (eventually already) new page
        var newHtmlElement = driver.findElement(webdriver.By.tagName('html')),
            newHtmlElementId = newHtmlElement.getId(),
            oldHtmlElementId = oldHtmlElement.getId();

        // compare the id of the html tag on the page with the one we just got
        //  and if it's no longer the same one, we must be on the new page.
        return oldHtmlElementId !== newHtmlElementId;
    }, timeout);
}