我的html使用ng-template。该模板用于创建缩略图。
<ng-template #thumbnailTemplate let-option="option">
<div id="{{option.divId}}"> <!-- top level div of thumbnail. This will have ids thumbnail-1, thumbnail-2 etc.-->
<img id="{{option.imgId}}" src="{{option.imgSrc}}"> <!-- this will have width, height=80-->
<a href="#" id="{{option.closeId}}" (click)="deleteThumbnail(option)"></a> <!-- the X button is created using CSS. This will have ids close-button-1, close-button-2. They'll also containn reference to the parent div id (thumbnail-1, thumbnail-2 ) -->
</div>
</ng-template>handleFileSelect创建一个FileReader,为FileReader分配回调,并调用readAsDataURL函数开始读取文件。
handleFileSelect(files:ArrayLike<File>):FileReader|null{
... let reader:FileReader = new FileReader();
reader.onload = this.handleReaderLoaded.bind(this);
reader.onerror = this.handleFileLoadError.bind(this);
reader.onabort = this.handleFileAbort.bind(this);
reader.readAsDataURL(file);
}异步调用的handleReaderLoaded方法接受加载的文件并对其进行处理。
我想对handleReaderLoaded方法进行单元测试。我这样做的方法是检查两个变量currentImageAttachmentCount和thumbnailContainerRef,如果handleReaderLoaded工作正常,它们应该已经更新。我所写的规范如下所示,它可以工作,但我在这里没有使用done函数,我认为它是为了测试jasmine的同步代码而推荐的。
fit('should upload image if user selects an image', async(() => {
let newPracticeQuestionComponent = component;
expect(newPracticeQuestionComponent.currentImageAttachmentCount).toBe(0);
expect(newPracticeQuestionComponent.thumbnailContainerRef.length).toBe(0);
let file1 = new File(["foo1"], "foo1.txt");
let reader = newPracticeQuestionComponent.handleFileSelect([file1]);
setTimeout(function() {
console.log("in timeout");
expect(newPracticeQuestionComponent.currentImageAttachmentCount).toBe(1);
expect(newPracticeQuestionComponent.thumbnailContainerRef.length).toBe(1);
}, 2000);
}));1)我想使用done方法,但我不知道如何使用它。我如何使用done重写上面的规范。2)由于我可以在没有done方法的情况下进行测试,我想知道done有什么用
发布于 2019-02-01 14:20:46
我错误地认为我的规范在没有done的情况下运行得很好。发生的事情是,Jasmine刚刚完成了it规范,甚至没有等待setTimeout。由于没有要做的断言,规范显示为已通过。
正确的was方法是在异步代码中调用done
setTimeout(function() {
console.log("in timeout");
expect(newPracticeQuestionComponent.currentImageAttachmentCount).toBe(1);
expect(newPracticeQuestionComponent.thumbnailContainerRef.length).toBe(1);
done(); //without done, jasmine will finish this test spec without checking the assertions in the timeout
}, 2000);我认为done在Jasmine中扮演着检查点的角色。当Jasmine发现某个规范使用了done时,它知道除非调用了包含done的代码段,否则它不能继续下一步(比如运行下一个规范或将此规范标记为完成)。
https://stackoverflow.com/questions/54466214
复制相似问题