0

My function in file user-profile.component.ts:

    loadImage(file) {
      const myReader: FileReader = new FileReader();
      myReader.onloadend = () => {
        this.imageInBase64 = myReader.result;
      };
      myReader.readAsDataURL(file);
    }

and 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);
    });

I always get "Expected 0 to be greater than 0". How to write a right unit test for this case?

I tried mockFileReader from How do I write FileReader test in Jasmine? but no luck.

Tomcat
  • 21
  • 4

1 Answers1

1

Your test runs before the image is loaded. The image is loaded on the load event but your loadImage function returns before the event is fired.

You can solve this by returning a Promise from loadImage:

    loadImage(file) {
      return new Promise((resolve, reject) => {
        const myReader: FileReader = new FileReader();
        myReader.onloadend = () => {
          this.imageInBase64 = myReader.result;
          resolve();
        };
        myReader.readAsDataURL(file);
      });
    }

And then await for loadImage in your test:

    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);
    });

You probably also need to add some error handling and call reject when an error occurs. Also, you could return myReader.result from the Promise, instead of using a member variable.

rveerd
  • 3,620
  • 1
  • 14
  • 30