Possible to test the result of an input keypress handler?

1,064 views
Skip to first unread message

David Karr

unread,
Oct 15, 2013, 3:57:33 PM10/15/13
to jasmi...@googlegroups.com
I have a function which takes an element and assigns a keypress event handler to it.  The event handler returns false if any keypress does not match a particular regexp.  It is intended to take input elements as its argument.

I'm trying to see if I can write a test for this, showing that if I simulate a keypress it should accept, then the character would be added to the input value, and not if it's a keypress that it should not accept.

I'm trying to create the fixture inline in the test, and pass that fixture through jquery to the method under test.

I've read numerous articles about how to simulate an event, and they're all pretty different, and of various ages.

The function I want to test is like this:
COMP.util.validateAlphaNumber = function(field) {
jQuery(field).keypress(function(e){
var character,
   re = /^[0-9a-zA-Z\s]+$/;
if (!e){
e = window.event;
}
if (e.which !== 0 && e.charCode !== 0) {
character = String.fromCharCode(e.keyCode||e.charCode);
}
if (!re.test(character)) {
return false;
}
});
};

My test so far looks like this:
define(['jquery', 'COMP.util'], function($, ign) {
describe("COMP.util", function(){
var fixture;
beforeEach(function() {
$('#fixture').remove();
$('body').append("<input id='fixture' type='text'/>")
spyOn($, "ajax").andCallFake(function(params){
params.success({});
});
});
it("validateAlphaNumber only allows alphanumeric characters", function() {
COMP.util.validateAlphaNumber($('#fixture'));
var evt = $.Event("keydown");
evt.which = evt.keycode = 50; // Should be "2"
$('#fixture').trigger(evt);
var fieldValue = $('#fixture').val();
console.log("fieldValue[" + fieldValue + "]\n");
});
});
});

The log statement is printing an empty string for "fieldValue".

Sheel Choksi

unread,
Oct 17, 2013, 2:06:37 AM10/17/13
to jasmi...@googlegroups.com
This seems like a fine way to trigger the keypress. I think that you might not be in the callback function because the spec code you provided triggers a 'keydown' and the source code listens to 'keypress'. Making these consistent should show that you're in the callback at least. 

Unfortunately, as you've noticed, manually triggering a keydown/keypress doesn't go on to set the value of the text field (it's not exactly a user input and I'm not sure that there's a way to make it more like a user input without using something like Selenium tests). I think this might be a blocker in behaviorally testing it in Jasmine the way you've described. 

Sorry there's not an easy solution, but hopefully that helps!
Reply all
Reply to author
Forward
0 new messages