Select Page
Codoid Blog

Understanding Asynchronous WebdriverJS

Being a leading QA Company, we write blogs on all prominent software testing topics and tools using our real-world experience. So stay sharp by subscribing to our Newsletter.

While I was working on a proof of concept using CucumberJS and Selenium-WebDriverJs, I found a few interesting concepts which are very helpful for testers who are newbies to JavaScript automation testing.

Let’s see with an example.

require('chromedriver')

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

var by = driver.By;

browser.get('https://codoid.com');

browser.quit();

//Print Done
console.log("===============>Done")  

If you run the above JS snippet, it will print the console.log before launching the browser, and the execution will be completed only after executing all the statements.

Now you may ask a few questions-1) Why my Selenium commands are not waiting and 2) Why the execution is not completed even after executing the last statement (console.log)?

The answer is: WebDriver’s JavaScript API is entirely asynchronous, and every Selenium WebDriver command returns a Promise object.

Asynchronous function calls make the script as non-blocking, so that is why the script did not wait for browser launch and console.log was printed immediately. However, how the execution was not completed even after executing the last statement (console.log)?

That is because of the ControlFlow class which is used by WebDriver’s JavaScript API internally to schedule all your Selenium commands as tasks in a queue.

See the below diagram. As soon as you start the execution, all the Selenium webdriverJs commands are scheduled asynchronously in a Controlflow task queue and the ControlFlow executes the tasks one by one.

Understanding Asynchronous WebdriverJS

Note: If you are using CucumberJS with WebDriverJS, then return a Promise at the last line of your step definition as shown below so that the step definitions waits until the promise is returned from the control flow.

When(/^I click ([^"]*) link$/, function (text) {
    condition=driver.until.elementLocated(by.linkText('CONTACT US'))
    browser.wait(condition, 10000).click();
    return browser.findElement({linkText: text}).click();
});  

Hope it is helpful.

Written by: Asiq Ahamed

Comments(0)

Submit a Comment

Your email address will not be published. Required fields are marked *

Talk to our Experts

Amazing clients who
trust us


poloatto
ABB
polaris
ooredo
stryker
mobility