1

我想要

  1. 保存远程 Web 服务器中的图像文件,以及
  2. 将其上传到另一台服务器

在量角器测试中。

// 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
4

1 回答 1

4

当您调用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

于 2014-12-02T15:50:27.047 回答