How to mock File in javascript?

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;

Here's how I create a dummy pdf file to use with pdf.js

  1. Create a base64 string of your file. I use base64 command in my shell.

    base64 < src/mockData/dummy.pdf
    #outputs something like: VEhJUyBJUyBUSEUgQU5TV0VSCg==
    
  2. Copy this string into your source code.

    const dataBase64 = "VEhJUyBJUyBUSEUgQU5TV0VSCg==";
    //note this not a pdf, but for demo purposes because a pdf file is too big
    
  3. Decode the base64 and create a file

    const arrayBuffer = Uint8Array.from(window.atob(dataBase64), c => c.charCodeAt(0));
    const file = new File([arrayBuffer], "dummy.pdf", {type: 'application/pdf'});
    

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.