typescript "参考错误:为React项目运行Jest测试时"未定义窗口

vcirk6k6  于 2023-01-06  发布在  TypeScript
关注(0)|答案(2)|浏览(204)

我有几个Jest测试,测试应用程序中与FirebaseUI完全无关的功能,也不需要浏览器窗口来执行。我在应用程序的其他不相关部分使用FirebaseUI。
话虽如此,当我尝试运行其中一个测试时,FirebaseUI抛出错误"ReferenceError: window is not defined",即使我没有调用任何与FirebaseUI相关或需要浏览器的代码。
我知道Jest测试在Node.js环境中运行,所以浏览器窗口根本不存在,但是,由于我的Jest测试不调用任何FirebaseUI代码,所以这不应该发生。
我该怎么做?有没有办法用Jest模拟一个虚拟的浏览器窗口?
下面是测试文件:

import '../../../../cbjs/setup_test'
import {getCenter, rgbaNormalizedToCSS, templateStructToNewCollage} from "./template_converter";
import {Point, Size} from "@piccollage/cbjs";
import {serverStringToStruct} from "../string_struct_converters";
import {ImageScrape} from "../../collage_editor/models/image_scrape";

// TODO: can't run tests from this file (Firebase error => window is not defined in ref_store constructor)

it("rgbaNormalizedToCSS works", () => {
  expect(rgbaNormalizedToCSS([0, 0.5, 0.3, 0.4]))
    .toBe("rgba(0, 128, 77, 0.4")
})

it("getCenter works", () => {
  expect(getCenter([0, 0], [100, 100]))
    .toBe(new Point(50, 50))
})

it("templateStructToNewCollage works (just a single ImageScrape)", () => {
  const struct = serverStringToStruct("../test_files/test.plist", true)

  console.log(struct)

  const collage = templateStructToNewCollage('0', struct)

  expect(collage.size$.value).toBe(new Size(300, 300))
  expect(collage.ownerId).toBe('0')
  expect(collage.backgroundURL$.value).toBe("photo-framework:/AAF82513-DA99-4F71-A371-7CCED92F4D52/L0/001")
  expect(collage.scrapes$.value.length).toBe(1)

  const scrape = collage.scrapes$.value[0]

  expect(scrape instanceof ImageScrape).toBeTruthy()
  expect(scrape.sizeBase$.value).toBe(new Size(300, 58.843537414965986))
  expect(scrape.positioning$.value.point).toBe(new Point(396.9729729729729, 518.6104045537717))
  expect(scrape.positioning$.value.rotation).toBe(0)
  expect(scrape.positioning$.value.scale).toBe(1.8990109511630093)
  expect(scrape.z$.value).toBe(1)
  expect((scrape as ImageScrape).imageSourceUrl$.value)
    .toBe("photo-framework:/687200F1-2A1C-40A0-BF76-B1D678C64799/L0/001")
})

以下是堆栈跟踪:

ReferenceError: window is not defined

      at node_modules/firebaseui/dist/npm.js:1:270
      at node_modules/firebaseui/dist/npm.js:26:301
      at Object.<anonymous> (node_modules/firebaseui/dist/npm.js:460:359)
      at Object.<anonymous> (node_modules/@piccollage/cbjs/dist/src/firebaseAuth.js:15:33)

文件 * jest.配置. js *

module.exports = {
  preset: 'ts-jest',
  testEnvironment: 'node',
  transformIgnorePatterns: [
    'node_modules/(?!(cbjs)/)',
  ],
  transform: {
    "^.+\\.(ts|js|jsx)$": "ts-jest"
  },
  moduleFileExtensions: ["ts", "tsx", "js", "jsx", "json", "node"],
};
wmtdaxz3

wmtdaxz31#

window是一个全局浏览器对象,在Node.js运行时使用Jest运行测试时没有定义它。通常Jest可以使用jsdom环境来运行,该环境将提供这些全局对象,在--env=jsdom上的命令行界面中使用就可以了。
至于库,您可能希望使用Jest配置完全模拟它。Mocking Node modules.这很简单,只需在项目根目录的适当位置创建一个文件,并在mocks目录中创建node_modules。

j91ykkif

j91ykkif2#

在终端尝试:

npx jest --env=jsdom

相关问题