15

Mock FileList

I am trying to write a unit test (Angular5) that requires a FileList. I have looked everywhere for any hint at a solution. I am wondering if this is even possible because of the security nature of FileList and my quest has been doomed from the start.

If this is possible any pointers would be greatly appreciated.

  • I don't know jasmine, but the only spec wise way to **create a writable** FileList from scratch is through the `DataTransfer` constructor (currently only available in Blink) . See https://stackoverflow.com/questions/47119426/how-to-set-file-objects-and-length-property-at-filelist-object-where-the-files-a/47172409#47172409 for a demo. – Kaiido Mar 26 '18 at 05:53
  • We don't have debates here. – Robert Harvey Mar 27 '18 at 00:08
  • 4
    https://gist.github.com/amabes/88324d68690e0e7b8e313cd0cafaa219 – Alan Mabry Apr 06 '18 at 04:35
  • 1
    @Kaiido, seems like this question is not a duplicate to the one you've marked. Could you please remove the mark or clarify the reason of marking as duplicate? – Just Shadow May 06 '19 at 06:08
  • 1
    @AlanMabry you may want to post as an answer. – Kaiido May 06 '19 at 13:51

1 Answers1

15

Option 1: Using DataTransfer Constructor

describe('Component', () => {
  const getFileList = () => {
    const dt = new DataTransfer();
    dt.items.add(new File([], 'file.csv'));
    return dt.files;
  };

  it('should mock fileList', () => {
    component.fileList = getFileList();
  });
});

Option 2: Mocking Filelist with Blob

describe('Component', () => {
  const getFileList = () => {
    const blob = new Blob([""], { type: "text/html" });
    blob["lastModifiedDate"] = "";
    blob["name"] = "filename";
    const file = <File>blob;
    const fileList: FileList = {
      0: file,
      1: file,
      length: 2,
      item: (index: number) => file
    };
    return fileList;
  };

  it('should mock fileList', () => {
    component.fileList = getFileList();
  });
});

Happy coding!

Bhavin
  • 970
  • 1
  • 13
  • 20
  • 1
    And if you need a `HTMLInputEvent` type see [this answer](https://stackoverflow.com/a/43176930/23118). – hlovdal Oct 27 '21 at 09:58