导入反应图时,Jest 因“self is not Defined”而失败

问题描述 投票:0回答:2

我正在尝试创建一个与 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
2个回答
13
投票

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

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-diagrams
是一个
react
库,它需要
dom
环境而不是
nodejs


0
投票

感谢您将

testEnvironment
更改为
jsdom
的提示。最初,这对我不起作用。但是,我注意到一些测试文件顶部有指令
@jest-environment node
。将其更改为
@jest-environment jsdom
后,测试按预期进行。

如果您遇到类似问题,请检查此指令是否在您的测试文件中并进行相应更新。

/**
 * @jest-environment node -> @jest-environment jsdom
 */
© www.soinside.com 2019 - 2024. All rights reserved.