Angular 4 Test FileReader onload

Viewed 2267

I try to test a method for transform my file into Base64 with Dropzone.js. My method work, but for test the FileReader, it gets hard. Actually, I created a test (see below) for called the FileReader, but I can't be enter in onload property. I want to test the inner of onload property. Thank you for your answers.

My Code Coverage

Code Coverage

My component

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

My test

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 Answers

maybe a bit late but I had the same question today. I would suggest to exclude the processing of the response and have a separate function for this.

    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...
    } 

Now it is possible to test processFileLoad separately and it would make the code more readable.

Related