如何使用 Jest 模拟 HTML5 文件对象

The*_*TFo 1 javascript unit-testing jestjs flowtype

我有很多代码传递 HTML 5 文件对象。我为它编写了一套测试,但是,由于文件对象的上次修改日期,它破坏了我的快照测试。

我尝试使用以下方式进行模拟:

jest.mock('File', () => {
    return class MockFile {
        filename: string;

        constructor(parts: (string | Blob | ArrayBuffer | ArrayBufferView)[], filename: string, properties?: FilePropertyBag) {
            this.filename = filename;
        }
    }
});
Run Code Online (Sandbox Code Playgroud)

我收到错误消息,提示找不到文件模块(我不需要在使用它的任何地方导入它......)

我还尝试扩展文件类并覆盖 lastmodified get 属性,但它似乎并没有修复我的快照。

处理这个问题的最佳方法是什么?

And*_*rle 5

File您只需要在全局命名空间中设置:

global.File = class MockFile {
    filename: string;
    constructor(parts: (string | Blob | ArrayBuffer | ArrayBufferView)[], filename: string, properties ? : FilePropertyBag) {
      this.filename = filename;
    }
  }
Run Code Online (Sandbox Code Playgroud)