jmreicha
jmreicha

Reputation: 3354

WebdriverJS ElementNotVisibleError: element not visible

I'm new to Selenium and I think I'm just not understanding what is happening in the code and browser. I can work around my issue by replacing the driver.wait code (posted below) with a driver.sleep(1000) but I have been reading that sleep statements aren't ideal.

Can somebody help me figure out why the code I have isn't working and what exactly is going on? I can provide a full stack trace if it is helpful.

Here is what the code looks like.

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

var username = "XXX"
var password = "XXX"

function login(username, password) {    
    // This part works fine
    driver.wait(until.elementLocated(By.id('Email')))
    driver.findElement(By.id('Email')).sendKeys(username)
    driver.findElement(By.id('next')).click()

    // Here is where the element not visible happens
    driver.wait(until.elementLocated(By.id('Passwd')), 5000)
    // driver.sleep(1000) works but I'm not sure why?
    driver.findElement(By.id('Passwd')).sendKeys(password)

    // Login
    driver.findElement(By.id('signIn')).click()
}

var driver = new webdriver.Builder()
        .withCapabilities({'browserName': 'chrome'}).build()
driver.get('https://gmail.com')
login(username, password)

Update:

Per suggestion, I tried using the elementIsVisible function to wait for the element to become visible, via the following code.

driver.wait(until.elementIsVisible(driver.findElement(By.id('Passwd')), 5000))

But I get the following error.

NoSuchElementError: no such element: Unable to locate element: {"method":"css selector","selector":"*[id="Passwd"]"}

Upvotes: 2

Views: 3174

Answers (1)

Saurabh Gaur
Saurabh Gaur

Reputation: 23825

driver.wait(until.elementIsVisible(driver.findElement(By.id('Passwd')), 5000))

Actually this statement is not correct to wait until element is visible, in this statement driver.findElement(By.id('Passwd')) would throw NoSuchElementError if at that time element is not present on the DOM which you are getting.

You should try using until.elementLocated(locator) to wait until desire element present on the DOM first, then wait until element is visible using until.elementIsVisible(element) below :-

const until = webdriver.until;

var pwd = driver.wait(until.elementLocated(By.id('Passwd')), 5000);
driver.wait(until.elementIsVisible(pwd), 5000)).sendKeys(password)

Upvotes: 5

Related Questions