我想要
保存在远程Web服务器中的图像文件,并
将其上传到另一台服务器
在量角器测试中。
// depend on a external module
var fs = require('fs');
// save remote file(url) to local(dest)
var download = function (url, dest) {
// let this function be async
browser.executeAsyncScript(function (url, dest, done) {
var file = fs.createWriteStream(dest);
var request = http.get(url, function (response) {
response.pipe(file);
file.on('finish', function () {
file.close(done);
});
});
}, url, dest);
};
describe('', function () {
it('', function () {
browser.get('http://...');
download('http://.../foo.jpg', 'foo.jpg'); /*** DOESN'T WORK! ***/
var absolutePath = path.resolve(__dirname, 'foo.jpg');
$('input[type=file]').sendKeys(absolutePath);
$('#uploadButton').click();
...
但这不起作用:
Stacktrace:
UnknownError: javascript error: fs is not defined
当我将
var fs = require('fs');
放在download
函数中时,错误消息如下: Stacktrace:
UnknownError: javascript error: require is not defined
最佳答案
调用executeAsyncScript
时,传递的函数将在浏览器中序列化执行。该函数将不会在量角器测试的上下文中运行,而是在浏览器上运行。
您需要创建一个承诺,在下载完文件后即可解决。
// depend on a external module
var fs = require('fs');
describe('', function () {
// save remote file(url) to local(dest)
var download = function (url, dest) {
// Create a promise that will be resolved after download.
var d = protractor.promise.defer();
var file = fs.createWriteStream(dest);
var request = http.get(url, function (response) {
response.pipe(file);
file.on('finish', function () {
file.close();
// The file has been read, resolve the promise
d. fulfill();
});
});
// Return the promise
d.promise;
};
it('', function () {
browser.get('http://...');
// Get the file and wait for the promise to resolve to move on
download('http://.../foo.jpg', 'foo.jpg').then(function() {
// Make sure you specify a path where you can write and read the file.
var absolutePath = path.resolve(__dirname, 'foo.jpg');
$('input[type=file]').sendKeys(absolutePath);
$('#uploadButton').click();
...
});
让我知道是否有效
这里是文档:https://code.google.com/p/selenium/wiki/WebDriverJs#Deferred_Objects