【发布时间】:2020-02-24 06:37:52
【问题描述】:
更新:
这似乎是 FileReader 的问题。找到这个link
谁能建议我如何为 FileReader 相关的东西编写单元测试
我有实例,我在可观察的订阅回调中有回调。
组件.ts
public ngOnInit(): void {
this.subscriptions.push(this.route.paramMap.subscribe((params: ParamMap) => {
this.service.getAttachment()
.subscribe(response => {
this.convertBlobToBase46String(response.contentBytes,
async (data) => {
this.fileData = data;
});
this.isAttachmentLoadingCompleted = true;
}, error => {
this.isAttachmentLoadingCompleted = true;
this.loggingServie.logError(error, 'Error occurred while fetching attachment.');
});
}));
}
private convertBlobToBase46String(resp, callback) {
const reader = new FileReader();
reader.onload = function () {
callback(reader.result);
};
reader.readAsDataURL(resp);
}
public isAttachmentVisible(): boolean {
if (this.fileData != null && this.isAttachmentLoadingCompleted) {
return true;
}
return false;
}
component.spec.ts
it('should hide attachment if attachment is not visible', fakeAsync(() => {
let content = "Hello World";
let data = new Blob([content], { type: 'text/plain' });
let arrayOfBlob = new Array<Blob>();
arrayOfBlob.push(data);
let file = new File(arrayOfBlob, "Mock.svc");
spyOn(service, 'getAttachment').and
.returnValue(Observable.of({ mimeType: 'text/plain', contentBytes: file }));
component.ngOnInit();
fixture.detectChanges();
tick(40);
const returnValue = component.isAttachmentVisible();
expect(returnValue).toBe(true);
}));
这里 fileData 设置在回调函数中,并在 isAttachmentVisible() 方法中使用,因此它应该等待回调完成。但它不会等待它,即使我增加了刻度值,它也会在设置fileData之前调用isAttachmentVisible()
【问题讨论】:
标签: angular typescript jasmine angular6 karma-jasmine