Stencil.js 开玩笑:模拟 FileReader 'not defined' 除非使用 window.FileReader

Stencil.js Jest: mock FileReader 'not defined' unless use window.FileReader

我有一个带有实用程序 class 的 util.ts 模块,可以在 input 上传文件后读取文件:

// utils/utils.ts

export class JsonFileProcessor {

   process(files) {
     // ReferenceError: FileReader is not defined
     const reader = new FileReader();
   }
}

在我的 utils.spec.ts 中,我模拟了 window.FileReader(到目前为止未定义)

import { JsonFileProcessor } from "./utils";

describe("JsonFileProcessor", () => {

 it("processes the files", () => {
   // createMockFileReader returns a `class MockFileReader`
   // that replicates the methods of FileReader
   window.FileReader = createMockFileReader(files)
   const processor = new JsonFileProcessor();
   processor.process(someFiles);

我在 JsonFileProcessor.process 方法 ReferenceError: FileReader is not defined 中遇到错误,但是如果我将 new FileReader() 替换为 new window.FileReader() 它会起作用

我已经坚持这个很久了!我正在使用 Stencil.js 和 运行 它附带的 Jest 设置。还有其他可用的 window 属性(因为我已经对其进行了调试和 console.log )

我知道我必须自己模拟 FileReader,但我很困惑为什么 util class 找不到模拟的 class,除非我专门使用 new window.FileReader()

事实证明,Stencil 的 jest 设置不包括 jsdom。 Stencil 使用精简版的 Puppeteer 进行单元测试 - windowdocument 属性可以通过返回的 page 对象访问模板的 newSpecPage()

因为我的测试是 运行 而没有 newSpecPage 我需要使用 global 对象来代替,例如global.FileReader = createMockFileReader(files)