DEV Community

Akira Kashihara
Akira Kashihara

Posted on

How to mock FileList on Vitest

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.

  • can return a string representing the FileList mock object.
  • The function that will be tested can process each File using for statement.

How to Mock FileList?


Vitest v0.9.3

Source Code

The Source Code of The Tested Function

export const filesProcess = (fileList) => {
  if (" ")[1].slice(0, -1) !=
    throw Error("Please input FileList type object as the argument.");

  for (let file of fileList) {
    console.log("File name: " +;
Enter fullscreen mode Exit fullscreen mode

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 });
        "The string representation the object: " +

      expect(1).toBe(1); // Dummy assertion because I want to try only to mock FileList
Enter fullscreen mode Exit fullscreen mode


The result shows the result of testing using console.log.
The result of running test


Object.create() - JavaScript | MDN

The Object.create() method creates a new object, using an existing object as the prototype of the newly created object.


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)