Vite+Vue3+TypeScript项目Jest报错:找不到ts-jest指定模块路径
解决Vite+Vue3+TypeScript项目中Jest报错“Cannot find module 'ts-jest/dist/config/config-set'”
问题根源
这个错误是Jest生态依赖版本不兼容导致的:
- 你使用了Jest 29.x版本,但
@vue/vue3-jest和babel-jest停留在27.x版本,这两个包与Jest 29存在兼容性冲突,会导致ts-jest无法正确加载内部模块。 ts-jest29.x需要匹配同主版本的Jest,但配套的Vue测试工具版本未同步升级,直接引发模块查找失败。
解决方案步骤
1. 卸载冲突依赖
先移除当前版本不匹配的测试相关包:
npm uninstall jest ts-jest @vue/vue3-jest babel-jest @types/jest
2. 安装版本匹配的依赖
安装与Jest 29完全兼容的全套测试依赖:
npm install -D jest@29 ts-jest@29 @vue/vue3-jest@29 @types/jest@29 babel-jest@29
注意:测试工具属于开发依赖,需放在
devDependencies中(之前你将部分测试依赖放在了dependencies,建议调整)
3. 更新package.json配置
调整后的package.json相关依赖部分参考如下:
"dependencies": { "@vue/composition-api": "^1.7.1", "fuzzysort": "^2.0.1", "vue": "^3.2.37" }, "devDependencies": { "@types/jest": "^29.5.0", "@typescript-eslint/eslint-plugin": "^5.38.1", "@typescript-eslint/parser": "^5.38.1", "@vitejs/plugin-vue": "^3.1.0", "@vue/eslint-config-typescript": "^11.0.2", "@vue/test-utils": "^2.4.0", "@vue/vue3-jest": "^29.2.6", "babel-jest": "^29.5.0", "eslint": "^8.22.0", "eslint-plugin-vue": "^9.5.1", "jest": "^29.5.0", "sass": "^1.55.0", "sass-loader": "^13.0.2", "ts-jest": "^29.1.0", "typescript": "^4.8.4", "vite": "^3.1.0", "vue-tsc": "^0.40.4" }, "moduleDirectories": [ "node_modules", "src" ]
4. 优化Jest配置
你的jest.config.js可添加preset: 'ts-jest'简化配置,同时补充Vue3测试必需的jsdom环境:
module.exports = { preset: 'ts-jest', moduleFileExtensions: [ 'js', 'ts', 'json', 'vue' ], transform: { '^.+\\.ts$': 'ts-jest', '^.+\\.vue$': '@vue/vue3-jest' }, testMatch: [ '**/(src)/**/*.spec.(js|jsx|ts|tsx)|**/__tests__/*.(js|jsx|ts|tsx)', ], testEnvironment: 'jsdom' }
5. 清理缓存并重新测试
执行命令清除Jest旧缓存,避免干扰:
npx jest --clearCache
随后运行测试:
npx jest
关键注意事项
- 必须保证
jest、ts-jest、@vue/vue3-jest、babel-jest的主版本号完全一致(比如都是29.x),这是Jest生态兼容的核心要求。 - 若仍报
jsdom相关错误,可手动安装:npm install -D jsdom
内容的提问来源于stack exchange,提问作者Jean Grimbert
相关产品推荐
相关产品推荐

