【问题标题】:'globalThis' underfined for Jest test cases'globalThis' 未定义 Jest 测试用例
【发布时间】:2020-07-13 12:50:14
【问题描述】:

我在我的 React WebApp 中使用 globalThis 属性,特别是 globalThis.scrollTo(0,0)。

我正在使用 Jest 和 Enzyme 进行单元测试。

测试用例失败,因为它无法识别 globalThis 并说 'globalThis' 未定义。

有没有办法将 globalThis 引入测试,就像 jsdom 对窗口等所做的那样?

举例

-- abc.tsx--

const abc: React.FC<CustomProps> = props => {
useEffect(() => {
globalThis?.scrollTo(0,0);
}
}

-- abcTest.tsx--

wrapper = mount(<abc/>);

mount 产生“globalThis”未定义的错误

【问题讨论】:

  • 请分享您的一些代码,至少是您的测试代码。
  • 这可能有帮助,类似的错误被报告给 jsdom ("ReferenceError: globalThis is not defined") - github.com/jsdom/jsdom/issues/2795
  • 安装了什么版本的node、jest、jsdom?
  • Node 版本是 8,Jest 是 24,Jest 是 16。将 Node 更新到 12 可以工作吗?

标签: javascript reactjs jestjs enzyme jsdom


【解决方案1】:

globalThis 需要节点版本 12+。我使用n作为节点版本管理。

console.log(globalThis);

对于node/10.16.2,出现错误:

console.log(globalThis);
            ^

ReferenceError: globalThis is not defined

对于node/12.6.1,得到:

Object [global] {
  global: [Circular],
  clearInterval: [Function: clearInterval],
  clearTimeout: [Function: clearTimeout],
  setInterval: [Function: setInterval],
  setTimeout: [Function: setTimeout] { [Symbol(util.promisify.custom)]: [Function] },
  queueMicrotask: [Function: queueMicrotask],
  clearImmediate: [Function: clearImmediate],
  setImmediate: [Function: setImmediate] {
    [Symbol(util.promisify.custom)]: [Function]
  }
}

【讨论】:

  • 我正在使用版本节点 15X 并且有相同的错误...
  • 我的 Angular 应用程序在 14.17.6 和 16.18.0 收到此错误
猜你喜欢
  • 2021-04-24
  • 2021-06-09
  • 1970-01-01
  • 2021-06-17
  • 2022-06-30
  • 2017-07-20
  • 2018-02-26
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多