Babel别名适用于测试文件本身,但不适用于vue文件中的导入。
我遇到类似error when jest try import file in vue file
的错误我将moduleNameMapper添加到玩笑的配置,但只有当我删除babel-plugin-module-resolver并在webpack中添加别名时,他才起作用。这个解决方案不适合我,因为我们所有的项目都有相同的别名指示方式
moduleNameMapper: {
"^~/(.*)$": "<rootDir>/src/$1"
},
recovery.test.js
import { wrap } from '~/utils/test';
import recovery from '~/popup/router/pages/recovery/recovery';
import captcha from '~/components/captcha/captcha';
import ELInput from 'element-ui/lib/input';
recovery.vue
import punycode from 'punycode';
import { mapActions, mapState } from 'vuex';
import captcha from '~/components/captcha/captcha';
import { RECOVERY_PASSWORD, RECOVERY_PASSWORD_SUCCESS, RECOVERY_PASSWORD_FAILURE
} from '~/store/recovery/events';
import ssid from '~/mixins/ssid';
import { w3cValidateEmail, getConfig } from '~/helpers/index';
.babelrc
{
"plugins": [
"@babel/plugin-proposal-optional-chaining",
["module-resolver", {
"alias": {
"~": "./src"
}
}]
],
"presets": [
["@babel/preset-env", {
"useBuiltIns": "usage",
"targets": {
"browsers": ["> 0.25%", "not ie 11", "not op_mini all"]
}
}]
],
"env": {
"test": {
"presets": [
["env", { "targets": { "node": "current" }}]
]
}
}
}
jest.config.js
module.exports = {
setupFiles: [
"./jest.setup.js"
],
moduleFileExtensions: [
"js",
"vue"
],
transform: {
"^.+\\.js$": "<rootDir>/node_modules/babel-jest",
".*\\.(vue)$": "<rootDir>/node_modules/vue-jest"
},
testPathIgnorePatterns: [
'<rootDir>/initTest.js',
'<rootDir>/utils',
'<rootDir>/node_modules'
],
testMatch: [
"**/*.test.js"
],
collectCoverage: true,
collectCoverageFrom: [
"**/src/components/**/*.vue",
"**/src/options/**/**/*.vue",
"**/src/helpers/index.js",
"**/src/popup/router/pages/**/**.vue",
],
coveragePathIgnorePatterns: [
"src/popup/router/pages/Index.vue"
],
coverageThreshold: {
global: {
statements: 50,
branches: 20,
lines: 50,
functions: 40,
},
},
};
答案 0 :(得分:0)
我刚刚解决了这个问题,所以如果有人在搜索这个问题时遇到这个问题,这里是问题的原因和我的解决方案。
.babelrc module-resolver
覆盖 jest moduleNameMapper
您可以在除 test 之外的任何 NODE_ENV
中使用 babel 模块解析器,因此我们在运行 jest 测试时只会使用 moduleNameMapper
。
我们可以在 babel 中通过将 .babelrc 转换为 .babelrc.js 并检查 NODE_ENV
中的 process.env
如果它等于测试来完成此操作,不要将 module-resolver
推送到插件.