如何在angularjs e2e量角器测试中上传文件

Paw*_*ngh 83 file-upload file angularjs gruntjs protractor

我想使用angularjs e2e测试来测试文件上传.你如何在e2e测试中做到这一点?我通过咕噜的业力来运行我的测试脚本.

And*_*s D 132

我是这样做的:

var path = require('path');

it('should upload a file', function() {
  var fileToUpload = '../some/path/foo.txt',
      absolutePath = path.resolve(__dirname, fileToUpload);

  element(by.css('input[type="file"]')).sendKeys(absolutePath);    
  element(by.id('uploadButton')).click();
});
Run Code Online (Sandbox Code Playgroud)
  1. 使用该path模块可以解析要上载的文件的完整路径.
  2. 设置input type ="file"元素的路径.
  3. 单击上传按钮.

这对Firefox不起作用.量角器会抱怨因为元素不可见.要在Firefox中上传,您需要使输入可见.这就是我做的:

browser.executeAsyncScript(function(callback) {
  // You can use any other selector
  document.querySelectorAll('#input-file-element')[0]
      .style.display = 'inline';
  callback();
});

// Now you can upload.
$('input[type="file"]').sendKeys(absolutePath);    
$('#uploadButton').click();
Run Code Online (Sandbox Code Playgroud)

  • FWIW,`__ dirname`有时指向一个临时目录(可能是测试运行者复制测试的地方).如果是这种情况,你可以使用`process.cwd()`而不是`__dirname`. (6认同)

bda*_*xyz 11

你不能直接.

出于安全原因,您无法模拟在功能测试套件(如ngScenario)中选择系统上的文件的用户.

使用Protractor,因为它基于WebDriver,所以应该可以使用这个技巧

问:WebDriver是否支持文件上传?答:是的.

您无法直接与本机OS文件浏览器对话框进行交互,但我们会做一些魔术,因此如果您在文件上传元素上调用WebElement #sendKeys("/ path/to/file"),它就会做正确的事情.确保你没有WebElement#click()文件上传元素,否则浏览器可能会挂起.

这很好用:

$('input[type="file"]').sendKeys("/file/path")
Run Code Online (Sandbox Code Playgroud)