I am running with protractor and cucumber. For a number of tests, the outcome is problematic, and will sometimes produce an alert box.
what I'd like to do is in my beginning method for each test, check to see if there is an alert box, and then close/dismiss it. Then continue. The problem I'm facing is, I can't guarantee that there will always be an alert box, and if there isn't one, I get a NoSuchAlertError: no alert open
and the entire script stops.
Is there any way around this?
Current code:
try {
browser.switchTo().alert().dismiss();
}catch(err){
}
driver.switchTo().alert().then(
function (alert) { alert.dismiss(); },
function (err) { }
);
This worked for me. It'll dismiss the alert if it is there, and do nothing if it isn't.
Change dismiss()
for accept()
if you want to accept the alert (OK) instead of dismissing (Cancel).
//dismiss "wrong credentials" alert
browser.driver.sleep(2000);
browser.switchTo().alert().accept().then(null, function(e) {
if (e.code !== webdriver.ErrorCode.NO_SUCH_ALERT) {
throw e;
}
});
This worked for me in Protractor 2.0. I am sure there is a better solution that doesn't involve using sleep(). After a couple hours of frustration, though, I was just happy to see something that worked.
Exception handling from: https://code.google.com/p/selenium/wiki/WebDriverJs
try to override the javascript method to confirm a dialogue if exist
window.confirm = function() { return true; }
this solution works for me with capybara and cucumber
As in https://code.google.com/p/selenium/wiki/WebDriverJs, you could try/catch to handle the alert
try {
driver.switchTo().alert().dismiss();
} catch (NoAlertPresentException ignored) {
}