如何在 Jasmine 测试中使用 readAsText() 并提醒结果?
How to use readAsText() within a Jasmine test and alert the result?
我正在尝试测试一个函数,returns 一个 CSV 的 Blob
,它有一个类型、名称等,并提醒 returns 这个:
Object{size: 9, type: 'text/csv;charset=utf-8;', name: 'Test'}
也是instanceOf Blob
。
我试过做这个咨询this question...
var fr = new FileReader();
fr.onload = function(e) {
return e.target.result;
};
alert(fr.readAsText(blob));
alert(blob instanceof Blob);
虽然运气不好,但第一个警报呼叫只是 returns undefined
。
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。
如果您在 Jasmine 测试中有类似的情况,可能也是您的情况。为了解决这个问题,我在测试中模拟了 creates/organizes 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");
}
};
我正在尝试测试一个函数,returns 一个 CSV 的 Blob
,它有一个类型、名称等,并提醒 returns 这个:
Object{size: 9, type: 'text/csv;charset=utf-8;', name: 'Test'}
也是instanceOf Blob
。
我试过做这个咨询this question...
var fr = new FileReader();
fr.onload = function(e) {
return e.target.result;
};
alert(fr.readAsText(blob));
alert(blob instanceof Blob);
虽然运气不好,但第一个警报呼叫只是 returns undefined
。
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。
如果您在 Jasmine 测试中有类似的情况,可能也是您的情况。为了解决这个问题,我在测试中模拟了 creates/organizes 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");
}
};