Send keypresses to text inputs as though as user has actually interacted with a form

This commit is contained in:
John Barker 2011-05-04 16:45:57 +08:00 committed by Joe Ferris
parent 7df0f230ae
commit c369389b5e
2 changed files with 35 additions and 9 deletions

View File

@ -405,6 +405,7 @@ describe Capybara::Driver::Webkit do
var element = elements[i];
element.addEventListener("focus", recordEvent);
element.addEventListener("keydown", recordEvent);
element.addEventListener("keypress", recordEvent);
element.addEventListener("keyup", recordEvent);
element.addEventListener("change", recordEvent);
element.addEventListener("blur", recordEvent);
@ -419,19 +420,27 @@ describe Capybara::Driver::Webkit do
end
end
let(:newtext) { 'newvalue' }
let(:keyevents) do
(%w{focus} +
newtext.length.times.collect { %w{keydown keypress keyup} } +
%w{change blur}).flatten
end
it "triggers text input events" do
subject.find("//input[@type='text']").first.set("newvalue")
subject.find("//li").map(&:text).should == %w(focus keydown keyup change blur)
subject.find("//input[@type='text']").first.set(newtext)
subject.find("//li").map(&:text).should == keyevents
end
it "triggers textarea input events" do
subject.find("//textarea").first.set("newvalue")
subject.find("//li").map(&:text).should == %w(focus keydown keyup change blur)
subject.find("//textarea").first.set(newtext)
subject.find("//li").map(&:text).should == keyevents
end
it "triggers password input events" do
subject.find("//input[@type='password']").first.set("newvalue")
subject.find("//li").map(&:text).should == %w(focus keydown keyup change blur)
subject.find("//input[@type='password']").first.set(newtext)
subject.find("//li").map(&:text).should == keyevents
end
it "triggers radio input events" do

View File

@ -54,6 +54,19 @@ Capybara = {
this.nodes[index].dispatchEvent(eventObject);
},
keypress: function(index, altKey, ctrlKey, shiftKey, metaKey, keyCode, charCode) {
var eventObject = document.createEvent("Events");
eventObject.initEvent('keypress', true, true);
eventObject.window = window;
eventObject.altKey = altKey;
eventObject.ctrlKey = ctrlKey;
eventObject.shiftKey = shiftKey;
eventObject.metaKey = metaKey;
eventObject.keyCode = keyCode;
eventObject.charCode = charCode;
this.nodes[index].dispatchEvent(eventObject);
},
visible: function (index) {
var element = this.nodes[index];
while (element) {
@ -73,9 +86,13 @@ Capybara = {
var type = (node.type || node.tagName).toLowerCase();
if (type == "text" || type == "textarea" || type == "password") {
this.trigger(index, "focus");
node.value = value;
this.trigger(index, "keydown");
this.trigger(index, "keyup");
node.value = "";
for(var strindex = 0; strindex < value.length; strindex++) {
node.value += value[strindex];
this.trigger(index, "keydown");
this.keypress(index, false, false, false, false, 0, value[strindex]);
this.trigger(index, "keyup");
}
this.trigger(index, "change");
this.trigger(index, "blur");
} else if(type == "checkbox" || type == "radio") {