How can I test context menu functionality in a web app?

早过忘川 提交于 2019-12-05 12:31:54

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
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!