4

Using selenium web-driver API in headless mode, I am trying to perform a mouse-hover on a menu item; so that all the sub menu items show up. After that, I click one of the sub menu items. The following is the code snippet:

Actions actions = new Actions(driver);
WebDriverWait wait = new WebDriverWait(driver, 20);

//Waiting for menu item to be clickable
wait.until(ExpectedConditions.elementToBeClickable(By.cssSelector(menu_item)));
WebElement firstLink = driver.findElement(By.cssSelector(menu_item));
//Hovering over the menu item
actions.moveToElement(firstLink).build().perform();
//Waiting for the sub-menu item to be clickable - ERRORS OUT HERE
wait.until(ExpectedConditions.elementToBeClickable(By.cssSelector(submenu_item)));
//Getting the second link
WebElement secondLink = driver.findElement(By.cssSelector(submenu_item));
//Click on sub menu
actions.moveToElement(secondLink).click().build().perform();

However, the test times out saying that the sub menu item could not be found.

I've verified that the above works perfectly fine with the Firefox driver. Also, the css selectors are proper.

Are there any known issues with PhantomJs and mouse hover actions - which might explain why the code does not run with the PhantomJs driver. If so, is there any work-around for the same.

Also, is there a better way to sequence the APIs to simulate the mouse-hover-and-then-click action?

(Note: I also tried chaining the operations as mentioned in How to perform mouseover function in Selenium WebDriver using Java?, but it didn't help)

4

1 回答 1

0

尝试使用非本地 JavascriptExecutor:

public void mouseHoverJScript(WebElement HoverElement) {
            String mouseOverScript = "if(document.createEvent){var evObj = document.createEvent('MouseEvents');evObj.initEvent('mouseover', true, false); arguments[0].dispatchEvent(evObj);} else if(document.createEventObject) { arguments[0].fireEvent('onmouseover');}";
            ((JavascriptExecutor) driver).executeScript(mouseOverScript,
                    HoverElement);
}
于 2016-02-11T09:10:05.753 回答