0

Suppose you have:

<form>
    <input type="text" id="tbInput" text="foo" />
</form>

It turns out somebody wrote the following code:

$("#tbInput").on("keypress", function (e) {
    if (e.keyCode == 13) {
        // bad code!
        e.preventDefault();
    }
}

This is not the desired behavior, as pressing enter to submit a form is often what the user wants to happen.

How can I test that pressing enter on #tbInput causes the form to submit during an automated test?

(I haven't figured out a way to simulate a keypress event that will cause a form submit.)

jsFiddle link Have at it!

dx_over_dt
  • 103
  • 4

1 Answers1

0

What tool are you using to interact with the DOM? If you are using selenium, ENTER is an available keypress event that you can trigger on a particular element: http://selenium.googlecode.com/svn/trunk/docs/api/java/org/openqa/selenium/Keys.html.

If you are testing with javascript, you can trigger a keypress directly:

var e = $.Event('keypress');
e.which = 13;
$('form').trigger(e);

EDIT --

In response to comment below, I see what you're getting at. I suspect that browsers specially handle that case of enter on a form field and fire a form submission event (after the keypress event has been evaluated)? So I don't think you can really emulate that behavior purely with javascript (though I may be wrong). I ran a quick test with selenium (which has as close to "native" browser events as you can get) and got the behavior you're looking for:

>>> from selenium import webdriver
>>> ff = webdriver.Firefox()
>>> ff.get('file:///home/justin/Desktop/test.html')
>>> from selenium.webdriver.common.keys import Keys
>>> el = ff.find_element_by_css_selector('#tbInput')
>>> el.send_keys(Keys.ENTER)
# Alert popped up twice!

If you expect to be doing more UI testing along these lines, the investment in selenium might be worth it.

Justin
  • 188
  • 1
  • 5
  • I've been using javascript (with QUnit). I'll look into Selenium. I copied and pasted your js code into my jsfiddle. Triggering the event didn't work on neither $('form') nor $(#tbinput). If I added e.keyCode = 13, I could get the keypress event to fire on #tbInput, but the form's submit event still did not fire. – dx_over_dt Mar 26 '15 at 16:23