Selenium WebDriverJS thenCatch does not catch a StaleElementException

I am running node.js and Selenium WebDriverJS. One of my tests does not work with the following error:

UnknownError: unknown error: Runtime.evaluate threw exception: Error: element is not attached to the page document

I understand that this is essentially a StaleElementReferenceException exception, but I could not find a reliable solution. I tried the following without success:

  • waiting for an element to appear on the page before searching and clicking on the element

    waitForElement: function (selector, timeout) {
        if (typeof(timeout) === 'undefined') { timeout = 3000; }
        driver.wait(function() {
            return driver.findElements(selector).then(function(list) {
                return list.length > 0;
            });
        }, timeout);
    }
    
  • waiting for an explicit period of time ( driver.sleep(1000)) before searching and clicking on an element
  • search for an item several times (using .findElement()) before clicking on the item
  • using the promise chain to catch any errors and try to click on an element

    driver.getTitle().then(function(title) {
        driver.findElement(webdriver.By.xpath(...)).click();
    }).thenCatch(function(e) {
        driver.findElement(webdriver.By.xpath(...)).click();
    });
    
  • using promise chain with recursive function to try re-clicking an element

    var getStaleElement = function(selector, callback) {
        var element = driver.findElement(selector);
        callback(element);
    }).thenCatch(function(e) {
        getStaleElement(selector, callback);
    });
    
    var clickSelf = function(ele) { return ele.click() };
    
    driver.getTitle().then(function(title) {
        driver.findElement(webdriver.By.xpath(...)).click();
    }).thenCatch(function(e) {
        getStaleElement(webdriver.By.xpath(...), clickSelf);
    });
    
  • 4 5 errback .then() .thenCatch()

, Selenium . , , , NoSuchElementError, .thenCatch(). , ?

+4
2

, , ...

/*
 * params.config - {
 *           opposite - {Boolean} - if true, will wait till negative result is reached/ error is thrown.
 *           maxWaitTime - {Number} - if this time exceeds, just throw an error and leave.
 *           waitTime - {Number} - wait time between two checks.
 *           expectValue - {Boolean} - where you just want it to run without error, or it should expect a value
 *           expectedValue - {Object} - object value it should or should not match.
 *         }
 *  params.fn - a function that returns a promise that we want to keep checking till desire value is reached
 */
function waiter(fn, config){
    config = config || {};
    var deffered = Driver.promise.defer(),  
        wt = config.waitTime || 100,
        mwt = config.maxWaitTime || 3000,
        timeoutReached = false,
        pCall = function(){
                        fn().then(pThen, pCatch);
                    },
        pThen = function(data){
                    if(timeoutReached)  return;
                    if(config.expectValue){
                        if(config.opposite){                        
                            if(data == config.expectedValue){
                                setTimeout(pCall, wt);
                            }else{
                                clearTimeout(vTimeout);
                                deffered.fulfill(true);
                            }
                        }else{
                            if(data == config.expectedValue){
                                clearTimeout(vTimeout);
                                deffered.fulfill(true);
                            }else{
                                setTimeout(pCall, wt);
                            }
                        }
                    }else{
                        deffered.fulfill(true);
                    }
                },  
        pCatch = function(err){
                    if(timeoutReached)  return;
                    if(config.opposite){
                        deffered.fulfill(true);
                    }else{
                        setTimeout(pCall, wt);
                    }
                };  

    pCall();    

    var vTimeout = setTimeout(function(){
        timeoutReached = true;
        if(config.opposite){
            deffered.fulfill(true);         
        }else{
            deffered.reject(new Error('timed-out'));
        }
    }, mwt);
    return deffered.promise;
}

( ):

var myPromise = function(){
    return driver.findElement(webdriver.By.xpath(...)).click();
};

//default use
waiter(myPromise).then(function(){
    console.log('finally...');
}).catch(fucntion(err){
    console.log('not working: ', err);
});

// with custom timeout after 10 seconds
waiter(myPromise, {maxWaitTime: 10000}).then(function(){
    console.log('finally...');
}).catch(fucntion(err){
    console.log('not working: ', err);
});
0

getStaleElement, . :

function retryOnStale(selector, callback) {
    return browser.findElement(selector).then(callback)
        .thenCatch(function (err) {
            if (err.name === 'StaleElementReferenceError')
                return retryOnStale(selector, callback);

            throw err;
        });
}

, . , retryOnStaleIllustrate , - , console.log. retryOnStale, , .

var webdriver = require('selenium-webdriver');
var chrome = require('selenium-webdriver/chrome');
var By = webdriver.By;
var until = webdriver.until;

var browser = new chrome.Driver();

browser.get("http://www.example.com");

function make_stale() {
    browser.executeScript("document.body.innerHTML = " +
                          "'<p id=\\'foo\\'>foo text</p>'");
}

// Create our initial p element with id `foo`.
make_stale();

var fake_stale = 10;

// We have to use var ... = ... because later in this code we are
// going to change the value of retryOnStaleIllustrate.
function retryOnStaleIllustrate(selector, callback) {
    return browser.findElement(selector).then(function (element) {

        //
        // This code is here to simulate a process that causes the element
        // we acquired to become stale.
        //
        if (fake_stale) {
            make_stale();
            fake_stale--;
        }

        return callback(element);
    }).thenCatch(function (err) {
        if (err.name === 'StaleElementReferenceError') {
            console.log("stale: retrying");
            return retryOnStaleIllustrate(selector, callback);
        }

        throw err;
    });
}

retryOnStaleIllustrate(By.id("foo"), function (element) {
    element.getText().then(console.log);
});

// Once we remove the code to simulate an element becoming stale, and
// the console.log for diagnosis, this is what we are left with:
function retryOnStale(selector, callback) {
    return browser.findElement(selector).then(callback)
        .thenCatch(function (err) {
            if (err.name === 'StaleElementReferenceError')
                return retryOnStale(selector, callback);

            throw err;
        });
}

// This just shows that retryOnStale returns a promise which can be used.
retryOnStale(By.id("foo"), function (element) {
    return element.getText();
}).then(function (text) {
    console.log(text);
});

browser.quit();

:

stale: retrying
stale: retrying
stale: retrying
stale: retrying
stale: retrying
stale: retrying
stale: retrying
stale: retrying
stale: retrying
stale: retrying
foo text
foo text

stale: retrying foo text , retryOnStaleIllustrate. foo text , retryOnStale.

0

All Articles