Friday, November 14, 2008

ENTER key press in Selenium

Mike Gage needed to simulate an ENTER key press in Selenium to call a submit. Erstwhile Asynchronite Ryan Tyer provided some helpful feedback via Twitter (we're gonna miss him!):
In selenium, there is a submit function. This submits the form without using a submit button, same as an enter key press. [And in a followup:] Further, you should be able to simulate an enter key press with rc (java) selenium.keyDown(id, "\\13");
Mike specifically wanted to make sure that the ENTER did something, which meant that he didn't want to use the submit function in Selenium. Here's what worked for him, using Ryan's approach (only with KeyPress) -- in Firefox, at least:
public void EnterKeyPressedOnTextAreaTriggersSubmit()
selenium.Type("quicksearchtextcriteria", "text");
selenium.KeyPress("quicksearchtextcriteria", "13");

Assert.IsTrue(selenium.IsTextPresent("We could not find an exact match for your Quick Search entry"));


SuperWes said...

This same project had the same bug show up 9 months later. When searching for a solution this was the first result and it didn't help so I figured I'd post here to give help to anyone who needs it.

The above test works fine in Firefox, but it won't work in IE7. To press the enter button in IE7, the test will need to look like this:

selenium.Type("quicksearchtextcriteria", "0015884");
Assert.Equal("Spectacular Limestone Mansion", selenium.GetText("pageHeading"));

Selenium isn't set up to handle how IE processes text entry so you'll need to give the field itself focus and then send the KeyPress for Enter.

harish said...

Can you please provide the HTML code for the same, as it does not supprt KeypressNative command.


Re@PeR said...
This comment has been removed by the author.
Re@PeR said...

For firefox in windows you need to use keydown and in linux you need to use keypress.

[python selenium code]

def press_special_key(self, element, key):
keys = {"enter": "\\13"}
# press key in windows
self.sel.key_down(element, keys[key])
self.sel.key_up(element, keys[key])
# press key in linux
self.sel.key_press(element, keys[key])

[/python selenium code]

Allinn1 said...

How can i achieve the same using WebDriver (Firefox & HtmlUnitDriver)?

Mahesh didugu said...

In WebDriver you can use

sendKeys(Keys.RETURN) function which is located in the package org.openqa.selenium.Keys