0

Currently, I have simple create react app with following code

import React from "react";

export const readFilePromise = (file) => {
  return new Promise((resolve, reject) => {
    let reader = new FileReader();
    reader.readAsDataURL(file);
    reader.onload = () => {
      resolve(reader.result);
    };
    reader.onerror = (error) => {
      reject(error);
    };
  });
};

test("test", async () => {
  let spy = jest
    .spyOn(FileReader.prototype, "onload")
    .mockImplementation(() => {
      console.log("+++ onload");
    });

  const result = await readFilePromise();

  spy.mockRestore();
});

When running npm test, I am getting this Illegal invocation

TypeError: Illegal invocation

16 | test("test", async () => {
17 |   let spy = jest
> 18 |     .spyOn(FileReader.prototype, "onload")

Any idea how to fix it?

Update 1

I changed the code a bit. Basically, I want to code coverage onload and onerror. What exactly do I need to do?

test("test", async () => {
  let spy = jest.spyOn(global, "FileReader").mockImplementation(function () {
    this.readAsDataURL = jest.fn();
    this.onload = jest.fn();
    this.onerror = jest.fn();
  });

  let result = await readFilePromise();

  spy.mockRestore();
});
kenpeter
  • 7,404
  • 14
  • 64
  • 95
  • Possible duplicate of https://stackoverflow.com/questions/61572070/how-to-test-filereader-onload-using-simulate-change-in-jest – Estus Flask Jun 04 '20 at 11:15
  • Mocking FileReader.prototype.onload would be useless because it's shadowed by reader.onload but here it additionally triggers an error for a reason explained in the dupe. Mock the entire FileReader. – Estus Flask Jun 04 '20 at 11:17
  • @EstusFlask, see my update above – kenpeter Jun 05 '20 at 00:23
  • The answer contains the code that suits your case, including onload coverage. Did you try it? – Estus Flask Jun 05 '20 at 05:44

0 Answers0