Vue.js+Jest测试在VSCode中调试时断点映射异常问题排查
问题描述
使用VSCode 1.69.2调试Vue3项目的Jest单测时,在Vue源文件(如EventSummary.vue)设置的断点触发后,会跳转到同名的编译后文件,而非原始源码。
相关配置
package.json 片段
"devDependencies": { "@babel/core": "^7.12.16", "@babel/eslint-parser": "^7.12.16", "@babel/plugin-transform-modules-commonjs": "^7.18.2", "@vue/cli-plugin-babel": "^5.0.0", "@vue/cli-plugin-eslint": "~5.0.0", "@vue/cli-plugin-unit-jest": "~5.0.0", "@vue/cli-service": "^5.0.0", "@vue/compiler-sfc": "^3.0.0", "@vue/test-utils": "^2.0.0-rc.17", "@vue/vue3-jest": "^27.0.0", "eslint": "^8.18.0", "eslint-config-prettier": "^8.3.0", "eslint-import-resolver-alias": "^1.1.2", "eslint-plugin-import": "^2.26.0", "eslint-plugin-prettier": "^4.0.0", "eslint-plugin-promise": "^6.0.0", "eslint-plugin-vue": "^9.1.1", "markdownlint-cli": "^0.31.1", "mocked-env": "^1.3.5", "node-sass": "^6.0.1", "prettier": "^2.4.1", "sass-loader": "^10.1.0" }, "browserslist": [ "> 1%", "last 2 versions", "not dead" ], "jest": { "setupFiles": [ "<rootDir>/tests/env.js" ], "preset": "@vue/cli-plugin-unit-jest", "moduleNameMapper": { "^.+\\.css$": "<rootDir>/tests/css-stub.js", "d3": "<rootDir>/node_modules/d3/dist/d3.min.js" }, "moduleFileExtensions": [ "js", "json", "vue" ], "transform": { "^.+\\.js$": "babel-jest", "^.+\\.vue$": "@vue/vue3-jest" } }
launch.json 配置
{ "configurations": [ { "type": "node", "name": "vscode-jest-tests.v2", "request": "launch", "console": "integratedTerminal", "internalConsoleOptions": "neverOpen", "disableOptimisticBPs": true, "cwd": "${workspaceFolder}", "runtimeExecutable": "npm", "args": [ "test", "--", "--runInBand", "--watchAll=false", "--testNamePattern", "${jest.testNamePattern}", "--runTestsByPath", "${jest.testFile}" ] } ] }
解决方案
1. 配置Jest生成正确的Sourcemap
修改package.json中的jest配置,明确开启sourcemap生成,同时禁用覆盖率收集(避免干扰sourcemap):
"jest": { // 保留原有配置... "collectCoverage": false, "transform": { "^.+\\.js$": ["babel-jest", { "sourceMaps": "both" }], "^.+\\.vue$": ["@vue/vue3-jest", { "sourceMaps": "both" }] }, "testEnvironment": "jsdom" }
2. 调整VSCode调试配置
更新launch.json,添加sourcemap相关配置并禁用Jest缓存:
{ "configurations": [ { "type": "node", "name": "vscode-jest-tests.v2", "request": "launch", "console": "integratedTerminal", "internalConsoleOptions": "neverOpen", "disableOptimisticBPs": true, "cwd": "${workspaceFolder}", "runtimeExecutable": "npm", "args": [ "test", "--", "--runInBand", "--watchAll=false", "--testNamePattern", "${jest.testNamePattern}", "--runTestsByPath", "${jest.testFile}", "--no-cache" ], "sourceMaps": true, "outFiles": ["${workspaceFolder}/node_modules/.cache/jest/**/*"] } ] }
3. 检查Babel配置(若有单独的babel.config.js)
确保Babel开启sourcemap生成:
module.exports = { presets: ['@vue/cli-plugin-babel/preset'], sourceMaps: 'both', plugins: ['@babel/plugin-transform-modules-commonjs'] }
4. 清理Jest缓存
执行命令清理旧缓存,确保调试使用最新编译结果:
npx jest --clearCache
内容的提问来源于stack exchange,提问作者cyclocrossing
相关产品推荐
相关产品推荐

