Selenium JavaScript:匿名与命名函数

Selenium JavaScript:匿名与命名函数,javascript,selenium,Javascript,Selenium,对于Selenium JavaScript,我在interwebs上读到的每个示例似乎都解释了处理JavaScript异步性质的最佳方法是使用.then()创建一个匿名函数来查找页面上的每个元素/与之交互,而不是创建命名函数并在运行时调用它们 例如,如果我想使用凭据登录到站点: 背景: 'use strict'; const WebDriver = require('selenium-webdriver'); const By = WebDriver.By; const until = W

对于Selenium JavaScript,我在interwebs上读到的每个示例似乎都解释了处理JavaScript异步性质的最佳方法是使用
.then()
创建一个匿名函数来查找页面上的每个元素/与之交互,而不是创建命名函数并在运行时调用它们

例如,如果我想使用凭据登录到站点:

背景:

'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();
示例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(); })
例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))

我的问题:使用示例A比使用示例B有优势吗?在尝试运行时,它们似乎都起作用。尽管第二种方法看起来像是更多的代码行,但它只是感觉更有条理,更易于阅读(因为命名函数确切地告诉我发生了什么,而不是试图阅读示例A中匿名函数中的逻辑)

两者之间的区别如下:

示例A等待承诺兑现,然后一个接一个地链接每个方法

示例B大致等同于以下内容:

const result = driver.get("http://somefakewebsite.com")

inputLogin(driver)
inputPassword(driver)
clickSubmit(driver)
waitAfterLogin(driver)
clickSomeButtonAfterLogin(driver)

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

如果示例B适用于您,则可能不需要满足
driver.get
的要求即可使其上的方法正常工作,或者问题是缺少代码的关键部分。或者承诺立即兑现。示例B立即执行您的所有方法(
inputLogin
inputPassword
单击Submit
),并将
未定义的
传递到
然后
中,这可能不是您想要的。我不确定您所说的是否正确。。我的示例B脚本运行良好,并且只有在登录后才能与可用的元素交互。。我对我的例子进行了相应的修改。很抱歉,我可能遗漏了你们提到的那个关键部分。我在示例的顶部添加了“内容”来详细说明。