Notification(Alert) comes randomly throughout application in selenium webdriver - java

I am using selenium webdriver with Java language. I am facing an issue that notification alert appears randomly through out application. Basically these alert have some information as it is functionality .
As script performs its steps but suddenly these alert appears on the screen and my script would fail due to alert message.
Please give your suggestions, How can we handle this type of alert which appears randomly on any window?
Below are two points come in my mind to handle this scenario:
I will check Alert appears or not at every step (after click or
other action) but it increases my execution time.
Is there any way, we keep monitoring that Alert appears or not. If
Alert appears just close the Alert if not then keep execute the
steps of scripts.
Please suggest any workaround to handle such Alert so that our scripts do not fail.
This is the same scenario that we automate mobile application using Appium tool and suddenly any advertisement come on the screen.
It would be good if any one provide java code to handle this type of scenario.
Thanks in advance!!

If you want that unnecessary alert not appear during your script execution you can override you alert function before executing your script by using JavaScriptExecutor as below :-
JavascriptExecutor executor = (JavascriptExecutor)driver
executor.executeScript("window.alert = function () { return true}");
You can execute this script once every time when your page is loaded. this script will override your alert functionality and the alert will never occur.
I suggest you this script run when if your test is not depend on alert because after execute this script the alert will not be appear on the page.
other than you can handle alert as below :-
WebDriverWait wait = new WebDriverWait(driver, 100);
wait.until(ExpectedConditions.alertIsPresent());
Alert alert = webDriver.switchTo().alert();
Now if you want to accept alert, you can use :-
alert.accept();
and for cancel, you can use :-
alert.dismiss();
Note :- if alert is not present by using WebDriverWait it will throw TimeoutException.. so you need to handle it.
Edited..
For Appium automation to solve this problem, you can use a desired capability specifically designed to handle these alerts.
You can either always accept or always dismiss the alerts with these desired capabilities :-
autoAcceptAlerts = true
...
capabilities.SetCapability("autoAcceptAlerts", true);
or
autoDismissAlerts = true
...
capabilities.SetCapability("autoDismissAlerts", true);
Furthermore, some of the older versions of Appium haven’t worked with this solution, so you might want to try a small workaround with this :-
driver.SwitchTo().Alert().Accept();
For more info follow this
Hope it will help you..:)

You can call this method wherever you are getting the alert.This method will accept the alert.
public void checkAlert(){
if(ExpectedConditions.alertIsPresent() != null){
driver.switchTo().alert().accept();
}
}

Related

How to automate test cases for a dialog box message using selenium web driver

I am actually new to selenium web driver and stackoverflow. I am working on automating test cases for a 'forgot password' feature which has a dialog box when unregistered email address is entered.
I want to validate the message 'This email is not registered!' in the dialog box ,but not sure how to proceed as i am using xPath which keeps changing for the message 'This email is not registered'.
This email account is not registered!
#Test
public void checkForgotPasswordWithInvalidCredentials() throws Exception {
driver.findElement(By.xpath(".//*[#id='forgetBtn']")).click();
driver.findElement(By.xpath(".//*[#id='emailInput']")).sendKeys("test#test.com");
driver.findElement(By.xpath(".//*[#id='verify_btn']")).click();
Thread.sleep(5000);
driver.findElement(By.xpath(".//*[#id='alert_box_14']/p")).isDisplayed();
}
In the above code, the Xpath for the alert message(.//*[#id='alert_box_14']/p) keeps changing.
Any help would be appreciated. Thanks!
If the number keep changing you can use partial id
driver.findElement(By.xpath(".//*[contains(#id, 'alert_box')]/p")).isDisplayed();

Selenium RemoteWebDriver - Do something if element could not be found

I am trying to develop a Suite of classes for testing my websites functionality every night and I do this in Chrome, Firefox, Edge and IE. Because sometimes Selenium doesn't find an element I need something that e.g. takes a screenshot of the browser before giving out an error. I don't need a function for taking a screenshot I need something that triggers when Selenium can't continue.
Best regards,
MK
If I understand correct, you need to set up the trigger for your another system, which can react on Selenium test error.
In your test code you can use :
try {
// find element and test code
} catch (NoSuchElementException e) {
// set up the trigger code
}
To notify another system you can choose any system, which can provide notification mechanism.
In your case, you could use for example Redis with pub/sub.
So your reaction system will be a subscriber and test - provider of the event.

Selenium catch popup on close browser

I'm trying to test that when I close my window a popup shows with a warning message.
I've tried both driver.close() and driver.quit() after making sure I'm on the proper window but this just terminates the process since my popup doesn't show.
I could test it by using the awt Robot and sending alt+f4 but this doesn't seem too reliable.
What would be the proper way to do this?
Instead of using driver.quit() to close the browser, closing it using the Actions object may work for you. This is another way to close the browser using the keyboard shortcuts.
Actions act = new Actions(driver);
act.sendKeys(Keys.chord(Keys.CONTROL+"w")).perform();
Or, if there are multiple tabs opened in driver window:
act.sendKeys(Keys.chord(Keys.CONTROL,Keys.SHIFT+"w")).perform();
You need to switch into the alert if the alert is displayed accept or dismiss it and then call driver.quit();
if(driver.switchTo().alert() != null)//switches only if alert is displayed
{
Alert alert = driver.switchTo().alert();
alert.dismiss(); // alert.accept();
}
driver.quit();
Hope this helps you...kindly get back if it is not working for you

Java Selenium: How is it possible to get a NoAlertPresentException from inside a UnhandledAlertException handler?

I am using Java selenium in order to control a browser (open up webpages, delete cookies, etc). Whenever I have an alert, I dismiss it as follows:
try
{
webDriver.someFunc();
}
catch (UnhandledAlertException error)
{
webDriver.switchTo().alert().dismiss();
}
Then, in some cases I get a NoAlertPresentException thrown when trying to dismiss the alert.
I do not understand, how is it possible that I get a NoAlertPresentException thrown from inside a UnhandledAlertException handler?????
Thanks
I too am getting the same error,but am unable to figure out why?
I tried this:
try
{
webDriver.someFunc();
webDriver.switchTo().alert().dismiss();
}
catch (UnhandledAlertException error)
{
//Ignore
}
This should work.
Problem with your code probably is:
suppose you click on some button which opens an alert and you have put that in try block.As soon as unhandledalertexception is triggered(when alert is opened) it automatically dismisses your alert so that the next statement becomes invalid so the statement you have defined in catch block becomes invalid and it shows No alert found exception as the alert has already been dismissed.
But am still trying to figure out why unhandledalert exception is triggered at the first place.It is triggered all of a sudden for some alerts and doesnot show for all alerts.
I hope this clarifies.
Firstly, i must say, that the concept of unhandled alert makes no sense to me, because alerts are triggered by actions. If you don't understand how the alert is triggered, you should discuss this with your developers and handle it the right way. That being said, take a look into DesiredCapabilities -> CapapilityType -> UNEXPECTED_ALERT_BEHAVIOUR

MessageBox with timeout in Selenium

After writing some automated tests with selenium, I want a message box
telling the testers which test is launched.
It is important, that the test must not run when the messagebox is shown.
They should be paused when the messagebox is shown.
I did this by JavaScript
Object result = ((JavascriptExecutor)TestRunner.driver).executeScript("alert('" + text + "');");
Now I want this messagebox to be shown some seconds. I tried:
TestRunner.driver.manage().wait(10);
And
Selenium selenium = new WebDriverBackedSelenium(TestRunner.driver, TestRunner.driver.getCurrentUrl());
selenium.start();
selenium.getConfirmation();
And
WebDriverWait waitForOkay = new WebDriverWait(TestRunner.driver, 10);
waitForOkay.wait(10);
But the alert always immediately disapears, just like there is some
alert.accept();
Is there any way to have a messagebox that is either clicked "Ok" or
some timeout (e.g. 10 seconds) to not block automated tests?
Any input (like other ways to achieve that) very welcome!
A wait condition is unnecessary in this situation, since by Default the JavaScript alert box.... blocks the execution till you click on "Ok" button.
I tried with sample code (C# snippet) and it was working.
IWebDriver driver = new InternetExplorerDriver();
driver.Navigate().GoToUrl("http://www.google.com");
IJavaScriptExecutor js = (IJavaScriptExecutor)driver;
driver.Manage().Timeouts().SetScriptTimeout(TimeSpan.FromSeconds(4));
Console.WriteLine("Entering the Sync Call");
js.ExecuteScript("alert('"+ Error+"');");
Console.WriteLine("Exiting the Sync Call");
I hope this helps...All the Best :-)

Categories