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?
function:
const testFunction = (uint8arr, callback) => { const bb = new Blob([uint8arr]); const f = new FileReader(); f.onload = function (e) { callback(e.target.result); }; f.readAsText(bb); }; module.exports = { testFunction }; test:
const { testFunction } = require("./index"); 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("testFunction", () => { const fileReader = new FileReaderMock(); jest.spyOn(window, "FileReader").mockImplementation(() => fileReader); it("should be called mockCallback and readAsText with the blob value", () => { const uintArray = new Uint8Array(); testFunction(uintArray, mockCallback); // expect(mockCallback).toHaveBeenCalled(); // expect(fileReader.readAsText).toHaveBeenCalledWith(new Blob([uintArray])); }); }); codesandbox: https://codesandbox.io/s/jest-test-forked-ecejb?file=/index.test.js