Blogs

How to make Selenium work with Node.js

Introduction

Node development is quite different from other programming languages like Python or Ruby. In Python, you write code in a straight way with expected behavior. But in Node because of asynchronous factors, the code might break you out with unexpected behavior. Similarly this might pose challenges in automating the application using Selenium. To explain this better lets take an example.

Lets look at the below Selenium code

The above red circled code does not work because both statements are executed at the same time.  Why? As we explained in the introduction Node development is quite different from other programming languages like Python or Ruby. The asynchronous factors will provide unexpected behavior. Lets look at the failure trace

Failure:

What is the Solution for this asynchronous behaviour?

WebDriver for javascript luckily allows us to use “Promises” so that the steps of our test are executed in the proper sequence.

What is a Promise?

JavaScript allows you to create a new type of object called a Promise. Promises are used for asynchronous or deferred computations, and can be an alternative to the usual callback approach.

Promises are a bit better, a resolution context is returned and a then() method can be chained for the next operation. The sequence is now somewhat manageable and not packed into one giant triangle.

The following code snippet does the same thing the previous version should, but it actually executes correctly:

Given below code  used to get the project  tile .

See the output of your script file.

Conclusion:
By using “Promise” in our Selenium code we are addressing the asynchronous behavior of Node.js applications and making our Selenium code more robust!!

Leave a Comment