dee*_*ell 14 testing capybara dropzone.js
我已经切换到使用Dropzone.js插件进行拖放文件上传.如何编写Capybara测试以确保此功能继续工作?
以前我有一个带有输入文件元素的模板:
<input type="file" name="attachments">
Run Code Online (Sandbox Code Playgroud)
测试很简单:
When(/^I upload "([^"]*)"$/) do |filename|
attach_file("attachments", File.expand_path(filename))
# add assertion here
end
Run Code Online (Sandbox Code Playgroud)
但是这不再有效,因为Dropzone没有可见的文件输入.
dee*_*ell 24
要解决这个问题,请模拟一下甚至触发将附件丢弃到Dropzone上.首先将此函数添加到步骤定义中:
# Upload a file to Dropzone.js
def drop_in_dropzone(file_path)
# Generate a fake input selector
page.execute_script <<-JS
fakeFileInput = window.$('<input/>').attr(
{id: 'fakeFileInput', type:'file'}
).appendTo('body');
JS
# Attach the file to the fake input selector
attach_file("fakeFileInput", file_path)
# Add the file to a fileList array
page.execute_script("var fileList = [fakeFileInput.get(0).files[0]]")
# Trigger the fake drop event
page.execute_script <<-JS
var e = jQuery.Event('drop', { dataTransfer : { files : [fakeFileInput.get(0).files[0]] } });
$('.dropzone')[0].dropzone.listeners[0].events.drop(e);
JS
end
Run Code Online (Sandbox Code Playgroud)
然后测试:
When(/^I upload "([^"]*)"$/) do |filename|
drop_in_dropzone File.expand_path(filename)
# add assertion here
end
Run Code Online (Sandbox Code Playgroud)
注意:您需要加载jQuery,Dropzone元素需要dropzone类.
这些天我觉得这样更优雅
page.attach_file(Rails.root.join('spec/fixtures/files/avatar.png')) do
page.find('#avatar-clickable').click
end
Run Code Online (Sandbox Code Playgroud)
在我的情况下,哪里是#avatar-clickable一个包含 Dropzone 表单标签的 div。
从 Capybara 3.21.0开始,您可以将文件拖放到元素上,如下所示:
find(".dropzone").drop(Rails.root.join("spec/fixtures/file.txt"))
Run Code Online (Sandbox Code Playgroud)
详细信息请参阅Element#drop 来源。
| 归档时间: |
|
| 查看次数: |
4433 次 |
| 最近记录: |