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

Vue3+TS+Jest项目测试报TypeError: sourceMaps.get is not a function如何解决

问题根因

TypeError: sourceMaps.get is not a function报错的核心原因是项目内jest相关依赖版本不一致,尤其是@jest/source-map版本和其他jest核心包版本不匹配,叠加ts-jest、TypeScript、Vue3 Jest transformer的版本适配冲突导致。

可行适配方案

第一步:统一依赖版本

删除原有node_modules、package-lock.json/yarn.lock后,在package.json的devDependencies中固定以下兼容版本组合:

  • vue: ^3.2.31
  • typescript: ~4.5.5
  • jest: ^27.5.1
  • ts-jest: ^27.1.5
  • babel-jest: ^27.5.1
  • @vue/test-utils: ^2.0.0-rc.17
  • @vue/cli-plugin-unit-jest: ~5.0.4
  • @vue/cli-plugin-typescript: ~5.0.4
  • vue-jest: ^5.0.0-alpha.10
  • @jest/source-map: ^27.5.1

重新安装依赖即可避免版本缓存导致的兼容性问题。

第二步:修正配置文件

jest.config.js

module.exports = {
  preset: '@vue/cli-plugin-unit-jest/presets/typescript-and-babel',
  transform: {
    '^.+\\.vue$': 'vue-jest'
  },
  testEnvironment: 'jsdom',
  moduleFileExtensions: ['js', 'ts', 'vue', 'json'],
  moduleNameMapper: {
    '^@/(.*)$': '<rootDir>/src/$1'
  },
  globals: {
    'ts-jest': {
      tsconfig: '<rootDir>/tsconfig.json',
      babelConfig: true
    }
  },
  coverageReporters: ['html', 'text-summary']
}

babel.config.js

module.exports = {
  presets: [
    '@vue/cli-plugin-babel/preset',
    ['@babel/preset-typescript', { allExtensions: true, isTSX: false }]
  ]
}

tsconfig.json

{
  "compilerOptions": {
    "target": "esnext",
    "module": "esnext",
    "strict": true,
    "jsx": "preserve",
    "moduleResolution": "node",
    "skipLibCheck": true,
    "esModuleInterop": true,
    "allowSyntheticDefaultImports": true,
    "forceConsistentCasingInFileNames": true,
    "useDefineForClassFields": true,
    "sourceMap": true,
    "baseUrl": ".",
    "paths": {
      "@/*": ["src/*"]
    },
    "lib": ["esnext", "dom", "dom.iterable", "scripthost"]
  },
  "include": ["src/**/*.ts", "src/**/*.vue", "tests/**/*.ts"]
}

第三步:测试用例验证

参考以下最简用例验证配置有效性:

import { mount } from '@vue/test-utils'
import HelloWorld from '@/components/HelloWorld.vue'

test('mount component', () => {
  const wrapper = mount(HelloWorld, {
    props: { msg: 'test' }
  })
  expect(wrapper.text()).toContain('test')
})
踩坑补充
  • 所有jest生态依赖大版本必须完全统一,禁止跨大版本混用(如部分依赖27.x、部分依赖28.x)
  • 无需将TypeScript降级至3.9版本,ts-jest 27.x完整支持TypeScript 4.0~4.6版本,此前的不支持提示是因为ts-jest版本过低
  • 调整配置后运行测试前,可执行npx jest --clearCache清除缓存避免异常

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.06 12:42:00