Home > database >  How to make Selenium WebdriverJS code execute in sequence
How to make Selenium WebdriverJS code execute in sequence

Time:11-07

I'm relatively new to using WebDriverJS and trying out a simple script to begin with. However, am facing a lot of issues and did not find any resources that were helpful.

Scenario being Tested:

  1. Launch browser
  2. Navigate to google.com
  3. Capture Title of the page
  4. Add a wait statement (driver.sleep)
  5. Enter some text in Search box

Here is the code snippet:

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

var driver = new webdriver.Builder().forBrowser('chrome').build();
driver.get("http://www.google.com");
driver.getTitle().then(function(title) {
    console.log("Title is: "   title);
});
console.log('Before sleep');
driver.sleep(10000);
console.log('After sleep');
driver.findElement(By.name('q')).sendKeys("Hello");

Here is the output:

Before sleep
After sleep

DevTools listening on ws://127.0.0.1:52449/devtools/browser/aea4d9eb-20ee-4f10-b53f-c2003c751796
Title is: 

As can be seen, it is a very straight forward scenario. However none of it is working as expected.

Below are my queries/ observations:

  1. console.log for Before/ After sleep is executed as the very first statement even before browser is launched whereas it is not clearly the intention.
  2. Title is returned an empty String. No value printed.
  3. driver.sleep() never waited for the specified duration. All commands got immediately executed. How to make driver hard wait when driver.sleep is not working?
  4. Tried adding implicit wait, however that resulted in error as well.
  5. What are the best practices to be followed?

I did not find very many helpful webdriver javascript resources and it is not clear how to proceed.

Any guidance is appreciated. TIA.!

I referred the documentation as well and similar steps are given there. Not sure if there is some issue from my end. https://github.com/SeleniumHQ/selenium/wiki/WebDriverJs

CodePudding user response:

Assuming that you example is written in JavaScript and runs on Node.js, it looks to be as if you would miss all the waiting for asynchronous functions to have finished processing. Please be aware that most functions return a promise and you must wait for the promise to be resolved.

Consider the following example code:

const {Builder, By, Key, until} = require('selenium-webdriver');

(async function example() {
  let driver = await new Builder().forBrowser('firefox').build();
  try {
    await driver.get('http://www.google.com/ncr');
    await driver.findElement(By.name('q')).sendKeys('webdriver', Key.RETURN);
    await driver.wait(until.titleIs('webdriver - Google Search'), 1000);
  } finally {
    await driver.quit();
  }
})();
  • Related