Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I reliably wait for JavaScript alerts using Selenium2 / WebDriver?

I am currently assisting in a proof of concept using Selenium 2 / WebDriver with C# against an ASP.NET MVC application using the InternetExplorerDriver.

The application uses a standard pattern for notifying users that a record has saved. This works by settings TempData to include "Record saved successefully", and if TempData is present in the View, the view will alert the message.

Whilst working on Selenium tests for this functionality, we are receiving inconstitant behaviour from the below C# / Selenium test code:

        _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")); 

Approximately 50% of the time, Selinium will fail with a

OpenQA.Selenium.NoAlertPresentException : No alert is active

I struggle to find an exact way to replicate the issue, and worry regarding the inconsistency aspect. If it failed consistently, then we could debug and track the problem down.

like image 565
Paul Williams Avatar asked Nov 29 '11 12:11

Paul Williams


1 Answers

Hope this will be helpful for waiting and click

WebDriverWait(driver,4).until(EC.alert_is_present())
driver.switch_to.alert.accept()
like image 110
Hietsh Kumar Avatar answered Nov 05 '22 07:11

Hietsh Kumar