使用Projen创建的React库Jest测试报错:找不到react/jsx-runtime
解决Projen React组件库测试时找不到
react/jsx-runtime的问题 我用Projen搭建了一个要发布到NPM的React组件库,把React和React-dom配置成了peer依赖+开发依赖,项目能正常编译,在其他React项目里也能用。但执行npx projen test时报错:Cannot find module 'react/jsx-runtime' from 'src/react/context/MyContext.tsx'。要求不能把React移到生产依赖,解决这个测试问题。
现有配置
.projenrc.ts
import { typescript } from 'projen'; import { NpmAccess, TypeScriptJsxMode } from 'projen/lib/javascript'; const project = new typescript.TypeScriptProject({ defaultReleaseBranch: 'main', name: 'NAME', projenrcTs: true, releaseToNpm: true, // Npm publishing npmAccess: NpmAccess.PUBLIC, packageName: 'PACKAGE-NAME', peerDeps: [ 'react@^16.8.0 || ^17.0.0 || ^18.0.0', 'react-dom@^16.8.0 || ^17.0.0 || ^18.0.0', ], /* Dependencies */ devDeps: [ 'react@^18.2.0', 'react-dom@^18.2.0', '@types/react', '@types/react-dom', ], /* Extending tsconfig to accept .tsx files and JSX */ tsconfig: { compilerOptions: { jsx: TypeScriptJsxMode.REACT_JSX, }, include: ['src/**/*.tsx'], }, tsconfigDev: { compilerOptions: { jsx: TypeScriptJsxMode.REACT_JSX, }, include: ['src/**/*.tsx'], }, }); project.synth();
Projen自动生成的package.json中的Jest配置
{ ... "jest": { "testMatch": [ "<rootDir>/src/**/__tests__/**/*.ts?(x)", "<rootDir>/(test|src)/**/*(*.)@(spec|test).ts?(x)" ], "clearMocks": true, "collectCoverage": true, "coverageReporters": [ "json", "lcov", "clover", "cobertura", "text" ], "coverageDirectory": "coverage", "coveragePathIgnorePatterns": [ "/node_modules/" ], "testPathIgnorePatterns": [ "/node_modules/" ], "watchPathIgnorePatterns": [ "/node_modules/" ], "reporters": [ "default", [ "jest-junit", { "outputDirectory": "test-reports" } ] ], "preset": "ts-jest", "globals": { "ts-jest": { "tsconfig": "tsconfig.dev.json" } } }, ... }
解决方案
核心原因是Jest在测试时没有正确识别React的JSX运行时,虽然React已经装在devDeps里,但需要给Jest配置明确的模块解析规则,或者调整ts-jest的处理方式。
方法1:给Jest添加moduleNameMapper配置
修改.projenrc.ts,在project定义后手动扩展Jest配置,明确映射React相关模块:
// 扩展Jest配置,指定React模块的查找路径 project.jest?.addConfig('moduleNameMapper', { '^react/jsx-runtime$': 'react/jsx-runtime', '^react$': 'react', '^react-dom$': 'react-dom', });
这样Jest会直接从node_modules的dev依赖中找到对应模块,解决找不到的问题。
方法2:调整ts-jest的JSX处理模式
如果方法1无效,可以让ts-jest把JSX转译成传统的React.createElement调用,避免依赖react/jsx-runtime:
修改.projenrc.ts中的tsconfigDev:
tsconfigDev: { compilerOptions: { // 将JSX模式从REACT_JSX改为REACT jsx: TypeScriptJsxMode.REACT, }, include: ['src/**/*.tsx'], },
同时确保Jest使用修改后的配置:
project.jest?.addConfig('globals.ts-jest.tsconfig', 'tsconfig.dev.json');
方法3:对齐@types/react与React的版本
devDeps中React是18.2.0,建议给@types/react指定对应版本,避免类型不一致引发的间接问题:
devDeps: [ 'react@^18.2.0', 'react-dom@^18.2.0', '@types/react@^18.2.0', '@types/react-dom@^18.2.0', ],
最后同步配置并测试
修改完.projenrc.ts后,执行以下命令让Projen重新生成配置文件:
npx projen
然后运行测试:
npx projen test
内容的提问来源于stack exchange,提问作者70ny
相关产品推荐
相关产品推荐

