asynchronous函数依赖于量angular器testing中的外部模块
我要
- 保存在远程Web服务器中的图像文件 ,以及
- 将其上传到另一台服务器
在量angular器testing。
// 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
function中,错误信息如下:
Stacktrace: UnknownError: javascript error: require is not defined
当你调用executeAsyncScript
,你传递的函数被序列化,并在浏览器中执行。 该函数不会在量angular器testing的上下文中运行,而会在浏览器上运行。
您需要创build一个承诺,解决您完成下载文件。
// 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