How can I test context menu functionality in a web app?
I'm playing with a grails app that has a contextmenu开发者_运维百科 (on right-click). The context menu is built using Chris Domigan's jquery contextmenu plugin.
While the contextmenus do actually work, I want to have automated tests, and I can't work out how to do it.
- I've tried Selenium 2.05a (ie. Webdriver), but there's no rightClick method.
- I notice that HtmlUnit has a rightclick method, but I don't seem to be able to detect any difference in the DOM between before the click and after it.
Currently there's no right click method in WebDriver, there's an enhancement request opened for it - http://code.google.com/p/selenium/issues/detail?id=161
For now you can use keyboard shortcut Shift+F10 to simulate the right click on the element:
WebElement element = driver.findElement(....);
element.sendKeys(Keys.chord(Keys.SHIFT, Keys.F10));
While I'd like to be able to do it in Internet Explorer or Firefox as well, the main usage will be HtmlUnit. It's nice that the HtmlUnit HtmlElement has a rightClick()
method, but unfortunately it's protected
and so not accessible from the WebDriver wrapped HtmlUnitWebElement.
I wrote a hack to make it accessible, and so now I can call rightClick(), although it only works if it's running with HtmlUnit - not IE or FF.
// Needs to be in this package to get access to the element
package org.openqa.selenium.htmlunit;
import com.gargoylesoftware.htmlunit.html.HtmlElement;
public class OpenHtmlUnitWebElement extends HtmlUnitWebElement {
// Provide a constructor, even though we don't really need it.
public OpenHtmlUnitWebElement(HtmlUnitDriver parent, HtmlElement element) {
super(parent, element);
}
// this is the method we really want.
public static HtmlElement using(HtmlUnitWebElement huwe) {
return huwe.element;
}
}
Now my (groovy) test looks like this:
import static org.openqa.selenium.htmlunit.OpenHtmlUnitWebElement.using
...
def itemWithContextMenu = driver.findElement(By.id('theId'))
if (itemWithContextMenu instanceOf HtmlUnitWebElement) {
using(itemWithContextMenu).rightClick()
def contextMenu = driver.findElement(By.id('jqContextMenu'))
assert ...
}
if you use Ruby with Capybara, this one should be useful:
module Capybara
module Node
class Element
def context_click
@session.driver.browser.action.context_click(self.native).perform
end
end
end
end
精彩评论