最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Mock FileList for Unit Test Angular 5 App - Stack Overflow

programmeradmin2浏览0评论

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.

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.

Share Improve this question edited May 6, 2019 at 23:53 asked Mar 26, 2018 at 2:04 user9298624user9298624 5
  • 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 stackoverflow.com/questions/47119426/… for a demo. – Kaiido Commented Mar 26, 2018 at 5:53
  • We don't have debates here. – Robert Harvey Commented Mar 27, 2018 at 0:08
  • 4 gist.github.com/amabes/88324d68690e0e7b8e313cd0cafaa219 – Alan Mabry Commented Apr 6, 2018 at 4: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 Commented May 6, 2019 at 6:08
  • 1 @AlanMabry you may want to post as an answer. – Kaiido Commented May 6, 2019 at 13:51
Add a comment  | 

1 Answer 1

Reset to default 19

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!

发布评论

评论列表(0)

  1. 暂无评论