【问题标题】:Jest fails with 'self is not defined' when importing react-diagrams导入反应图时,Jest 因“未定义自我”而失败
【发布时间】:2021-07-26 03:52:48
【问题描述】:

我正在尝试创建一个与 npm 依赖项交互的基本玩笑测试:react-diagrams

失败的测试

import { DiagramModel } from '@projectstorm/react-diagrams'

test('importing react diagrams', () => {
    let x = DiagramModel
});

仅引用 DiagramModel 类会导致此错误:

    ReferenceError: self is not defined

    > 1 | import { DiagramModel } from '@projectstorm/react-diagrams'
        | ^
      2 |
      3 | test('importing react diagrams', () => {
      4 |     let x = DiagramModel

      at Object.<anonymous> (node_modules/@projectstorm/react-diagrams/dist/index.umd.js:1:331)
      at Object.<anonymous> (tests/DiagramModel.test.ts:1:1)

其他测试工作正常,并且依赖项在捆绑到其他地方时工作正常。

jest.config.js

module.exports = {
  preset: 'ts-jest',
  testEnvironment: 'node',
};

package.json

"jest": "^26.6.3",
"ts-jest": "^26.5.2",
...

有什么想法可以解决这个问题吗?

复制

codesandbox 中添加了测试+ 配置(但无法让测试运行程序获取它)。完整的repo

【问题讨论】:

标签: reactjs jestjs ts-jest


【解决方案1】:

经过一些测试,它终于可以使用这个配置了:

jest.config.js

module.exports = {
  preset: 'ts-jest',
  testEnvironment: 'jsdom',
};

package.json :

{
  "name": "jest-test",
  "version": "1.0.0",
  "main": "index.js",
  "license": "MIT",
  "devDependencies": {
    "jest": "^26.6.3",
    "ts-jest": "^26.5.2"
  },
  "scripts": {
    "test": "jest"
  },
  "dependencies": {
    "@emotion/react": "^11.1.5",
    "@emotion/styled": "^11.3.0",
    "@projectstorm/react-canvas-core": "^6.5.2",
    "@projectstorm/react-diagrams": "^6.5.2",
    "@projectstorm/react-diagrams-routing": "^6.5.2",
    "closest": "^0.0.1",
    "dagre": "^0.8.5",
    "pathfinding": "^0.4.18",
    "paths-js": "^0.4.11",
    "react": "^17.0.2",
    "resize-observer-polyfill": "^1.5.1"
  }
}

您错过了 @projectstorm/react-diagramsreact 库并且它需要 dom 环境而不是 nodejs 的事实。

【讨论】:

  • 我更新了我的答案以测试它是否与 Jest testEnvironment 相关,如果它有效,请告诉我!
  • 救命稻草!我可以在 24 小时内奖励赏金 :)
猜你喜欢
  • 1970-01-01
  • 2021-02-01
  • 1970-01-01
  • 2020-02-08
  • 1970-01-01
  • 1970-01-01
  • 2017-11-19
  • 2022-12-07
  • 2018-06-03
相关资源
最近更新 更多