Javascript 如何在Jasmine测试中使用readAsText()并警告结果?

Javascript 如何在Jasmine测试中使用readAsText()并警告结果?,javascript,csv,jasmine,filereader,Javascript,Csv,Jasmine,Filereader,我正在尝试测试一个函数,它返回CSV的Blob,它有一个类型、名称等,并发出警报,返回以下内容: Object{size: 9, type: 'text/csv;charset=utf-8;', name: 'Test'} 它也是Blob的一个实例 我试着做这个咨询 虽然运气不好,但第一个警报调用只返回未定义的 ALERT: undefined ALERT: true 有什么帮助吗?如何将CSV blob内容转换为字符串,然后读取并测试CSV中内容的结果?FileReader是一个异步库。

我正在尝试测试一个函数,它返回CSV的
Blob
,它有一个类型、名称等,并发出警报,返回以下内容:

Object{size: 9, type: 'text/csv;charset=utf-8;', name: 'Test'}
它也是Blob的一个实例

我试着做这个咨询

虽然运气不好,但第一个警报调用只返回
未定义的

ALERT: undefined
ALERT: true 

有什么帮助吗?如何将CSV blob内容转换为字符串,然后读取并测试CSV中内容的结果?

FileReader是一个异步库。将函数分配给
fr.onload
时,FileReader将在加载文件时使用数据调用该函数。这意味着您的数据仅在该函数内部可用,而无法将其传递到外部范围。您希望执行以下操作:

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`

问题实际上是测试中的其他东西在模拟CSV/blob创建,特别是
ngMocks
,因此blob实际上没有被创建

如果你有一个类似的案例,在茉莉花测试中这样做,可能也是你的情况。为了解决这个问题,我在测试中模拟了创建/组织blob内容的函数,然后在本地录制了该函数,以便以后可以对其进行测试……而不是尝试访问blob本身

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