Selenium IJavaScriptExecutor `ExecuteScript()` 方法在将页面对象作为参数传递时抛出异常

Selenium IJavaScriptExecutor `ExecuteScript()` method throwing an exception when passing page objects as params

我正在使用 Selenium 2、C#、SpecFlow、页面对象和页面工厂创建 BDD 框架来初始化页面对象。

出于报告目的和异常处理,我使用 EventFiringWebDriver class 覆盖了 Selenium 基本操作的事件侦听器,并在覆盖的方法中添加了报告调用。

public class WebDriverActionListener : EventFiringWebDriver
{
     protected override void OnElementClicked(WebElementEventArgs e)
     {
        base.OnElementClicked(e);
        const string expectedDescription = "Click on the element";
        var actualDescription = String.Format("Successfully clicked on the element '{0}'", ScenarioContext.Current["element"]);
        Reporter.ReportEvent(expectedDescription, actualDescription, Status.Pass); // Logging the low level reporting
        _driver.Sync();
     }
}

现在我正在为 WebDriverActionListener class 创建对象,如下所示:

return new WebDriverActionListener(new FirefoxDriver());

我正在使用上面初始化的相同驱动程序初始化页面对象。

[FindsBy(How = How.Id, Using = "Login1_UserName")]
private IWebElement _userName;

public LoginPage(IWebDriver driver)
{
  _driver = driver;
  PageFactory.InitElements(_driver, this);
  if (!(_userName.Displayed && _loginButton.Displayed))
    throw new InvalidPageObjectException("Login page is not displayed", Status.Fail);
}

public void SomeMethod()
{
 _userName.JsClick(); // Java Script click call method
}

我创建了一种使用 javascript(非常旧的应用程序)单击某些页面对象的方法。当我尝试将页面对象元素传递给 ExecuteScript() 方法时出现异常。根据提供的帮助,它应该接受“IWebElement”作为参数。

public static void JsClick(this IWebElement element)
{
  ((IJavaScriptExecutor)_driver).ExecuteScript("arguments[0].click();", element);
}

但我无法在“ExecuteScript()”方法中使用页面对象。

读得太快了。如果我没记错(也没有测试),扩展方法必须是 staticReference

嗯,我没有合适的解决方案,但我有解决办法。

要使用 Java 脚本单击的元素,使用 WebDriver 的 FindElement() 方法找到它们,而不是创建页面对象(仅要使用 Java 脚本单击的元素)

_driver.FindElement(By.Id("Login1_UserName")).JsClick();

这种方法应该毫无例外地起作用。