Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to handle the "unexpected alert open"?

Tags:

java

selenium

I got an issue with Selenium throwing timeout exception because of a pop up window

  unexpected alert open
  not provide any stacktrace information)
  Command duration or timeout: 5 milliseconds

The alert has OK and CANCEL buttons. I know two ways to handle this


The first way is reopen a new session

driver.quit();
driver = new ChromeDriver();

Second way is using Robot class

Robot r = new Robot();
r.keyPress(KeyEvent.VK_ENTER);
r.keyRelease(KeyEvent.VK_ENTER);

However, this methods are not time efficient. Is there any better way?

like image 777
Buras Avatar asked Oct 04 '13 04:10

Buras


2 Answers

This should do the trick:

driver.switchTo().alert().accept();
like image 177
Nathan Merrill Avatar answered Sep 21 '22 05:09

Nathan Merrill


Methods to handle alerts in Selenium

  1. Decide on each individually

If you need to take action on each alert in your tests individually, the driver gives you the option to switch to the alert and decide to either accept or dismiss it.

driver.switchTo().alert().accept();

  1. Handle by default setup

When you want all the alerts handled in the same way, you can set a global capability at the start of the test execution to ACCEPT, INGORE or DISMISS alerts by default when they appear.

capabilities.setCapability(CapabilityType.UNEXPECTED_ALERT_BEHAVIOUR, UnexpectedAlertBehaviour.ACCEPT);

  1. Using Robot class

Alternatively, you could use Robot class to send an Enter key event, which would accept the alert.

Robot r = new Robot();
 
r.keyPress(KeyEvent.VK_ENTER);
r.keyRelease(KeyEvent.VK_ENTER);

like image 34
cogitovirus Avatar answered Sep 21 '22 05:09

cogitovirus