Selenium with JavaScript: The Battle of Anonymous Functions and Named Functions

When working with Selenium JavaScript, the prevalent advice I come across online suggests that the most effective approach to handle the asynchronous behavior of JavaScript is by utilizing anonymous functions with .then() for locating/interacting with elements on a page, as opposed to creating named functions and executing them at runtime.

For instance, if I wanted to perform a login operation using credentials:

Situation:

'use strict';
const WebDriver = require('selenium-webdriver');
const By    = WebDriver.By;
const until = WebDriver.until;
var driver = new WebDriver.Builder().withCapabilities(
    WebDriver.Capabilities.chrome()).build();

Scenario A:

driver.get("http://somefakewebsite.com")
.then(function(){ driver.findElement(By.id("login")).sendKeys("myLogin"); })
.then(function(){ driver.findElement(By.id("password").sendKeys("myPassword"); })
.then(function(){ driver.findElement(By.id("submit").click(); })
.then(function(){ driver.wait(until.elementLocated(By.id("pageId")), 5000); })
.then(function(){ driver.findElement(By.id("buttonOnlyAvailableAfterLogin").click(); })

Scenario B:

function inputLogin(driver){
    driver.findElement(By.id("login")).sendKeys("myLogin");
}

function inputPassword(driver){
    driver.findElement(By.id("password")).sendKeys("myPassword");
}

function clickSubmit(driver){
    driver.findElement(By.id("submit")).click();
}

function waitAfterLogin(driver){
    driver.wait(until.elementLocated(By.id("pageId")), 5000);
}

function clickSomeButtonAfterLogin(driver){
    driver.findElement(By.id("buttonOnlyAvailableAfterLogin")).click();
}

driver.get("http://somefakewebsite.com")
.then(inputLogin(driver))
.then(inputPassword(driver))
.then(clickSubmit(driver))
.then(waitAfterLogin(driver))
.then(clickSomeButtonAfterLogin(driver))

My inquiry: Is there a specific advantage to opting for Scenario A over Scenario B? Despite both methods proving functional during execution, the latter entails more lines of code while offering a clearer organization and readability (thanks to the descriptive names of the functions providing clarity compared to deciphering the logic within the anonymous functions in Scenario A).

Answer №1

The distinction between the two scenarios is as follows:

Scenario A expects the promise to be resolved before executing each consecutive method.

Scenario B can be likened to the code snippet below:

const result = browser.navigateTo("http://somefakewebsite.com")

enterUsername(browser)
enterPassword(browser)
clickLoginButton(browser)
waitForPageToLoad(browser)
clickActionButton(browser)

result
  .then(undefined)
  .then(undefined)
  .then(undefined)
  .then(undefined)
  .then(undefined)

If Scenario B suits your needs, it may indicate that the execution of `browser.navigateTo` does not necessarily have to be completed for its subsequent methods to function properly. Alternatively, there might be missing elements in your code, or the Promise could resolve immediately, or encounter a blocking issue.

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

sending an alert via a function's return statement

Could you explain to me why this code isn't functioning properly? When I call s.A, the alert message doesn't appear. Can you help me understand why? var s = { A: function () { alert("test A"); }, B: function () { alert("test B"); } }; ...

Retrieving information received from an XML HTTP request in node.js

Currently, I am transmitting text data from a textbox to a node.js express server using XMLHttpRequest: var text = document.getElementById("textBox").value; console.log(text); var xmlhttp; if (window.XMLHttpRequest) {// code for IE7+, Fire ...

AngularJS enables the loading of directives dynamically, but sometimes encounters errors such as "Restricted URI access denied."

Presently, I am in the process of developing a small educational project using HTML5, CSS, JS and AngularJS. Hiccup: Loading an AngularJS Directive in my index.html file Error code [1] - Local browser Error: Access to restricted URI denied Various resp ...

Guidelines on integrating Admob into Ionic framework

I tried following the steps outlined in this post: AdMob not loading ads in ionic/angular app After running the app using "ionic build ios && ionic emulate ios," I still see no ads, no black bar, nothing at all. Can someone help me figure out wha ...

Scripting events in JavaScript/jQuery are failing to trigger on elements located inside nested <div> containers

I am currently developing a simple RSS reader application where, upon clicking a 'story', the relevant information is displayed in a modal view. The 'stories' or RSS feed items are presented in a scrolling row. However, I have encounte ...

Failed to build development environment: Unable to assign the attribute 'fileSystem' to a null value

I'm attempting to launch an Ionic 2 Application, but I keep encountering this error when running ionic serve Error - build dev failed: Unable to assign a value to the 'fileSystem' property of object null Here is the complete log: λ ion ...

Executing ng-click to access outer controller from within nested ng-controllers

I'm exploring the potential of using angularjs to develop a dynamic page with the following capabilities: It starts off blank, except for a dropdownlist that automatically populates with various apps. Upon selecting an app from the list, relevant da ...

Is there a way to access the webpage and search form along with login credentials using selenium and Beautifulsoup?

I am looking to extract data from this website for a project involving natural language processing. Despite having a subscription, I am encountering difficulty in obtaining the desired results. The error message indicates that the element cannot be located ...

Optimize Date Formatting within a React Application Using Material UI Data Grid

I am currently working with MUI Data Grid Pro and I have an issue with filtering dates in the format dd-mm-yyyy. While the dates are displayed correctly in the columns, the filtering defaults back to mm-dd-yyyy. https://i.stack.imgur.com/Ue12K.png For mo ...

Encountering a NULL argument in an MVC controller when executing an Ajax post request

I am facing an issue with my ajax post request where I send JSON string data, but it is showing null in my controller. Here is the AJAX Call: var jsonData = JSON.stringify(matrixPresenter); $.post("/matrix/Savematrix?matrixData=" + jsonData , fu ...

comparing caching with jquery deferred against promise

Currently, I have implemented code using jQuery Deferred and ajax to fetch data from a remote API, store it in localStorage, and retrieve it from there. However, this code has a bug where it doesn't display the data properly the first time it runs (re ...

What is the best way to delay JavaScript execution until after React has finished rendering?

Perhaps this is not the exact question you were expecting, but it did catch your attention :) The issue at hand revolves around the fact that most of the translations in my text do not update when the global language changes. Specifically, the translation ...

How to extract keys with the highest values in a JavaScript hashmap or object

Here is an example for you to consider: inventory = {'Apple':2, 'Orange' :1 , 'Mango' : 2} In this inventory, both Apple and Mango have the maximum quantity. How can I create a function that returns both Apple and Mango as t ...

JavaScript - The progression of a virtual pet even when the user is offline

Currently, I am utilizing VueJS and MongoDB to develop an interactive virtual pet. Our approach involves storing user data in localStorage for easy access and retrieval. I'm exploring the concept of allowing the virtual pet to evolve autonomously (s ...

What could be the reason for a variable not being assigned a value following the xmlhttp.responseText?

During the validation process of a send-fax form, I am checking if a fax has been previously sent using our software fax package. This involves a simple query to a table executed by a script, which will return text if a previous fax exists or blank if not. ...

Switch Focus and Collapse Submenus upon Menu Click in Recursive React Menu

I've created a dynamic menu system in React using Material-UI that supports recursion for submenus. I'm aiming to implement the following features: 1. When a menu item is clicked, all other open submenus should close and focus on the clicked men ...

A guide to effortlessly converting Any[] to CustomType for seamless IntelliSense access to Properties within Angular/Typescript

Our Angular service interacts with the backend to retrieve data and display it on the UI. export interface UserDataResponse { id: number; userName: string; } AngularService_Method1() { return this.http.get<UserDataResponse[]>(this.appUrl + "/Ap ...

What is the process for executing a Node.js file using a JavaScript command?

Currently, I am in the process of developing an online game that doesn't require high-speed interaction, allowing for the utilization of a single json file. My familiarity with node.js is limited, as I am relatively new to it. In my exploration, I ca ...

Creating a Vertical Navbar Dropdown in Bootstrap 3.0 Without Appending to the Last List Item Only

Currently, I'm in the process of creating a panel layout that features an elegant vertical navbar. Although everything seems to be aligned correctly and I've managed to implement a dropdown menu in a vertical layout, it keeps appending to the las ...

Issue with Jquery Drag and Drop functionality, navigate to a different page

I am trying to incorporate a page with js from quotemedia.com using Jquery. When I insert the js into the sortable, and then drag and drop the element containing the js, it suddenly switches to full page display. This issue occurs in Firefox, but IE works ...