Is it possible to use .then() in Selenium Webdriver when finding multiple elements with find

Before delving into the issue at hand, I must mention that my experience with selenium-webdriver has mostly been within the context of wrapper/dsl frameworks (such as Capybara for Ruby) or newer automation frameworks like Cypress/Playwright.

Recently, while examining some older code, I came across what appeared to be a complex sequence of selenium commands involving finding elements and waiting. The structure resembled callback hell, which is quite different from the selenium samples I have encountered in the past. Here is a snippet from the chain of commands:

driver.sleep(1000).then(function(a) {
        driver.findElement(locators.baseURL)
        .sendKeys("www.widgets.com");
        driver.sleep(1000).then(function(b) {
                driver.findElement(locators.someKey)
                 .sendKeys("AVALIDKEY");
                 driver.sleep(1000).then(function(c) {
                        driver.findElement(locators.somethingElse)
                        .sendKeys("SOMETEXT");
                        driver.sleep(1000).then(function(d) {
                                driver.findElement(locators.anotherLocator)
                                .click();
                                driver.sleep(6000).then(function(e) {
                                etc......
})})})})})

This pattern continues for quite some time. Admittedly, despite my familiarity with selenium, this particular usage seems unusual to me. It's worth noting that this code dates back around 4-5 years.

My main inquiry revolves around whether this intricate coding approach is standard practice for selenium. With selenium lacking built-in auto-waiting features akin to cypress or playwright, is there room for improvement in streamlining such sequences? Could this possibly be a contributing factor to why selenium might not be as popular these days?

In scenarios where numerous commands are executed sequentially, how does one effectively manage element waiting times? Does selenium offer support for async/await methods?

It is my understanding that selenium was designed to appear synchronous while functioning asynchronously under the surface. Therefore, is this convoluted script an accurate representation of how selenium scripts "should" be formulated?

Additionally, wouldn't the cumulative sleep durations result in lengthy test execution times? Or does selenium optimize waiting periods in some way?

Answer №1

To utilize the async function, you simply need to wrap your code within it and then apply the await keyword:

async function execute(){
  await driver.sleep(1000)
  await driver.findElement(locators.baseURL)
    .sendKeys("www.widgets.com");
  await driver.sleep(1000)
}
execute()

Using the sleep method in this manner may not be the best practice from a technical standpoint.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Navigating through states in Angular-ui-router seamlessly while performing asynchronous calls

Attempting to initiate an asynchronous API call through the onEnter function to a new .state. onEnter: function(StatFactory){ StatFactory.getStats(function(res){ console.log("callback"); }); } What I h ...

ng-options is not compatible with an object as a source

It seems like there should be a simple solution to this issue, but I'm struggling to get ng-options to work with my model object. Essentially, I want to populate my select dropdown with a list of countries. Each option value should be a country code a ...

Looking for a solution to my issue - my for loop is looping more times than it should

I am designing a confirm dialog using jQuery and Bootstrap. When the user clicks on 'Yes' or 'No', it should trigger an action, such as drawing two squares each time. The first time I click either button, it draws 2 squares. However, wi ...

capture the event when a value is submitted into the input field

One of the challenges I'm facing involves an input field intended for user emails I am trying to capture two specific events from this field using JavaScript The first event is triggered by clicking on the input field itself. The second event I need ...

Sorting elements in an array based on an 'in' condition in TypeScript

I am currently working with an arrayList that contains employee information such as employeename, grade, and designation. In my view, I have a multiselect component that returns an array of grades like [1,2,3] once we select grade1, grade2, grade3 from the ...

What is the best way to showcase this code using HTML?

Looking to create a real-time user counter for my Meteor app using Javascript. Currently, I am using the following code snippet to track the number of users on the site: Presences.find({online: true}).count(); However, I am unsure how to display this inf ...

What is the best way to retrieve information from a database using JSON with PHP, JQUERY, and

Trying to retrieve data from a MySQL database and pass it to a JavaScript file has been quite a challenge. Despite searching extensively online, the examples I found didn't work in my specific scenario. .html file <!DOCTYPE html PUBLIC '-//W ...

Unable to add an external NPM package for the creation of an Angular library

package.json was the first thing I worked on, { "name": "crypto-local-storage", "version": "0.0.1", "peerDependencies": { "@angular/common": "^12.2.0", "@angular/core ...

Creating an engaging Uikit modal in Joomla to captivate your audience

I need help optimizing my modal setup. Currently, I have a modal that displays articles using an iframe, but there is some lag when switching between articles. Here is the JavaScript function I am using: function switchTitleMod1(title,id) { document.g ...

What could be causing the failure to retrieve the salt and hash values from the database in NodeJS?

My current issue involves the retrieval of hash and salt values from the database. Although these values are being stored during sign up, they are not being retrieved when needed by the application. Below, you will find snapshots of the database, console s ...

Function that contains a JavaScript reference and observation

I'm experiencing issues with the code below and I'm having trouble figuring out what's causing the problem. function some(){ for (var i=0;i<....;i++) { var oneObject; ...some logic where this object is set oneObject.watch(prop ...

Express always correlates the HTTP path with the most recently configured route

Recently, I encountered a strange issue with my Express routes configuration. It seems that no matter which path I request from the server, only the callback for the "/admin" route is being invoked. To shed some light on how routes are set up in my main N ...

Having trouble generating a report in TestNg following a specific method

My print statement is not working after the login method in TestNG. It correctly prints the login-method statement. package lectures; import java.io.IOException; public class DependencyAnnot extends TestBase { // The code is written ...

Showing particular classes on an element using intersectionObserver/Scrollspy: a step-by-step guide

Here are three different sections on my Vue page. <section id="home">Home</section> <section id="about">About</section> <section id="contact">Contact</section> When I click on a Navbar Link ...

Choose the tab labeled "2" within a segment of the webpage

index.html#section takes you to a specific section of a webpage. However, I am interested in picking the second tab within a section of the page. I'm uncertain if this can be achieved without relying on JavaScript, but employing the Tab Content Script ...

Unable to establish SocketIO callback from client to server resulting in a null object instead

I'm encountering an unusual issue with SocketIO. On the server-side, I am using the emit() method like this: $s.sockets.emit(scope, {some: datas}, function(feedback) { console.log('received callback'); } ) ...

Encountering difficulties in the installation of a package within Next JS

Can anyone assist me with this issue I'm facing while trying to install styled-components on Next JS? I keep getting an error after entering npm install --save styled-components: npm ERR! Unexpected end of JSON input while parsing near '...ry.np ...

Issue with navigation menu button functionality on mobile devices

Whenever I attempt to access my website on a small device, the bootstrap navbar is supposed to collapse. However, the button doesn't seem to be working. Any assistance would be greatly appreciated as this is the one issue I'm struggling with. I&a ...

How to build a registration form with Stateless Components?

Could someone provide a sample code or explanation on how to create a form using stateless components? I'm also in need of a Material UI form example that utilizes refs. Please note that I am working with Material UI components. Below is the curren ...

Issue with React's MaterialUI Select Component not displaying the values passed as props

In my component, I have a FormControl element that includes a Select element accepting an array of options for MenuItem options, as well as a value as props. The component code looks like this: const TaxonomySelector = (props) => { const { isDisabled, t ...