背景
我有一个简单的表单,其中名称不能包含数字。
所以我抓住了按键:
// prevent number from being added in a name
$("#name1__firstname").keypress(function(e) {
rejectCharacterIfNumeric(e);
});
然后使用此函数检查是否为数字,如果是,preventDefault()
:
// function to disallow numbers added into a text input
function rejectCharacterIfNumeric(e) {
var key = e.which;
key = String.fromCharCode(key);
var regex = /[0-9]|\./;
if (regex.test(key)) {
e.preventDefault();
}
console.log('foo'); // <-- not being fired
};
问题
我需要为此编写一个Jasmine
测试,但它不会捕获按键。
这就是我正在尝试的:
describe("when text is entered in the input", function(){
var fixture;
beforeEach(function () {
fixture += "<input id='name1__firstname'>";
setFixtures(fixture);
});
it("it should not show if numeric", function(){
var textInput = $('#name1__firstname');
textInput.trigger(
$.Event( 'keypress', { keyCode: 65, which: 65 } ) // letter "a"
);
expect(textInput.val().length).toEqual(1);
});
afterEach(function () {
fixture = "";
fixture = null;
});
})
此测试失败,因为数字已插入输入Expected 0 to equal 1.
我知道测试没有调用rejectCharacterIfNumeric(e)
因为我在函数中添加了console.log()
而不会触发
问题
如何传递keyPress以便触发rejectCharacterIfNumeric(e)
函数?
答案 0 :(得分:1)
规范中的textInput变量没有附加事件:
it("it should not show if numeric", function(){
var textInput = $('#name1__firstname');
textInput.keypress(function(e) {
rejectCharacterIfNumeric(e);
});
textInput.trigger(
$.Event( 'keypress', { keyCode: 65, which: 65 } ) // letter "a"
).val('A');
expect(textInput.val().length).toEqual(1);
});