Selenium Navigate Back和jQuery Dirty Forms插件

时间:2016-09-20 15:16:48

标签: asp.net-mvc selenium-chromedriver jquery-dirtyforms

我有一些表单使用jQuery Dirty Forms插件在用户尝试离开之前提醒用户。

在Chrome 52之前,我能够使用Selenium对插件引发的警报进行测试。我打电话给driver.Navigate().Back();,它会触发警告框。然后,我可以使用以下代码处理警报:

d.Navigate().Back();

try
{
    // Expecting an alert now
    IAlert a = d.SwitchTo().Alert();

    // And acknowledge the alert (equivalent to clicking "OK")
    a.Accept();
}
catch (NoAlertPresentException ex)
{
    System.Diagnostics.Debug.Write($"Warning: Expected an alert but none was present. {ex.Message}");
}

但是,自Chrome 52以来,.Back()的行为似乎已发生变化。现在,抛出了InvalidOperationException消息

  

未知错误:无法确定装载状态
  从意外警报打开
       (会议信息:chrome = 53.0.2785.116)
       (驱动程序信息:chromedriver = 2.24.417431(9aea000394714d2fbb20850021f6204f2256b9cf),platform = Windows NT 10.0.10586 x86_64)

此时我正在丢弃此异常,但由于警报,下一个测试将无法运行。具体来说,这意味着我无法顺序运行多个测试。我必须单独运行每个测试,手动确认警报,以便Chrome关闭

我使用的是最新版本的Selenium(2.53.1)并尝试过ChromeDriver 2.22 / 23/24。所有人都有相同的行为。

我知道这里没有人可以控制Chrome,但我想知道是否有其他方法可以用来实现此测试目标,以确保显示脏窗体警报。由于其他一些问题,我无法真正从Chrome更改为其他浏览器。提交表单也是我不想做的事情(如果脏表单没有被触发,它会修改数据库,我不想解决这个问题。)

更新时间:2016-09-22

我现在正在解决以下代码的问题。

try
{
    // Navigate back to the previous page
    d.Navigate().Back();

    try
    {
        IAlert a = d.SwitchTo().Alert();

        // Get the text of the alert or prompt
        System.Diagnostics.Debug.WriteLine(a.Text);
        // And acknowledge the alert (equivalent to clicking "OK")
        a.Accept();
    }
    catch (NoAlertPresentException ex)
    {
        System.Diagnostics.Debug.Write($"Warning: Expected an alert but none was present. {ex.Message}");
    }
}
// Chrome 52: this is how the driver does it now?
catch (InvalidOperationException ex)
{
    if (!ex.Message.Contains("unexpected alert"))
        throw;

    IAlert a = d.SwitchTo().Alert();
    Assert.IsTrue(a.Text.Contains("lose these changes"));

    a.Accept();

    System.Diagnostics.Debug.WriteLine("Handled alert through InvalidOperationException handler.");
}

1 个答案:

答案 0 :(得分:0)

随着ChromeDriver 2.29的发布,这已得到修复。每个ChromeDriver发行说明:

  

修复了在页面卸载时干扰处理警报对话框的错误。

我现在正在运行Chrome 58,并且还更新到最新的Selenium库(3.4.0)。我最初使用的代码(来自原始帖子)现在再次使用。

复制原始代码以供参考:

d.Navigate().Back();

try
{
    // Expecting an alert now
    IAlert a = d.SwitchTo().Alert();

    // And acknowledge the alert (equivalent to clicking "OK")
    a.Accept();
}
catch (NoAlertPresentException ex)
{
    System.Diagnostics.Debug.Write($"Warning: Expected an alert but none was present. {ex.Message}");
}