0

I'm trying to test a function, that returns a Blob of a CSV, it has a type, name etc and alerting that returns this:

Object{size: 9, type: 'text/csv;charset=utf-8;', name: 'Test'}

and it is an instanceOf Blob as well.

I tried doing this consulting this question...

var fr = new FileReader();
fr.onload = function(e) {
  return e.target.result;
};
alert(fr.readAsText(blob));
alert(blob instanceof Blob);

Though no luck, the first alert call just returns undefined.

ALERT: undefined
ALERT: true 

Any help with doing this? How can I convert the CSV blob content to a String that I can then read and test the result of the content in the CSV?

Carson
  • 1,147
  • 5
  • 19
  • 41

2 Answers2

0

FileReader is an asynchronous library. When you assign a function to fr.onload, FileReader will call that function with the data when it loads a file. That means your data is only available inside that function and you cannot get it to the outer scope. You want to do something like this:

var fr = new FileReader(); // Create FileReader instance

// Assign a function to be called when FileReader reads a file
fr.onload = function(e) {

  // Your data is available in this scope only. Returning it does nothing.
  alert(e.target.result);
  alert(blob instanceof Blob);
};

fr.readAsText(blob); // Tell our instance of FileReader to read `blob`
Rodrigo Leite
  • 596
  • 5
  • 22
0

The issue actually was with something else within the test mocking the CSV/blob creation, particularly ngMocks so the blob wasn't actually being created.

If you have a similar case doing this in a Jasmine test, may be your situation as well. To get around this, I mocked the function that creates/organizes the content of the blob in the test and then just recorded that locally so I could test it later...rather than trying to access the blob itself.

this.CSV.stringify.and.callFake(function(csvFeaturesInStringify, csvOptionsInStringify) {
    this.csvFeatures = csvFeaturesInStringify;
    this.csvOptions= csvOptionsInStringify;
    return {
      then: function(successCallback) {
        successCallback("geometry,LAT,LONG,name,marker-color");
      }
    };
Carson
  • 1,147
  • 5
  • 19
  • 41