异步功能取决于量角器测试中的外部模块

Async function depends on a external module in Protractor test

本文关键字:外部 模块 测试 功能 取决于 量角器 异步      更新时间:2023-09-26

我想

  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

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