0

目前,我有以下代码的简单创建反应应用程序

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

跑步时npm test,我得到了这个Illegal invocation

TypeError: Illegal invocation

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

知道如何解决吗?

更新 1

我稍微更改了代码。基本上,我想对覆盖率onloadonerror. 我具体需要做什么?

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

0 回答 0