我无法弄清楚如何执行以下操作:
在运行我的测试之前,我想将一个文件(多部分)发布到服务器。我们的后端为这些上传创建内容配置文件,然后可以通过 UI 访问这些配置文件。我需要在此内容配置文件上运行测试。
我知道 .fill() 功能,但这并不适用,因为我不想通过 UI 上传文件。有什么方法可以通过 CasperJS 或 javascript 来实现,或者任何人都可以指出可能对我有帮助的文档吗?
据我阅读 casperjs 和 phantomjs 的文档,不允许直接提交文件。你可以像下面这样使用 curl:
curl http://some.testserver.com/post.php \
-F file_input=@/path/to/my/file.txt \
-F "text_field=Some Text Here" \
-F some_number=1234
但是,您可以在casperjs上打开 POST 请求:
casper.start();
casper.open('http://some.testserver.com/post.php', {
method: 'post',
data: {
'title': 'Plop',
'body': 'Wow.'
},
headers: {
'Content-type': 'multipart/form-data'
}
});
casper.then(function() {
this.echo('POSTED it.');
});
casper.run();
以下是相关文档:
尝试这个:
casper.thenOpen('about:blank', function(){
this.evaluate(function(){
var action = 'upload.php'
var html = '<form action="'+action+'" method="post" enctype="multipart/form-data">'
html += '<input type="file" name="files[]" multiple="multiple">'
html += '<button type="submit">Submit</button>'
html += '</form>'
document.write(html)
})
this.fill('form',{
'files[]': 'file.txt'
}, true)
this.waitFor(function(){
var uri = casper.evaluate(function(){
return document.documentURI
})
if ( 'about:blank' === uri ){
return false
}
return true
})
})
检查this.page.uploadfile,因为幻影浏览器没有选择文件的ui,你可以用它指向文件名,然后点击提交。
phantom.casperPath = '{PATH_TO_CASPER_JS}';
phantom.injectJs(phantom.casperPath + '\\bin\\bootstrap.js');
var system = require('system')
var page = require('webpage').create();
var casper = require('casper').create();
function getReturnedText() {
return document.querySelector('#ocr-result').innerText;
}
casper.start('http://www.newocr.com/', function() {
this.page.uploadFile('input[type="file"]', '{PATH_TO_JPEG}');
this.click('button[name="preview"]');
});
casper.thenEvaluate(function() {
this.click('button[name="ocr"]');
});
casper.run(function() {
this.echo(getReturnedText());
phantom.exit(1);
});