jest mock:Matcher error:接收的值必须是模拟或间谍函数

p1iqtdky  于 2023-09-28  发布在  Jest
关注(0)|答案(1)|浏览(161)

我想对这个方法进行单元测试(类似于How to use Jest to test file download?的启发):

export const download = (file, filename) => {
  FileSaver.saveAs(file,filename);
};

这是测试

import { download } from "../../../utils/methods/utils";
import FileSaver from "file-saver";
import { item } from "../../__mocks__/responses/export"

describe("Test download", () => {
  it("Can handle download", () => {
    jest.mock("file-saver", () => ({
      saveAs: jest.fn()
    }));
    download(item.file, "test.xls");
    expect(FileSaver.saveAs).toHaveBeenCalledTimes(1);
  });
});

但我得到

expect(received).toHaveBeenCalledTimes(expected)

Matcher error: received value must be a mock or spy function

Received has type:  function
Received has value: [Function anonymous]

   9 |     }));
  10 |     download(item.file, "test.xls");
> 11 |     expect(FileSaver.saveAs).toHaveBeenCalledTimes(1);
     |                              ^
  12 |   });
  13 | });
  14 |

  at Object.<anonymous> (src/__tests__/utils/methods/download.test.js:11:30)
fhity93d

fhity93d1#

我用SpyOn a mocked jest module not spying properly解决了。
问题是一个小超时。

it("Can handle download", () => {
    jest.mock("file-saver", () => ({
      saveAs: jest.fn()
    }));
    global.Blob = function (content, options) {
      return { content, options };
    };
    download(item.file, "test.xls");
    setTimeout(() => {
      expect(FileSaver.saveAs).toBeCalled();
      done();
    }, 10000);
  });

相关问题