0

In the following code example, clicking on the anchor with id openPage should open a new page. The test only succeeds, when using a short delay sleep(1000) as getCurrentUrl does not seem to wait until the page is loaded.

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

What would be the proper (async) way to code this without using a delay ?

doberkofler
  • 9,511
  • 18
  • 74
  • 126

1 Answers1

4

This great article answers my question to perfection and resulted in the following helper function I'm now using to wait for a page to be loaded:

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);
}
doberkofler
  • 9,511
  • 18
  • 74
  • 126