Last active
December 12, 2023 16:51
-
-
Save josephhanson/372b44f93472f9c5a2d025d40e7bb4cc to your computer and use it in GitHub Desktop.
Mock file for JavaScript based file upload - with basic test harness
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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'); | |
}); | |
}); |
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,
});
Saved my day. Thanks!
@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'.
Thanks a lot buddy! 👍
Thanks a lot for your work !!
with jest and jsdom i get empty object with this implementation
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
Thx a lot!