I need to mock FileList
that <input type="file" multiple />
provides. This article shows you how to mock it. I had a hard time mocking it.
The requirement to mock FileList
is the following.
-
Object.prototype.toString.call
can return a string representing theFileList
mock object. - The function that will be tested can process each
File
usingfor
statement.
How to Mock FileList
?
Environment
Vitest v0.9.3
Source Code
The Source Code of The Tested Function
export const filesProcess = (fileList) => {
if (
Object.prototype.toString.call(fileList).split(" ")[1].slice(0, -1) !=
"FileList"
)
throw Error("Please input FileList type object as the argument.");
for (let file of fileList) {
console.log("File name: " + file.name);
}
};
Test Code
it("testing", () => {
const file = new File(["foo"], "foo.txt", {
type: "text/plain",
});
const file2 = new File(["this is test file"], "test.txt", {
type: "text/plain",
});
const input = document.createElement("input");
input.setAttribute("type", "file");
input.setAttribute("name", "file-upload");
input.multiple = true;
let mockFileList = Object.create(input.files);
mockFileList[0] = file;
mockFileList[1] = file2;
Object.defineProperty(mockFileList, "length", { value: 2 });
console.log(
"The string representation the object: " +
Object.prototype.toString.call(mockFileList)
);
filesProcess(mockFileList);
expect(1).toBe(1); // Dummy assertion because I want to try only to mock FileList
});
Result
The result shows the result of testing using console.log
.
Reference
As An Aside
I make the browser displays all elements of FileList
that I generated by inputting some files to <input type="file" multiple />
using console.log
. After that, I googled necessary elements making ways and making testing code.
The original article is the following. This article was translated from Japanese to English.
Top comments (0)