我在user-profile.component.ts文件中的功能:
loadImage(file) {
const myReader: FileReader = new FileReader();
myReader.onloadend = () => {
this.imageInBase64 = myReader.result;
};
myReader.readAsDataURL(file);
}
和user-profile.component.spec.ts
it('upload image success', async () => {
const file = new File([new Blob(['123'])], 'abc.png', { type: 'image/png' });
component.loadImage(file);
expect(component.imageInBase64.length).toBeGreaterThan(0);
});
我总是得到“期望0大于0”。如何为这种情况编写正确的单元测试?
我尝试了How do I write FileReader test in Jasmine?的模拟文件读取器,但没有运气。
答案 0 :(得分:0)
您的测试在加载图像之前运行。图像已加载到load
事件中,但是您的loadImage
函数在事件触发前返回。
您可以通过从loadImage
返回Promise来解决此问题:
loadImage(file) {
return new Promise((resolve, reject) => {
const myReader: FileReader = new FileReader();
myReader.onloadend = () => {
this.imageInBase64 = myReader.result;
resolve();
};
myReader.readAsDataURL(file);
});
}
然后等待测试中的loadImage
:
it('upload image success', async () => {
const file = new File([new Blob(['123'])], 'abc.png', { type: 'image/png' });
await component.loadImage(file);
expect(component.imageInBase64.length).toBeGreaterThan(0);
});
您可能还需要添加一些错误处理,并在发生错误时调用reject
。另外,您可以从Promise中返回myReader.result
,而不使用成员变量。