简体   繁体   中英

Selenium c# accept confirm box

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);
}
}
}
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM