Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

selenium-webdriver node.js: how to handle missing element after wait timeout (exception can't seem to be caught)

I'm using Node.js selenium-webdriver and I have this annoying issue. I have this login function that fills out some fields and then tries to login to a website by triggering a click of a button. My way of knowing if the login succeeded is to wait for a certain element after the button click. I want to wait for 5 seconds, and respond accordingly to the caller.

The issue is that the wait function throws an exception and using try/catch around that doesn't help (the exception isn't caught and the program exits).

This is my code:

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

var driver = new webdriver.Builder()
    .forBrowser('chrome')
    .build();

var timeout = 5000;

function login(username, password, callback) {
    driver.get('https://www.example.com/');

    driver.switchTo().frame(driver.findElement(By.css("iframe")));
    driver.findElement(By.name('userid')).sendKeys(username);
    driver.findElement(By.name('password')).sendKeys(password);
    driver.findElement(By.id('submit_btn')).click();

    driver.wait(until.elementLocated(By.className('indication-that-login-was-successful')), timeout).then(function(elm) {
        callback(true);
        driver.quit();
    });
}

So in case the login was not successful (for example because the password was incorrect), the element indication-that-login-was-successful will never appear (a good thing). But in this case I keep getting

TimeoutError: Waiting for element to be located By(css selector, .indication-that-login-was-successful) Wait timed out after 5001ms

Ideally I could catch this exception and callback with false and quit the driver:

try {
    driver.wait(until.elementLocated(By.className('indication-that-login-was-successful')), timeout).then(function(elm) {
        callback(true);
        driver.quit();
    });
} catch (ex) {
   callback(false); 
   driver.quit();
}

However as stated above, wrapping this up with a try/catch block doesn't seem to help, the exception is never caught and the program exists.

Any ideas?

like image 957
orcaman Avatar asked Dec 14 '25 18:12

orcaman


1 Answers

You can try:

driver.wait(until.elementLocated(By.className('indication-th‌​at-login-was-success‌​ful')), 5000).then(function(elm) {
        callback(true);
        driver.quit();
    }).catch(function(ex) {
        callback(false);
        driver.quit();
    });
like image 144
Linh Nguyen Avatar answered Dec 17 '25 09:12

Linh Nguyen



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!