Understanding Asynchronous WebdriverJS


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.
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.
Hope it is helpful. Written by: Asiq Ahamed

Leave a Reply

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