SamAm
SamAm

Reputation: 39

Trying to pick a success message in Selenium WebDriver with JavaScript

I'm training on Selenium WebDrivers with JavaScript, I'm trying a simple walkthrough :

  1. opening chrome and browsing to a specific web page
  2. looking for the input field and entering an email address ([email protected])
  3. clicking on the button
  4. then picking the success message, and displaying it into my console

Steps 1,2 and 3 are no problem, but when I'm trying to add step 4, I don't receive the success message anymore on the page, it looks like my "step 4" code is preventing "step 3" to be executed properly

Here is my code :

const { Options } = require('selenium-webdriver/chrome');

var webdriver = require ('selenium-webdriver'),
By = webdriver.By,
until = webdriver.until;
   
var driver = new webdriver.Builder().forBrowser('chrome').build();


//Step 1

driver.get('https://library-app.firebaseapp.com/');


//Step 2

driver.findElement(By.css('input')).sendKeys('[email protected]');

//Step 3

driver.findElement(By.css('.btn')).click();

//I let 1 sec for the success message to be displayed before I can look for it

driver.sleep(1000);

//Step 4
driver.findElement(By.css('.alert-success')).getText().then(function(txt) {

    console.log("The alert success text is : " + txt);
});

If I'm removing step 4, everything is working fine, the success message is displayed, but if I add Step 4 in my code, I don't get it, and then, I get the following error message :

NoSuchElementError: no such element: Unable to locate element: {"method":"css selector","selector":".alert-success"}

I'm obviously missing something here, but can't figure out what. What am I doing wrong ?

Thanks for your help !

Upvotes: 0

Views: 671

Answers (1)

Avi L
Avi L

Reputation: 1708

The error occurred because the element wasn't created in the dom since the code didn't wait for the sleep to finish.

driver.sleep is a async function that returns a Promise. you need to use .then() or await so your code will execute after the sleep time is over.

driver.sleep(1000).then( () => {
  //Step 4
  driver.findElement(By.css('.alert-success')).getText().then(function(txt) {
    console.log("The alert success text is : " + txt);
});

})

Upvotes: 1

Related Questions