Angular 4 测试 FileReader 的 onload

4
我正在尝试使用Dropzone.js将文件转换为Base64的方法进行测试。我的方法可以工作,但是测试FileReader很困难。实际上,我创建了一个测试(见下文)来调用FileReader,但是我无法进入onload属性。我想测试onload属性的内部。感谢您的回答。 我的代码覆盖率 Code Coverage 我的组件
fileTransform(event, action): void {
  const reader = new FileReader();
  reader.onload = (evt) => {
    const file = evt.target['result'];
    if (action === 'add') {
      this.filesDrop.push(file);
    }
    if (action === 'remove') {
      const index = this.filesDrop.indexOf(file);
      if (index > -1) {
        this.filesDrop.splice(index, 1);
      }
    }
  };
  reader.readAsDataURL(event);
}

我的测试

const file = {
  'upload': {
    'progress': 0,
    'total': 17343,
    'bytesSent': 0,
    'filename': 'TEST.jpeg'
  },
  'type': 'images/jpeg',
  'width': 350,
  'height': 200,
  'size': 17343,
  'name': 'TEST.jpeg',
  'dataURL': 'data:image/jpeg;base64, FOO'
};

const fileFR = {
  'bubbles': false,
  'returnValue': true,
  'target': {
    'readyState': 2,
    'result': 'data:image/jpeg;base64, FOO',
    'onload': 'bar'
  }
};

it('should fileTransform()', () => {

  spyOn(<any>window, 'FileReader').and.returnValue({
    readAsDataURL: function() {},
    onload: function() {}
  });

  component.fileTransform(fileFR, 'add');
  expect(FileReader).toHaveBeenCalled();

});
1个回答

0
也许有点晚了,但我今天也有同样的问题。我建议排除响应处理,并为此编写单独的函数。
    fileTransform(event, action): void {
      const reader = new FileReader();
      reader.onload = (evt) => {
        this.processFileLoad(evt);
      };
      reader.readAsDataURL(event);
    }

    /**
    * Function which processes the results of a file read
    * @param evt: any - the data to process
    */
    processFileLoad(evt: any){
      ...do your magic here...
    } 

现在可以单独测试processFileLoad,这将使代码更易读。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接