How to mock File in javascript?

I'm developing some small project to exercise my TDD skills. The project consists in an audio player with drag'n'droping files in playlist. I use Jasmine as tsting framework. The problem I faced is that I can't mock javascript files to test my fileupload functionality. I tried to create File like this:

new File(new Blob(), "name");

but Chrome does not allow to create files manually. File's constructor is illegal to use. I found a solution with grunt.js which consists in returning some files from grunt, but I don't realy wanna use serverside for such a small test project. Is there any workaround for this problem?

Answers


You don't need to create a blob, you can do this which applies the genuine image string directly (I used this converter), or you can do follow the example below (if you don't actually care about having a valid image]):

html <img id="test" />

var img = window.btoa('I don't care about a broken image');
document.getElementById('test').src='data:image/png;base64,'+img;

The btoa function is just to create base64 from a string.


Chrome will let you create a new file:

var f = new File([""], "filename");

However IE11 (and other browsers?) will not.

Here's is my (poor?) fake File:

var blob = new Blob([""], { type: 'text/html' });
blob["lastModifiedDate"] = "";
blob["name"] = "filename";
var fakeF = blob;

You can fill in the values as you see fit. You can fill the blob with whatever you need. (See the other answer for how to use an image).

I've tested this in IE11, Chrome and Firefox. So far I seems to work, at least for my unit testing purposes.

Bonus: Here it is in typescript:

let blob = new Blob([""], { type: 'text/html' });
blob["lastModifiedDate"] = "";
blob["name"] = "filename";

let fakeF = <File>blob;

Need Your Help

Secure ways to reset password or to give old password

security passwords password-protection

What is the most secure way to handle forgotten passwords/password resets? Should I email the password to the user? If so do you then force them to reset it? Or do you let them reset it immediately

Action link to _escaped_fragment version of link

ajax facebook action facebook-timeline

I working on integration of Facebook timeline in my web app, but I have a problem with the action link.

About UNIX Resources Network

Original, collect and organize Developers related documents, information and materials, contains jQuery, Html, CSS, MySQL, .NET, ASP.NET, SQL, objective-c, iPhone, Ruby on Rails, C, SQL Server, Ruby, Arrays, Regex, ASP.NET MVC, WPF, XML, Ajax, DataBase, and so on.