我正在尝试创建一个与 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)
其他测试工作正常,并且依赖项在其他地方捆绑时工作正常。
module.exports = {
preset: 'ts-jest',
testEnvironment: 'node',
};
"jest": "^26.6.3",
"ts-jest": "^26.5.2",
...
我可以采取什么措施来解决这个问题?
在 codesandbox 中添加了测试+配置(但无法让测试运行器拾取它)。完整的repo
经过一些测试,它终于可以使用此配置了:
module.exports = {
preset: 'ts-jest',
testEnvironment: 'jsdom',
};
{
"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
。
感谢您将
testEnvironment
更改为 jsdom
的提示。最初,这对我不起作用。但是,我注意到一些测试文件顶部有指令 @jest-environment node
。将其更改为 @jest-environment jsdom
后,测试按预期进行。
如果您遇到类似问题,请检查此指令是否在您的测试文件中并进行相应更新。
/**
* @jest-environment node -> @jest-environment jsdom
*/