How to upload file in angularjs e2e protractor testing

Pawan Singh picture Pawan Singh · Jan 23, 2014 · Viewed 58.5k times · Source

I want to test file uploading using an angularjs e2e test. How do you do this in e2e tests? I run my test script through grunt karma.

Answer

Andres D picture Andres D · Jan 23, 2014

This is how I do it:

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();
});
  1. Use the path module to resolve the full path of the file that you want to upload.
  2. Set the path to the input type="file" element.
  3. Click on the upload button.

This will not work on firefox. Protractor will complain because the element is not visible. To upload in firefox you need to make the input visible. This is what I do:

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();