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".