It seems that in the ASP.NET WebDriver API, executing the following when there is no javascript alert present results in an exception:
browser.SwitchTo().Alert();
IE and FF both throw a WebDriverException, but Chrome throws an InvalidOperationException.
So far, this is the only code that seems to work:
try
{
var alert = browser.SwitchTo().Alert();
if (alert != null)
alert.Dismiss();
}
catch (WebDriverException)
{
// alert was not present in IE or FF
}
catch (InvalidOperationException)
{
// alert was not present in Chrome
}
Is there a way to check that an alert dialog is present, without having to catch an exception?
The actual answer here is no, you must always catch an exception. The logic behind the design of the API is that you should always be aware of what browser state you expect. If you expect an alert to appear, you should be able to use
switchTo()to switch to it and handle it. If you expect an alert to appear, and useswitchTo()and it is not present, that is an exceptional condition, and an exception is thrown. The normal (non-exceptional) case is to not expect an alert, and thus there is no corresponding method to look for an alert not being displayed. Incidentally, this is the same logic employed byfindElement(). You can argue that the wrong logic is being employed by the API designers, but that is the way the current API is implemented.