如何使用Selenium2 / WebDriver可靠地等待JavaScript警报?

时间:2011-11-29 12:17:22

标签: automated-tests webdriver selenium-webdriver

我目前正在协助使用Selenium 2 / WebDriver和C#对使用InternetExplorerDriver的ASP.NET MVC应用程序进行概念验证。

应用程序使用标准模式通知用户记录已保存。这可以通过设置TempData来包含“Record saved successcessefully”,如果View中存在TempData,视图将提醒消息。

在使用Selenium测试此功能的同时,我们从以下C#/ Selenium测试代码中获得了不一致的行为:

        _driver.Navigate().GoToUrl(_baseUrl + "/Amraam/List");
        _driver.FindElement(By.LinkText("Create New")).Click();

        _driver.FindElement(By.Id("txtAmraamSerialNumber")).SendKeys("CC12345");

        var selectElement = new SelectElement(_driver.FindElement(By.Id("LocationId")));
        selectElement.SelectByText("Tamworth");
        _driver.FindElement(By.Id("btnSave")).Click();
        var wait = new WebDriverWait(_driver, defaultTimeout);
        IAlert alert = wait.Until(drv => drv.SwitchTo().Alert());
        _alertText = alert.Text;

        alert.Accept();
        Assert.That(_alertText, Is.EqualTo("Record successfully saved")); 

大约50%的时间,Selinium将失败

OpenQA.Selenium.NoAlertPresentException:没有警报处于活动状态

我很难找到复制问题的确切方法,并担心不一致方面。如果它一直失败,那么我们就可以调试并跟踪问题。

2 个答案:

答案 0 :(得分:15)

Selenium 2中警报和提示的处理非常新,并且仍在积极开发中。 您的失败可能是由于时间问题,所以我建议围绕调用SwitchTo()。Alert()编写一个包装器方法,以便捕获OpenQA.Selenium.NoAlertPresentException并忽略它直到超时到期。

这样简单应该有用:

private IAlert AlertIsPresent(IWebDriver drv)
{
    try
    {
        // Attempt to switch to an alert
        return drv.SwitchTo().Alert();
    }
    catch (OpenQA.Selenium.NoAlertPresentException)
    {
        // We ignore this execption, as it means there is no alert present...yet.
        return null;
    }

    // Other exceptions will be ignored and up the stack
}

这一行

IAlert alert = wait.Until(drv => drv.SwitchTo().Alert());
然后

将成为

IAlert alert = wait.Until(drv => AlertIsPresent(drv));

答案 1 :(得分:0)

希望这有助于等待并单击

WebDriverWait(driver,4).until(EC.alert_is_present())
driver.switch_to.alert.accept()
相关问题