如何在onloadend内编写代码的单元测试?

时间:2020-03-13 10:39:56

标签: angular unit-testing jasmine

我在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?的模拟文件读取器,但没有运气。

1 个答案:

答案 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,而不使用成员变量。