javascript - 模拟拖放文件以在 Protractor 中上传

标签 javascript angular protractor e2e-testing

我想通过将文件拖动到页面中的放置区来测试文件上传,但是我找不到模拟从桌面文件夹拖动文件的方法。 我设法找到的唯一方法是以下方法 -

desktop.browser.actions().dragAndDrop(elem,target).mouseUp().perform();(Protractor)

但据我所知,它只拖动 css 元素。

最佳答案

这是一个模拟文件从桌面放到放置区域的工作示例:

const dropFile = require("./drop-file.js");
const EC = protractor.ExpectedConditions;

browser.ignoreSynchronization = true;

describe('Upload tests', function() {

  it('should drop a file to a drop area', function() {

    browser.get('http://html5demos.com/file-api');

    // drop an image file on the drop area
    dropFile($("#holder"), "./image.png");

    // wait for the droped image to be displayed in the drop area
    browser.wait(EC.presenceOf($("#holder[style*='data:image']")));
  });

});

drop-file.js 的内容:

var fs = require('fs');
var path = require('path');

var JS_BIND_INPUT = function (target) {
  var input = document.createElement('input');
  input.type = 'file';
  input.style.display = 'none';
  input.addEventListener('change', function () {
    target.scrollIntoView(true);

    var rect = target.getBoundingClientRect(),
      x = rect.left + (rect.width >> 1),
      y = rect.top + (rect.height >> 1),
      data = { files: input.files };

    ['dragenter','dragover','drop'].forEach(function (name) {
      var event = document.createEvent('MouseEvent');
      event.initMouseEvent(name, !0, !0, window, 0, 0, 0, x, y, !1, !1, !1, !1, 0, null);
      event.dataTransfer = data;
      target.dispatchEvent(event);
    });

    document.body.removeChild(input);
  }, false);

  document.body.appendChild(input);
  return input;
};


/**
 * Support function to drop a file to a drop area.
 *
 * @view
 * <div id="drop-area"></div>
 *
 * @example
 * dropFile($("#drop-area"), "./image.png");
 *
 * @param {ElementFinder} drop area
 * @param {string} file path
 */
module.exports = function (dropArea, filePath) {
  // get the full path
  filePath = path.resolve(filePath);

   // assert the file is present
  fs.accessSync(filePath, fs.F_OK);

  // resolve the drop area
  return dropArea.getWebElement().then(function (element) {

    // bind a new input to the drop area
    browser.executeScript(JS_BIND_INPUT, element).then(function (input) {

      // upload the file to the new input
      input.sendKeys(filePath);

    });
  });
};

关于javascript - 模拟拖放文件以在 Protractor 中上传,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37547182/

相关文章:

javascript - 通过按钮调用函数后悬停效果消失

javascript - Jquery slider 值不为零

javascript - “How to fix ‘NGX Data Table Checkbox Issue In Angular?”

Angular5 服务器端呈现((未知网址): 0 Unknown Error) 的 Http 失败响应

javascript - 类型 'Subscription' 缺少类型 'Observable<StringMap<any>>' 的以下属性

javascript - 返回给定时间的鼠标位置

javascript - 用于匹配州和邮政编码的正则表达式

protractor - searchText.indexOf 不是 Protractor 5.3.0 中的函数

protractor - 通过 css 和 buttonText 定位按钮

javascript - 从 selenium/protractor javascript 中的 span 元素中提取内部