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

Wait for page to load using webdriverjs with mocha/chai

在下面的代码示例中,单击 ID 为 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');
});

在不使用延迟的情况下,正确的(异步)编码方式是什么?

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);
}