How to mock File in javascript?

纵饮孤独 提交于 2019-11-30 07:55:55
Chris Weber

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;

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.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!