title: How to properly mock the file reader using Jest?
body: <p>I'm trying to mock a file reader, and I have a function that accepts a callback, but during the test, the line where the callback is called is not covered. How can this be solved?</p>
  <p>function:</p>
  <pre><code>const testFunction = (uint8arr, callback) =&gt; {
    const bb = new Blob([uint8arr]);
    const f = new FileReader();
    f.onload = function (e) {
      callback(e.target.result);
    };
  
    f.readAsText(bb);
  };
  
  module.exports = { testFunction };
  </code></pre>
  <p>test:</p>
  <pre><code>const { testFunction } = require(&quot;./index&quot;);
  
  class FileReaderMock {
    DONE = FileReader.DONE;
    EMPTY = FileReader.EMPTY;
    LOADING = FileReader.LOADING;
    readyState = 0;
    error = null;
    result = null;
    abort = jest.fn();
    addEventListener = jest.fn();
    dispatchEvent = jest.fn();
    onabort = jest.fn();
    onerror = jest.fn();
    onload = jest.fn();
    onloadend = jest.fn();
    onloadprogress = jest.fn();
    onloadstart = jest.fn();
    onprogress = jest.fn();
    readAsArrayBuffer = jest.fn();
    readAsBinaryString = jest.fn();
    readAsDataURL = jest.fn();
    readAsText = jest.fn();
    removeEventListener = jest.fn();
  }
  
  const mockCallback = jest.fn();
  
  describe(&quot;testFunction&quot;, () =&gt; {
    const fileReader = new FileReaderMock();
  
    jest.spyOn(window, &quot;FileReader&quot;).mockImplementation(() =&gt; fileReader);
  
    it(&quot;should be called mockCallback and readAsText with the blob value&quot;, () =&gt; {
      const uintArray = new Uint8Array();
      testFunction(uintArray, mockCallback);
  
      // expect(mockCallback).toHaveBeenCalled();
      // expect(fileReader.readAsText).toHaveBeenCalledWith(new Blob([uintArray]));
    });
  });
  </code></pre>
  <p>codesandbox: <a href="https://codesandbox.io/s/jest-test-forked-ecejb?file=/index.test.js" rel="nofollow noreferrer">https://codesandbox.io/s/jest-test-forked-ecejb?file=/index.test.js</a></p>