如何为 onloadend 中的代码编写单元测试?
How to write unit test for code inside onloadend?
我在文件用户中的函数-profile.component.ts:
loadImage(file) {
const myReader: FileReader = new FileReader();
myReader.onloadend = () => {
this.imageInBase64 = myReader.result;
};
myReader.readAsDataURL(file);
}
和用户-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);
});
我总是 "Expected 0 to be greater than 0"。如何为这种情况编写正确的单元测试?
我尝试了 How do I write FileReader test in Jasmine? 的 mockFileReader,但没有成功。
您的测试在图像加载之前运行。图像在 load
事件中加载,但您的 loadImage
函数在事件触发前 returns。
你可以通过return来自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 return myReader.result
而不是使用成员变量。
我在文件用户中的函数-profile.component.ts:
loadImage(file) {
const myReader: FileReader = new FileReader();
myReader.onloadend = () => {
this.imageInBase64 = myReader.result;
};
myReader.readAsDataURL(file);
}
和用户-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);
});
我总是 "Expected 0 to be greater than 0"。如何为这种情况编写正确的单元测试?
我尝试了 How do I write FileReader test in Jasmine? 的 mockFileReader,但没有成功。
您的测试在图像加载之前运行。图像在 load
事件中加载,但您的 loadImage
函数在事件触发前 returns。
你可以通过return来自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 return myReader.result
而不是使用成员变量。