moveToElement mouse hovering function in Selenium WebDriver using Java not stable - java

I'm using Selenium 3.0.1 for running automation tests using TestNG.
In one test I'm trying to hover on an action menu and then click an option in that menu:
Actions builder = new Actions(getWebDriver());
builder.moveToElement(actionButton).build().perform();
But the test is not stable. I can see the menu opens but immediately closing, so the test fails because it's not finding the option any more.
I'm receiving this error:
java.lang.IllegalArgumentException: Must provide a location for a move action.
at org.openqa.selenium.interactions.MoveMouseAction.<init>(MoveMouseAction.java:30)
at org.openqa.selenium.interactions.Actions.moveToElement(Actions.java:251)
How can I check if the menu is open? the perform() method is returning void.
I notice if I put call the moveToElement twice, than the test is being more stable. Is there any elegant option of doing so?
Actions builder = new Actions(getWebDriver());
builder.moveToElement(actionButton).build().perform();
builder.moveToElement(actionButton).build().perform();
This how the menu looks like when we hover over it:
I find this issue:
https://sqa.stackexchange.com/questions/3467/issue-with-losing-focus-of-hover-command-when-the-mouse-is-outside-of-the-acti
which explains best my problem. unfortunately, still with no solution.

If it is not necessary for you to open the menu, please try clicking the option using JavascriptExecutor. JavascriptExecutor can click a hidden element as well, all that is necessary for the click to be triggered using JavascriptExecutor is that the element is present on the DOM.
Snippet (Java):
((JavascriptExecutor)driver).executeScript("arguments[0].click()", driver.findElement(By.cssSelector("hiddenOptionFromMenu")));

You can wait for the menu to appear after the hover with a FluentWait, like so:
FluentWait<> wait = new FluentWait<>(getWebDriver())
.withTimeout(driverTimeoutSeconds, TimeUnit.SECONDS)
.pollingEvery(500, TimeUnit.MILLISECONDS)
.ignoring(StaleElementReferenceException.class)
.ignoring(NoSuchElementException.class)
.ignoring(ElementNotVisibleException.class)
wait.until(x -> { return driver.findElement(menuElementBy); } );
If the mouse hover succeeded - the menu starts appearing - there's no reason you need to call it twice.

It seems like a timing issue.
If the menu has a transition effect, then add a delay of the duration of the effect:
new Actions(driver)
.moveToElement(menu)
.pause(100) // duration of the transition effect in ms
.perform();
submenu.click();
You could also wait for the targeted element to become visible and steady (same position returned twice in a row).

Related

Selenium stops after click

I'm clicking on OK button. Clicks successfully. After that Selenium is not responding. It is not throwing any exception also. When I close the browser window manually then it tries to continue the execution.
I had the same effect, and so I wrote myself a custom Click() method that I call in such cases.
For Internet Explorer, it does a double-click instead of a click, which seems to be necessary sometimes for Selenium to work.
In Firefox, I occasionally got an exception ("Cannot press more then one button or an already pressed button"), so I wrote the following C# code that explicitly releases the button before pressing it (should look similar in Java):
public static void Click(this IWebElement element, TestParams testParams)
{
if (testParams.Target.IsFirefox)
{
var actions = new Actions(driver);
actions.MoveToElement(element);
driver.Manage().Timeouts().ImplicitlyWait(TimeSpan.Zero);
actions.Release().Build().TryPerform();
driver.Manage().Timeouts().ImplicitlyWait(TimeSpan.FromSeconds(testParams.DefaultTimeoutInSeconds));
actions.MoveToElement(element);
actions.Click().Build().Perform();
}
else if (testParams.Target.IsInternetExplorer)
{
element.DoubleClick(driver);
}
else
{
element.Click();
}
}
This doesn't always work, so I only call my custom Click() method when really necessary. This produces stable results on the sites I usually test.

How to select a hidden dropdown value in Selenium WebDriver using Java

I have a dropdown which is hidden at the moment it loads and with a button click it is set to visible and I can see it when the selenium is running it in the browser but still it gives me this exception
org.openqa.selenium.WebDriverException: ElementNotVisibleError: Element is not currently visible and may not be manipulated'ElementNotVisibleError: Element is not currently visible and may not be manipulated' when calling method: [wdIMouse::click] Command duration or timeout: 47 milliseconds
Can someone suggest how we can resolve this?
Try using Actions and WebDriverWait
Maybe something like this
Actions builder = new Actions(driver);
WebDriverWait wait = new WebDriverWait(driver);
Action clickTheDropDown = builder.moveToElement(dd).Click(otherElement).build();
clickTheDropDown.perform();
wait.Until(Expectedcondition.VisibilityOfElement(dd);

Cannot click element with IEDriverServer

I have an element on a web page that only becomes visible after clicking its parent element. So after clicking a demo in a list of demo's, a row of icons which represent actions for the selected demo is revealed. The following code works fine with both webdriver and chromedriver:
demo.click(); //click demo
waitForElementIsDisplayed(demoReservation_btn); //wait until reservation icon is displayed
demoReservation_btn.click(); //click icon
Originally i was getting a StaleElementReferenceException and i attempted to fix this by having a try/catch block within a while loop that would continue looping until the icon was clicked. This caused IEDriverServer to crash after a couple of loops.
I have also tried wrapping it up in an Action like so:
Action action = new Action(driver);
action.click(demo).click(demoReservation_btn).build().perform()
This results in a NoSuchElementException.
I know there are some problems mentioned in the documentation about browser focus and hovering over elements, but i dont believe this is the problem. I have tried a couple of other things like adding moverToElement to the action, hovering over the element but have had no success with these. I believe one possible solution is to use a javascript executor, but i would like to avoid this approach if possible, any other suggestions?
EDIT
IEDriverServer setup:
File file = new File("IEDriverServer.exe");
System.setProperty("webdriver.ie.driver", file.getAbsolutePath());
driver = new InternetExplorerDriver();
driver.manage().window().maximize();
return driver;
Try disabling Native events of IE
DesiredCapabilities cap = DesiredCapabilities.internetExplorer();
cap.setCapability("nativeEvents",false);
driver = new InternetExplorerDriver(cap);
I had better result using that in C# version. Read this to learn why you may need to do this.

Handle Window Pop Up in Selenium

I am working with Selenium, now there is a condition:
when I hit a button in my webpage a window pop up opens up.
Now I have to click a radio button (one out of two, it will work even if we send a TAB ) and then click an OK button. I searched in the net and got to know about "driver.getWindowHandle()".
But I don't have any idea dealing with the newly opened window popup.
Need help in this.
For switching purpose u can use enhanced for loop:
for (String winHandle : objDriver.getWindowHandles()) {
objDriver.switchTo().window(winHandle);
}
So it will switch the control from one driver window to child windows.
To interact with elements on the window try to find element with whatever tool u r using and perform the required action after switching to the window.
To return back to parent window you can use the same loop or use:
driver.switchTo().defaultContent();
Check my answer in this post and also read the comments to help you understand the difference between getWindowHandle() and getWindowHandles()
Java: focus is not on pop-window during window handling
We handled this situation using AutoItX - https://www.autoitscript.com/site/ in our Windows/IE C# project:
AutoItX3 autoIt = new AutoItX3();
var handle = autoIt.WinWaitActive("[window title]", "", 20);
Assert.IsTrue(handle != 0", string.Format("Was not able to find: {0}", [window title]);
autoIt.Send("{ESCAPE}"); // tab may work as well for selection
The pop up was a Windows window, and not part of IE, therefore the WebDriver didn't know about it.
Hope this helps.

Getting Java Webdriver 'Down Arrow' action to work

So I have been trying to resolve this for several hours. I have no clue what I am doing wrong.
This is a type ahead field I am looking in is <input type="text" id="id_attendees" name="attendees">. When I type in there a js dropdown is created. When I press the Down Arrow on keyboard it works fine and selects the top choice. When I do keyDown --- id=id_attendees --- \40 in IDE it works fine and also selects the choice.
I cannot get it to do the same in Java webdriver though
Actions actionObject = new Actions(driver);
actionObject.sendKeys(Keys.ARROW_DOWN);
^doesn't work.
driver.findElement(By.id("id_attendees")).sendKeys(Keys.ARROW_DOWN);
^doesn't work
I tried Keys.DOWN in both cases, that doesn't work either. I created a literal String altm = "\u0040"; and all that does is type an # symbol.
I also tried a bunch of other things as well and nothing is working. I have no clue what am I missing.
EDIT 1:
#Roddy Thank you! - Given that link I added the following that did work (after importing DefaultSelenium and WebDriverBackedSelenium.
DefaultSelenium sel = new WebDriverBackedSelenium(driver,vars.siteurl);
sel.fireEvent("//input[#id='id_attendees']", "keydown");
EDIT 2:
--> DOH that doesn't work. I got overzealous apparently.
some time scripts takes some time to load the list so need to add wait,
WebElement ar=driver.findElement(By.id("id_attendees"));
Thread.sleep(1000);
ar.sendKeys(Keys.ARROW_DOWN);
I think your use of Actions is not quite right.
The implementation is a builder pattern. Calling sendKeys doesn't send the event, it only stages the event to be fired when you call perform. Note that the return value of sendKeys is an Actions instance.
Actions actionObject = new Actions(driver);
actionObject = actionObject.sendKeys(Keys.ARROW_DOWN); //ASSIGN the return or you lose this event.
actionObject.perform(); //Should do what you want. Note that this will reset the builder.
Hope that helps.
With Actions class, after defining what it will do for you, you need to first build() it. So in your case it would be like this:
Actions actionObject = new Actions(driver);
actionObject.sendKeys(Keys.ARROW_DOWN).build();
When you want your script to execute that action, you need to perform() it. You can chain it right after your build() method (if you are using it just once, for example) or later in your code whenever you need it, like this:
actionObject.sendKeys(Keys.ARROW_DOWN).build().perform();
OR
actionObject.perform();
Good luck!

Categories