【发布时间】:2019-01-22 21:38:35
【问题描述】:
我有一个创建FileReader 的函数。在该函数中,我还设置了 load 和 error 事件处理程序
handleFileSelect(files:ArrayLike<File>){
...
let reader = new FileReader()
reader.onload = this.handleReaderLoaded;
reader.onerror = this.handleReaderError;
reader.readAsDataURL(file);
}
}
我想对handleFileSelect 正确设置错误处理程序以及如果FileReader 失败时调用错误处理程序 (handleReaderError) 进行单元测试。但我不知道如何使FileReader 失败。
到目前为止我写的规范是
fit('should call error handler when file doesn\'t get loaded successfully', (done) => {
let newPracticeQuestionComponent = component;
let file1 = new File(["foo1"], "foo1.txt");
/*
File reader will load the file asynchronously.
The `done` method of `Jasmine` makes `Jasmine` wait
When handleReaderError is called, call a fake function and within it call done
*/
spyOn(newPracticeQuestionComponent,'handleReaderError').and.callFake(function(event:FileReaderProgressEvent){
console.log("called fake implementation of handleReaderError ",event);
expect(event.type).toEqual("abort");
done();
});
newPracticeQuestionComponent.handleFileSelect([file1]);
//I SHOULD SIMULATE FILEREADER ERROR HERE BUT HOW??
});
【问题讨论】:
-
你能找到一个好的解决方案吗?
-
我得到了
FileReader的引用并使用dispatchEvent来模拟错误reader.dispatchEvent(new Event('error'));。您是否尝试过下面 mixth 提供的答案? -
我看到了,但不能完全理解。你是如何在你的函数中引用
FileReader的? -
我在这里问了一个类似但不同的问题 - 您的解决方案也适用于我的情况吗? stackoverflow.com/questions/65806605/…
标签: typescript jasmine filereader