Search code examples
javagoogle-chromeseleniummouseoveropera

Mouseover function with Selenium Webdriver does not work with Opera 39 and works inconsistently with Chrome 53


I'm trying to write Webdriver tests where I need to hover the mouse cursor over an element to trigger a drop down menu, and then click a button from the drop down menu. I've been writing my code following the suggestion from How to perform mouseover function in Selenium WebDriver using Java?. So for example, my code might look like this :

Actions action = new Actions(webdriver);
WebElement hoverElem = webdriver.findElement(By.xpath("//html/body/div[13]/ul/li[4]/a"));
WebElement clickElem = webdriver.findElement(By.xpath("//html/body/div[3]/li[12]/a"));
action.moveToElement(hoverElem).moveToElement(clickElem).click().build().perform();

My code runs perfectly when I test it in Firefox, but in Chrome it's inconsistent; sometimes it will work perfectly, and then the next time I run the test it will fail. In Opera it never works. When the code fails, it looks like the drop down menu appears for a split second on the screen, then disappears before WebDriver can click on the button on the drop down menu. I'm not sure how I can fix this problem. How can I get this to work with all 3 browsers?

As a reference, I'm using selenium-2.53.0, Chrome 53.0.2785.101 64-bit, and Opera 39.0.2256.71 64-bit.


Solution

  • In case anyone finds this in the future and is confused about why the mouse-over function works inconsistently with Chrome, Opera, or Internet Explorer, here is why:

    The code I have above is correct. The problem is that for whatever reason, mouse over with Chrome, Opera, and IE doesn't work if the mouse cursor is on the browser window while the test is running (this may be an issue within the driver for each of these browsers).

    To get around this, you need to ensure the mouse cursor is outside of the browser window while you run tests. I did this by leaving a pixel or two of space on the bottom of the screen when maximizing the browser window, and then using the java.awt.Robot class to move the mouse cursor to the bottom of the screen where the mouse would not interfere with the tests.

    Below is an example for my monitor (which is 1680 x 1050, so I leave 40 pixels of space at the bottom of the screen):

        driver.manage().window().setPosition(new Point(0, 0));
        org.openqa.selenium.Dimension d = new org.openqa.selenium.Dimension(1680, 1010);
        driver.manage().window().setSize(d);
    

    To move the cursor out of the way:

        Robot robot = new Robot();
        robot.mouseMove(0, 1050);
    

    You can call the above whenever you need to reset the mouse cursor to the bottom, for whatever reason.