Selenium c# accept confirm box - c#

I have written an nUnit test using selenium in c#.
All was going well until I have to confirm a JS confirm box.
here is the code I am using:
this.driver.FindElement(By.Id("submitButton")).Click();
this.driver.SwitchTo().Alert().Accept();
The confirm box appears after the submit button. The confirm appears and then disappears immediately but the form does not submit. The behaviour is the same regardless of the accept() line above.
I am using Firefox v15.0.1 and selenium v2.24
I have tried putting a Thread.Sleep between the submit click and the confirm accept.
Everything I have read has said that the selenium driver will automatically send a confirm OK, but something else seems to be happening.

in this issue i would try to verify confirm box presence.
it be something like:
this.driver.FindElement(By.Id("submitButton")).Click();
boolean presentFlag = false;
try {
// Check the presence of alert
Alert alert = driver.switchTo().alert();
// Alert present; set the flag
presentFlag = true;
// if present consume the alert
alert.accept();
} catch (NoAlertPresentException ex) {
// Alert not present
ex.printStackTrace();
}
return presentFlag;
}
then if doen't work. try to debug step by step.
some additional info concerning alert ( confirm boxes) handle in selenium here
hope this somehow helps you

You just need:
IAlert alert = driver.SwitchTo().Alert();
alert.Accept();

The end point I am testing does not have reliable response times and the only way I could get it to always work with webdriver selenium-dotnet-2.33.0 (.NET4) using Firefox was by doing the following:
private void acceptAlert(){
string alertText = "";
IAlert alert = null;
while (alertText.Equals("")){
if (alert == null)
{
try{
alert = driver.SwitchTo().Alert();
}
catch{
System.Threading.Thread.Sleep(50); }
}
else{
try{
alert.Accept();
alertText = alert.Text;
}
catch (Exception ex){
if (ex.Message.Equals("No alert is present")) alertText = "Already Accepted";
else System.Threading.Thread.Sleep(50);
}
}
}
}

Related

Unable to detect login alert using selenium web driver

I'm developing an automation testing project on http://the-internet.herokuapp.com/ website using C# and NUnit.
While testing the presence of the below alert on the page http://the-internet.herokuapp.com/basic_auth, the web driver is not able to detect the alert on the page though it is present. It is continuously giving NoAlertPresentException.
I'm using the code given below to detect the alert
Internal WebDriver wait = new WebDriverWait(driver, TimeSpan.FromSeconds(10));
internal void WaitUntilAlertIsVisible()
{
try
{
wait.Until(SeleniumExtras.WaitHelpers.ExpectedConditions.AlertIsPresent());
}
catch(WebDriverTimeoutException)
{}
}
internal bool IsAlertPresent()
{
try
{
WaitUntilAlertIsVisible();
driver.SwitchTo().Alert();
return true;
}
catch(NoAlertPresentException)
{
return false;
}
}
Please help!

How do I pass the C # Selenium Error Page?

I'm writing a bot with c # selenium. (The working logic of the bot is simply that there are 20 companies on each page, they go back to the detail page and get the data back. They go through all the companies in order. After getting the data of the last company, they continue to the next page.) After visiting 200-250 companies, the page in the picture opens. Bot's stopping progress. If I press the F5 menu manually, the bot continues to progress, but it doesn't work when we try with the code.
How do I resolve this error?
Error Page
I noticed it was on the way back from the detail page of this page. To go back;
driver.navigate().Back();
driver.navigate().GoToUrl("");
//I tried to go back with the codes but the solution was not.
I get this Error because the error page does not pass.
Bot needs to visit all companies without encountering an error page.
A correct approach for this is to wait for some amount of time for some element you expect on the page using WebDriverWait.
In this example, I wait for 10 seconds and look for element id 'some-id'.
You can change the criteria by replacing By.Id("some-id") with some other condition.
More about By class.
var wait = new WebDriverWait(driver, TimeSpan.FromSeconds(10));
driver.Navigate().GoToUrl("https://www.somedomain.com");
var validPage = false;
try
{
validPage = wait.Until(c =>
{
try
{
return driver.FindElement(By.Id("some-id")) != null;
}
catch
{
return false;
}
});
}
catch
{
// not exist
}
if (validPage == true)
{
// ok.
}
else
{
}

How to catch the error page in a website which throw System Error /Server Error In Selenium Webdriver c# and fail in my test case Nunit

I have been trying to find ways to catch this error in my selenium webdriver c#.Is any method which will catch this error in my test case ? There is system error or Server Error but I am unable to retrieve my error and fail my test cases. All my test cases which have these error (System/Server) end with the result = "Test Passed" instead of showing of the Error.
Eg: Click to View ServerError
Eg: Click to View System Error
[Test]
public void TestYamaha()
{
driver = new ChromeDriver();
driver.Navigate().GoToUrl("http://192.161.0.1/iels-admin-dev/Login/Login.aspx");
driver.Manage().Window.Maximize();
driver.Manage().Timeouts().ImplicitWait = TimeSpan.FromSeconds(5);
driver.FindElement(By.Id("ctl00_MainContent_ucLogin_txtUserID")).Click();
driver.FindElement(By.Id("ctl00_MainContent_ucLogin_txtUserID")).Click();
driver.FindElement(By.Id("ctl00_MainContent_ucLogin_txtUserID")).SendKeys("manteng");
driver.FindElement(By.Id("ctl00_MainContent_ucLogin_txtPassword")).SendKeys("Nic15742368");
driver.FindElement(By.Id("ctl00_MainContent_ucLogin_cmdLogin")).Click();
Thread.Sleep(2000);
driver.Navigate().GoToUrl("http://192.161.0.1/iels-admin-dev/Announcement_News/Announcement_News_Search.aspx");
Thread.Sleep(2000);
driver.FindElement(By.CssSelector(".ui-datepicker-trigger:nth-child(2)")).Click();
Thread.Sleep(2000);
driver.FindElement(By.CssSelector(".ui-icon-circle-triangle-w")).Click();
Thread.Sleep(2000);
driver.FindElement(By.LinkText("1")).Click();
Thread.Sleep(2000);
driver.FindElement(By.Id("ctl00_MainContent_cmdSubmit")).Click();
Thread.Sleep(2000);
driver.FindElement(By.CssSelector(".clsDataGridAltData a:nth-child(2) > img")).Click();
Thread.Sleep(2000);
driver.FindElement(By.Id("ctl00_MainContent_cmdSubmit")).Click();
Thread.Sleep(2000);
}
This code shows System Error (As shown in the picture) but how I show in my test case.
Use try-catch block to handle any exception and if required then you can log it in catch block. You should use any assertion library for making it pass/fail.
Note: Don't write everything into Test class.
I can only think of if the URL contain "Error", it will screenshot and fail the test case .
if (url.Contains("error") || url.Contains("Error") == true)
{
Base.ErrorMessage(driver, element); // screenshot the page
throw new SystemException("Webpage throw error");
//Console.WriteLine("Got");
}
else
{
Console.WriteLine("Passed");
}
}

Unhandled Alert Exception in selenium, c#

I am new to Selenium, and I am trying to verify that if user has successfully landed on the Home page or not. Here is the snippet:
LoginPage.GoTo();//Goes Well
LoginPage.LoginAs("UserName").WithPassword("Password").Login();//goes Well
Assert.IsTrue(HomePage.IsAt, "Failed to login");//Below is the implementation of HomePAge.IsAt
public static bool IsAt
{
get
{
var wait = new WebDriverWait(Driver.Instance, TimeSpan.FromSeconds(5));
wait.Until(x => x.SwitchTo().ActiveElement().GetAttribute("id") == "IDHere");//Here the exception is occuring.
}
var homePage = Driver().Instance.FindElement(By.Id("IDHere"));
// return true or False;
Can someone please help?
When an alert is present on your browser, it prevents you from actually doing ANYTHING else.
FYI, when I try to run my application, a window authentication pop up
comes and after that Page loads.
Well, yeah. That's the alert part from "Unhandled Alert Exception". The unhandled part, is because you didn't use any line of code to show your program how to handle the alert. Selenium goes to login page. Then tries to run this line x.SwitchTo().ActiveElement().GetAttribute("id") == "IDHere", but there is an alert on your page that prevents you from doing anything.
You have to actually try to handle it (close it or accept the message) and THEN do anything else.
It might be considered a good practice to wait for your alert to appear (since it might not appear instantly), and then, after (e.g.) 5 seconds, if there is no alert, run your code.
Try the code below to see if it resolves your problem:
public static boid WaitForAlert(bool accept)
{
//Initialize your wait.
WebDriverWait wait = new WebDriverWait(Driver.Instance, TimeSpan.FromSeconds(5));
//Wait for alert
try
{
wait.Until(ExpectedConditions.AlertIsPresent());
if (accept)
{
Driver().Instance.SwitchTo().Alert().Accept();
}
else
{
Driver().Instance.SwitchTo().Alert().Dismiss();
}
}
catch (WebDriverTimeoutException) { /*Alert did not appear, do nothing*/ }
}
And then do:
LoginPage.GoTo();
LoginPage.LoginAs("UserName").WithPassword("Password").Login();
LoginPage.WaitForAlert(true); //True to accept the alert
Assert.IsTrue(HomePage.IsAt, "Failed to login");

Handling Alert dialog Box in Selenium IE using C#

I am automating some tests for a webapp written in ASP.NET MVC5 that also uses jQuery. I've been looking around for options on handling an alert confirmation box while using Selenium in IE.
I need to confirm the message on the box, but I do not need to click anything on the dialog. Here is what I have now:
public bool IsAlertPresentAndCorrect(string Message)
{
try
{
WebDriverWait Wait = new WebDriverWait(Driver, System.TimeSpan.FromSeconds(10));
Wait.Until(ExpectedConditions.AlertIsPresent());
ReadOnlyCollection<string> Handles = Driver.WindowHandles;
string ToUse = "";
foreach (string Handle in Handles)
{
if (!Driver.CurrentWindowHandle.Equals(Handle))
{
ToUse = Handle;
}
}
IAlert Alert = (IAlert) Driver.SwitchTo().Window(ToUse);
return Alert.Text.Equals(Message);
}
catch (NoAlertPresentException)
{
return false;
}
finally
{
_driver.SwitchTo().DefaultContent();
}
}
I have also tried IAlert Alert = Driver.SwitchTo().Alert() and IAlert Alert = Driver.SwitchTo().ActiveElement() in place of getting the window handle but they are not working either.
The problem has been the exact same no matter what code I use: OpenQA.Selenium.UnhandledAlertException: Modal dialog present.
Any help would be greatly appreciated
Alert in Chrome:
Alert in IE:
In case of alert you don't necessarily have to switch back to the window handle. You can simply switch to alert, perform necessary operation, close the alert.
I modified your code a bit to fetch the alert text in a variable, close the alert pop-up then compare the alert text with the message passed in parameter and return bool value.
public bool IsAlertPresentAndCorrect(string Message)
{
try
{
WebDriverWait Wait = new WebDriverWait(Driver, System.TimeSpan.FromSeconds(10));
Wait.Until(ExpectedConditions.AlertIsPresent());
string alertText = Driver.SwitchTo().Alert().Text;
Driver.SwitchTo().Alert().Accept();
return alertText.Equals(Message);
}
catch (NoAlertPresentException)
{
return false;
}
}

Categories

Resources