React应用测试Go JS PackedLayout时Jest报错:无法在模块外使用import语句
解决React + GoJS集成时Jest测试的import语法错误
问题分析
你遇到的错误源于GoJS的extensionsJSM/PackedLayout.js使用了ES模块的import语法,但Jest默认不会转译node_modules目录下的文件,导致无法识别该语法。你之前尝试的transformIgnorePatterns未生效,大概率是因为Create React App(CRA)的默认Jest配置覆盖了自定义设置,或是配置规则不够精确。
解决方案
方案1:通过CRA自定义Jest配置转译GoJS文件
CRA允许在package.json中添加jest字段覆盖部分配置,确保Jest转译GoJS相关文件:
- 在项目根目录的
package.json中添加以下配置:
{ "jest": { "transformIgnorePatterns": [ "/node_modules/(?!(gojs)/)" ] } }
该规则表示:不对node_modules下除gojs之外的文件跳过转译,让babel-jest处理GoJS的ES模块文件。
- 若同时使用
gojs-react,可将其也加入规则:
"transformIgnorePatterns": [ "/node_modules/(?!(gojs|gojs-react)/)" ]
- 重新运行测试命令:
yarn test
方案2:使用Craco覆盖CRA的默认配置(更灵活)
若package.json的配置仍不生效,推荐用craco完全控制CRA的配置:
- 安装craco依赖:
yarn add @craco/craco --dev
- 在项目根目录创建
craco.config.js文件:
module.exports = { jest: { configure: { transformIgnorePatterns: [ '/node_modules/(?!(gojs)/)' ] } } };
- 修改
package.json中的scripts命令,替换为craco的命令:
{ "scripts": { "start": "craco start", "build": "craco build", "test": "craco test" } }
- 重新执行测试:
yarn test
方案3:Mock GoJS组件(适合单元测试)
如果你的测试不需要验证GoJS图表的渲染逻辑,仅测试组件的其他功能,可直接mock GoJS相关模块,避免加载真实文件:
在测试文件(如App.test.tsx)顶部添加以下mock代码:
jest.mock('gojs', () => ({ __esModule: true, default: {}, // 若测试中需要用到GoJS的特定导出,可在此补充 })); jest.mock('gojs/extensionsJSM/PackedLayout', () => ({ __esModule: true, PackedLayout: jest.fn() })); jest.mock('gojs-react', () => ({ __esModule: true, ReactDiagram: jest.fn(() => null) }));
这样Jest会用模拟模块替代真实的GoJS文件,不会触发import语法错误。
内容的提问来源于stack exchange,提问作者Asad Dhorajiwala
相关产品推荐
相关产品推荐

