4

I am writing this code which requires me to do unit testing via Q-Unit. I have an input field where a user uploads a file and I then read it using "FileReader" of Javascript to do some processing on it. However, when writing unit-test, I am unable to upload the file on the input field so that I can unit test my function. What I am doing at the moment is as follows:

//Unit test bit
var done = assert.async();
var pngFile = new File([""],"../../img/test.jpg");
inputElement.files[0] = pngFile;
photoMosaic.extractImageFromInput(inputElement);
setTimeout(function() {
        assert.equal(photoMosaic.getImageName(),"../../img/test.jpg", "Correct file format test succeeds" );
        done();
    }, 500 );

The code in extractImageFromInput that extract the image is as follows:

//after some checkings and stuff
var reader = new FileReader();
                    // Closure to capture the file information.
                    reader.onload = (function(theFile) {
                        return function(e) {
                            // Render image
                            this.MainImage = document.createElement('IMG');
                            this.MainImage.src = e.target.result;
                            this.MainImage.setAttribute("name",theFile.name);
                            return this.MainImage;
                        };
                    })(file);
                    reader.readAsDataURL(file);

However, it gives me the following error:

GET data: net::ERR_INVALID_URL

I have tried putting the image in the same directory as the test and using just "test.jpg" as path but no luck. Any help would be appreciated.

fur866
  • 413
  • 1
  • 5
  • 14
  • Have you tried an absolute URL (`http://www.yoursite.com/path/file.ext`)? – Scott Marcus Dec 07 '16 at 00:42
  • @ScottMarcus I did try that yes with no luck. Also another thing to notice is that I am using readAsDataURL. Perhaps that's breaking it? – fur866 Dec 07 '16 at 00:47
  • Use `URL.createObjectURL(file)` instead of using the FileReader – Endless Dec 07 '16 at 22:27
  • Possible duplicate of [Programmatically set name of file to upload in webpage](http://stackoverflow.com/questions/997977/programmatically-set-name-of-file-to-upload-in-webpage) – Paul Sweatte Dec 27 '16 at 17:39

0 Answers0