How to upload a file in AngularJS e2e tests?

In one of my views, I have file upload control. It supports downloading files either by drag and drop, or through the standard file dialog box, opened after clicking a button.

How to do this in my e2e 1 tests?




1 One of two options is enough

+13
javascript angularjs file-upload testing drag-and-drop
Nov 10 '12 at 12:20
source share
1 answer

You can upload files using Javascript blob. This requires FileApi, which is not compatible with older browsers ( http://caniuse.com/fileapi ). But since you mentioned the use of drag and drop, which uses FileApi, this should not really matter.

There are two ways to upload files using the blob API. One of them is very simple, and the other is just a continuation of the first.

Using Javascript, you can create a new blob with:

var blob = new Blob("content", contentType); 

For example, this will create a blob containing the text "Hello World!"

 var foo = new Blob("Hello World!", {type: "text/plain"}); 



You can also use the following method for files without text, such as pdf. You have to convert the file to Base64 (you can use something like this ) and create a blob using Base64 data.

Use this function (a slightly modified version of this ) to create a blob.

 function b64toBlob(b64Data, contentType, sliceSize) { b64Data = b64Data.replace(/\s/g, ''); contentType = contentType || ''; sliceSize = sliceSize || 1024; function charCodeFromCharacter(c) { return c.charCodeAt(0); } var byteCharacters = atob(b64Data); var byteArrays = []; for (var offset = 0; offset < byteCharacters.length; offset += sliceSize) { var slice = byteCharacters.slice(offset, offset + sliceSize); var byteNumbers = Array.prototype.map.call(slice, charCodeFromCharacter); var byteArray = new Uint8Array(byteNumbers); byteArrays.push(byteArray); } var blob = new Blob(byteArrays, {type: contentType}); return blob; } 

For example, this will create a blob PDF object.

 var pdf = "JVBERi0xLjQKJcfsj6IKNSAwIG9...=="; //base64 encoded file as a String var pdfBlob = b64toBlob(pdf, "application/pdf", 1024); 



After you create a blob using one of the methods above, it can be considered as a file. For example, you can put the file in a FormData object (if you are loading, for example this ):

 var fd = new FormData(); fd.append("uploadedFile", pdfBlob, "My PDF.pdf"*); 

* File name option only works on Chrome.

+3
Jun 03 '13 at 14:45
source share



All Articles