【问题标题】:Mock FileList for Unit Test Angular 5 App单元测试 Angular 5 应用程序的模拟文件列表
【发布时间】:2018-09-04 02:18:14
【问题描述】:

模拟FileList

我正在尝试编写一个需要 FileList 的单元测试 (Angular5)。我到处寻找解决方案的任何提示。 我想知道这是否可能因为 FileList 的安全性而我的任务从一开始就注定了。

如果可能,任何指针将不胜感激。

【问题讨论】:

标签: javascript angular typescript jasmine karma-jasmine


【解决方案1】:

选项 1:使用 DataTransfer 构造函数

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();
  });
});

选项 2:使用 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();
  });
});

编码愉快!

【讨论】:

  • 如果您需要HTMLInputEvent 类型,请参阅this answer
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-11-23
  • 2021-04-07
  • 2018-06-04
  • 1970-01-01
  • 1970-01-01
  • 2020-04-05
相关资源
最近更新 更多