title: How can I mock FileReader with jest?
body: <p>I've been struggling over the past couple of weeks with unit testing a file upload react component with jest. Specifically, I'm trying to test whether or not the method <a href="https://developer.mozilla.org/en-US/docs/Web/API/FileReader/readAsDataURL" rel="nofollow noreferrer">onReadAsDataUrl</a> is being called from FileReader in one of my methods. This is an example method I am testing:</p>
  
  <pre><code>loadFinalImage = async (file) =&gt; {
    const reader = new FileReader();
    reader.onloadend = () =&gt; {
      this.setState({
        imagePreviewUrl: reader.result,
        validCard: true,
      });
    };
    await reader.readAsDataURL(file);
  }
  </code></pre>
  
  <p>This is how I am attempting to mock FileReader and test whether or not onReadAsDataUrl has been called:</p>
  
  <pre><code>it('is a valid image and reader.onReadAsDataUrl was called', () =&gt; {
      const file = new Blob(['a'.repeat(1)], { type: 'image/png' });
      wrapper = shallow(&lt;ImageUpload /&gt;).dive();
      const wrapperInstance = wrapper.instance();
      const mockReader = jest.fn();
      jest.spyOn('FileReader', () =&gt; jest.fn());
      FileReader.mockImplementation(() =&gt; { return mockReader });
      const onReadAsDataUrl = jest.spyOn(mockReader, 'readAsDataURL');
      wrapperInstance.loadFinalImage(file);
      expect(onReadAsDataUrl).toHaveBeenCalled();
    });
  </code></pre>
  
  <p>After I run: <code>yarn jest</code>, I get the following test failure: </p>
  
  <blockquote>
    <p>Cannot spyOn on a primitive value; string given.</p>
  </blockquote>
  
  <p>I assume I am getting this error because I am not importing <code>FileReader</code>, but I am not exactly sure how I would import it or mock it because <code>FileReader</code> is an interface. Here is an image of the test failure:
  <a href="https://i.stack.imgur.com/OXdfw.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/OXdfw.png" alt="enter image description here"></a></p>
  
  <p>I am a bit of a noob with jest, reactjs, and web development, but would love to learn how to conquer this problem. Some resources I have looked at so far are: <a href="https://github.com/Shopify/quilt/issues/303" rel="nofollow noreferrer">Unresolved Shopify Mock of FileReader</a>, <a href="https://stackoverflow.com/questions/52859389/mock-new-function-with-jest">How to mock a new function in jest</a>, and <a href="https://stackoverflow.com/questions/15212348/how-do-i-write-filereader-test-in-jasmine">Mocking FileReader with jasmine</a>.</p>
  
  <p>Any help would be greatly appreciated! Thank you in advance.</p>