Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

I'm developing some small project to exercise my TDD skills. The project consists of an audio player which has the ability to drag'n'drop files in a playlist. I'm using Jasmine as a testing framework. The problem I faced is that I can't mock javascript files to test my file upload functionality. I tried to create a File like this:

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

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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
312 views
Welcome To Ask or Share your Answers For Others

1 Answer

Chrome will let you create a new file:

var f = new File([""], "filename", { type: 'text/html' });

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;

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...