I am using mocha, chai, karma along with PhantomJS and related addons. How can we create a client side File object to pass it to FileReader API ? I have to upload a test jpeg file, create a file object and pass it to FileReader api to continue testing.
1 Answer
I'm not sure why you need a File instance, A Blob should be enough. You need to show us some more context on what you are trying to achieve.
What are your code doing and what is the test expected to yield?
If you have access to DOM and canvas just simply create one with js
document.createElement('canvas').toBlob(function(blob) {
// FileReader will be happy with just a blob
// But if you really want a file you need to construct it also
// var file = new File([blob], 'canvas.jpg', {type: blob.type})
var fr = new FileReader
fr.onload = function(){
console.log(fr.result.byteLength)
}
fr.readAsArrayBuffer(blob)
}, 'image/jpeg')
3 Comments
Deepan Prabhu Babu
Dev code I am writing is going to validate files using javascript FileReader on a client's browser, once he selects a file for upload in a form, before uploading though. Basically, my setup consists of npm, karma, mocha, chai, browserify, phantomjs, and javascript code to validate a file, once a file object is passed. The code is working if I use a vanilla browser and select a file manually. I want to convert this into an automated test, where i can parameterize the file and pass different test files to test the code flow. Please tell me if you need more context.
Deepan Prabhu Babu
I am unable to test using phantomjs completely, because it doesn't fire most of the onload methods, and moreover, blob object i created using your above code ( Thank you !! ) is empty. I used a polyfill as phantomjs did not support natively.
guest271314
@DeepanPrabhuBabu "and javascript code to validate a file, once a file object is passed.The code is working if I use a vanilla browser and select a file manually. I want to convert this into an automated test, where i can parameterize the file and pass different test files to test the code flow." Are you trying to populate the
.files object of an <input type="file"> element using javascript? Can you include the javascript that both is, and is not returning expected result at Question? See stackoverflow.com/help/mcve, stackoverflow.com/help/how-to-ask
Fileobject for testing purposes. I'm voting to reopen.Fileobject. See also Chrome: Create file input from blob with Javascript?Fileobject usingnew File()constructor, as described at Answer at linked Question; orFormData,prototype.append()How to create a modified copy of a File object in JavaScript?