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).