You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Vue3项目Jest结合Babel测试报错:Cannot read properties of undefined (reading 'getCacheKey')求解决方案

解决Vue3+Jest+Babel单元测试中Cannot read properties of undefined (reading 'getCacheKey')的问题

这个错误大概率是Jest、vue3-jest和@vue/cli-plugin-unit-jest之间的版本不兼容导致的,结合你的依赖配置来看,核心问题就是版本匹配混乱,下面是具体的解决思路:

1. 统一Jest生态依赖的版本

你的package.json里存在明显的版本冲突点:

  • @vue/cli-plugin-unit-jest@4.5.x 原生适配的Jest版本是26.x,但你用了更高版本的jest@27.3.1
  • babel-jest@22.4.3 版本过于老旧,和Jest27完全不兼容
  • vue3-jest@27.0.0-alpha.1 是测试版,本身稳定性就差

建议把devDependencies里的相关依赖调整为以下版本(完美适配@vue/cli-plugin-unit-jest@4.x):

"devDependencies": {
  // ... 其他依赖保持不变
  "@vue/cli-plugin-unit-jest": "~4.5.0",
  "jest": "^26.6.3",
  "babel-jest": "^26.6.3",
  "vue3-jest": "^26.0.0"
}

2. 优化jest.config.js配置

@vue/cli-plugin-unit-jest的preset已经内置了Vue文件的转换规则,你可以尝试移除手动配置的Vue transform项,避免规则冲突:

const config = {
  preset: '@vue/cli-plugin-unit-jest',
  collectCoverage: true,
  transform: {
    '^.+\\.tsx?$': 'ts-jest',
    '^.+\\.jsx?$': 'babel-jest'
  },
  testMatch:["**/tests/Unit/*.spec.[jt]s?(x)"],
  verbose: true,
};
module.exports = config;

3. 清理依赖并重新安装

执行以下命令清理旧依赖缓存,确保新的版本依赖完全生效:

# 删除依赖文件夹和锁文件
rm -rf node_modules package-lock.json
# 重新安装依赖
npm install

完成以上步骤后再运行单元测试,应该就能解决这个getCacheKey的报错了。

内容的提问来源于stack exchange,提问作者user16859317

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.04.30 22:27:39