Skip to content

Instantly share code, notes, and snippets.

@josephhanson
Last active December 12, 2023 16:51
Show Gist options
  • Save josephhanson/372b44f93472f9c5a2d025d40e7bb4cc to your computer and use it in GitHub Desktop.
Save josephhanson/372b44f93472f9c5a2d025d40e7bb4cc to your computer and use it in GitHub Desktop.
Mock file for JavaScript based file upload - with basic test harness
// mock file
function MockFile() { };
MockFile.prototype.create = function (name, size, mimeType) {
name = name || "mock.txt";
size = size || 1024;
mimeType = mimeType || 'plain/txt';
function range(count) {
var output = "";
for (var i = 0; i < count; i++) {
output += "a";
}
return output;
}
var blob = new Blob([range(size)], { type: mimeType });
blob.lastModifiedDate = new Date();
blob.name = name;
return blob;
};
// mock file test harness
describe("Mock file for file upload testing", function () {
it("should be defined", function() {
var file = new MockFile();
expect(file).not.toBeNull();
});
it("should have default values", function() {
var mock = new MockFile();
var file = mock.create();
expect(file.name).toBe('mock.txt');
expect(file.size).toBe(1024);
});
it("should have specific values", function () {
var size = 1024 * 1024 * 2;
var mock = new MockFile();
var file = mock.create("pic.jpg", size, "image/jpeg");
expect(file.name).toBe('pic.jpg');
expect(file.size).toBe(size);
expect(file.type).toBe('image/jpeg');
});
});
@Sebdevar
Copy link

Sebdevar commented Nov 5, 2019

Thx a lot!

@RyanMulready
Copy link

My take, returns a true File type

export default function({ name = 'file.txt', size = 1024, type = 'plain/txt', lastModified = new Date() }) {
    const blob = new Blob(['a'.repeat(size)], { type });

    blob.lastModifiedDate = lastModified;

    return new File([blob], name);
}

const testFile = MockFile({
     type: 'image/png',
     size: 50000,
});

@riverinyo
Copy link

Saved my day. Thanks!

@anshuman
Copy link

@RyanMulready not being able to read files created using your method using FileReader.
Error: TypeError: Failed to execute 'readAsBinaryString' on 'FileReader': parameter 1 is not of type 'Blob'.

@Arka-cell
Copy link

Thanks a lot buddy! 👍

@DesireeBesnard
Copy link

Thanks a lot for your work !!

@nemanjam
Copy link

with jest and jsdom i get empty object with this implementation

@bwn-z
Copy link

bwn-z commented Dec 15, 2022

why does it swear at File is not defined and Blob is not defined?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment