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

Categories

0 votes
324 views
in Technique[技术] by (71.8m points)

html - How to mock File in javascript?

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

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

1 Answer

0 votes
by (71.8m points)

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;

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...